text
stringlengths 5
1.04M
|
|---|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_DOMAINS_GIS_IO_WKT_WRITE_WKT_HPP
#define BOOST_GEOMETRY_DOMAINS_GIS_IO_WKT_WRITE_WKT_HPP
#include <ostream>
#include <string>
#include <boost/array.hpp>
#include <boost/concept/assert.hpp>
#include <boost/range.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/geometry/algorithms/assign.hpp>
#include <boost/geometry/algorithms/convert.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
#include <boost/geometry/geometries/ring.hpp>
#include <boost/geometry/domains/gis/io/wkt/detail/wkt.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace wkt
{
template <typename P, int I, int Count>
struct stream_coordinate
{
template <typename Char, typename Traits>
static inline void apply(std::basic_ostream<Char, Traits>& os, P const& p)
{
os << (I > 0 ? " " : "") << get<I>(p);
stream_coordinate<P, I + 1, Count>::apply(os, p);
}
};
template <typename P, int Count>
struct stream_coordinate<P, Count, Count>
{
template <typename Char, typename Traits>
static inline void apply(std::basic_ostream<Char, Traits>&, P const&)
{}
};
struct prefix_linestring_par
{
static inline const char* apply() { return "LINESTRING("; }
};
struct prefix_ring_par_par
{
// Note, double parentheses are intentional, indicating WKT ring begin/end
static inline const char* apply() { return "POLYGON(("; }
};
struct opening_parenthesis
{
static inline const char* apply() { return "("; }
};
struct closing_parenthesis
{
static inline const char* apply() { return ")"; }
};
struct double_closing_parenthesis
{
static inline const char* apply() { return "))"; }
};
/*!
\brief Stream points as \ref WKT
*/
template <typename Point, typename Policy>
struct wkt_point
{
template <typename Char, typename Traits>
static inline void apply(std::basic_ostream<Char, Traits>& os, Point const& p)
{
os << Policy::apply() << "(";
stream_coordinate<Point, 0, dimension<Point>::type::value>::apply(os, p);
os << ")";
}
};
/*!
\brief Stream ranges as WKT
\note policy is used to stream prefix/postfix, enabling derived classes to override this
*/
template <typename Range, typename PrefixPolicy, typename SuffixPolicy>
struct wkt_range
{
template <typename Char, typename Traits>
static inline void apply(std::basic_ostream<Char, Traits>& os,
Range const& range)
{
typedef typename boost::range_iterator<Range const>::type iterator_type;
bool first = true;
os << PrefixPolicy::apply();
// TODO: check EMPTY here
for (iterator_type it = boost::begin(range);
it != boost::end(range);
++it)
{
os << (first ? "" : ",");
stream_coordinate
<
point_type, 0, dimension<point_type>::type::value
>::apply(os, *it);
first = false;
}
os << SuffixPolicy::apply();
}
private:
typedef typename boost::range_value<Range>::type point_type;
};
/*!
\brief Stream sequence of points as WKT-part, e.g. (1 2),(3 4)
\note Used in polygon, all multi-geometries
*/
template <typename Range>
struct wkt_sequence
: wkt_range
<
Range,
opening_parenthesis,
closing_parenthesis
>
{};
template <typename Polygon, typename PrefixPolicy>
struct wkt_poly
{
template <typename Char, typename Traits>
static inline void apply(std::basic_ostream<Char, Traits>& os,
Polygon const& poly)
{
typedef typename ring_type<Polygon const>::type ring;
os << PrefixPolicy::apply();
// TODO: check EMPTY here
os << "(";
wkt_sequence<ring>::apply(os, exterior_ring(poly));
typename interior_return_type<Polygon const>::type rings
= interior_rings(poly);
for (BOOST_AUTO_TPL(it, boost::begin(rings)); it != boost::end(rings); ++it)
{
os << ",";
wkt_sequence<ring>::apply(os, *it);
}
os << ")";
}
};
template <typename Box>
struct wkt_box
{
typedef typename point_type<Box>::type point_type;
template <typename Char, typename Traits>
static inline void apply(std::basic_ostream<Char, Traits>& os,
Box const& box)
{
// Convert to ring, then stream
typedef model::ring<point_type> ring_type;
ring_type ring;
geometry::convert(box, ring);
os << "POLYGON(";
wkt_sequence<ring_type>::apply(os, ring);
os << ")";
}
private:
inline wkt_box()
{
// Only streaming of boxes with two dimensions is support, otherwise it is a polyhedron!
//assert_dimension<B, 2>();
}
};
template <typename Segment>
struct wkt_segment
{
typedef typename point_type<Segment>::type point_type;
template <typename Char, typename Traits>
static inline void apply(std::basic_ostream<Char, Traits>& os,
Segment const& segment)
{
// Convert to two points, then stream
typedef boost::array<point_type, 2> sequence;
sequence points;
geometry::detail::assign_point_from_index<0>(segment, points[0]);
geometry::detail::assign_point_from_index<1>(segment, points[1]);
// In Boost.Geometry a segment is represented
// in WKT-format like (for 2D): LINESTRING(x y,x y)
os << "LINESTRING";
wkt_sequence<sequence>::apply(os, points);
}
private:
inline wkt_segment()
{}
};
}} // namespace detail::wkt
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template <typename Tag, typename Geometry>
struct wkt
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_YET_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE
, (types<Geometry>)
);
};
template <typename Point>
struct wkt<point_tag, Point>
: detail::wkt::wkt_point
<
Point,
detail::wkt::prefix_point
>
{};
template <typename Linestring>
struct wkt<linestring_tag, Linestring>
: detail::wkt::wkt_range
<
Linestring,
detail::wkt::prefix_linestring_par,
detail::wkt::closing_parenthesis
>
{};
/*!
\brief Specialization to stream a box as WKT
\details A "box" does not exist in WKT.
It is therefore streamed as a polygon
*/
template <typename Box>
struct wkt<box_tag, Box>
: detail::wkt::wkt_box<Box>
{};
template <typename Segment>
struct wkt<segment_tag, Segment>
: detail::wkt::wkt_segment<Segment>
{};
/*!
\brief Specialization to stream a ring as WKT
\details A ring or "linear_ring" does not exist in WKT.
A ring is equivalent to a polygon without inner rings
It is therefore streamed as a polygon
*/
template <typename Ring>
struct wkt<ring_tag, Ring>
: detail::wkt::wkt_range
<
Ring,
detail::wkt::prefix_ring_par_par,
detail::wkt::double_closing_parenthesis
>
{};
/*!
\brief Specialization to stream polygon as WKT
*/
template <typename Polygon>
struct wkt<polygon_tag, Polygon>
: detail::wkt::wkt_poly
<
Polygon,
detail::wkt::prefix_polygon
>
{};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
/*!
\brief Generic geometry template manipulator class, takes corresponding output class from traits class
\ingroup wkt
\details Stream manipulator, streams geometry classes as \ref WKT streams
\par Example:
Small example showing how to use the wkt class
\dontinclude doxygen_1.cpp
\skip example_as_wkt_point
\line {
\until }
*/
template <typename Geometry>
class wkt_manipulator
{
public:
inline wkt_manipulator(Geometry const& g)
: m_geometry(g)
{}
template <typename Char, typename Traits>
inline friend std::basic_ostream<Char, Traits>& operator<<(
std::basic_ostream<Char, Traits>& os,
wkt_manipulator const& m)
{
dispatch::wkt
<
typename tag<Geometry>::type,
Geometry
>::apply(os, m.m_geometry);
os.flush();
return os;
}
private:
Geometry const& m_geometry;
};
/*!
\brief Main WKT-streaming function
\ingroup wkt
\par Example:
Small example showing how to use the wkt helper function
\dontinclude doxygen_1.cpp
\skip example_as_wkt_vector
\line {
\until }
*/
template <typename Geometry>
inline wkt_manipulator<Geometry> wkt(Geometry const& geometry)
{
concept::check<Geometry const>();
return wkt_manipulator<Geometry>(geometry);
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_DOMAINS_GIS_IO_WKT_WRITE_WKT_HPP
|
/***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
//=========================================================
// Default behaviors.
//=========================================================
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "entities/NPCs/Monsters.h"
#include "entities/NPCs/Schedule.h"
#include "DefaultAI.h"
#include "entities/CSoundEnt.h"
#include "nodes/Nodes.h"
#include "entities/NPCs/scripted/Scripted.h"
//=========================================================
// Fail
//=========================================================
Task_t tlFail[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT, (float)2 },
{ TASK_WAIT_PVS, (float)0 },
};
Schedule_t slFail[] =
{
{
tlFail,
ARRAYSIZE ( tlFail ),
bits_COND_CAN_ATTACK,
0,
"Fail"
},
};
//=========================================================
// Idle Schedules
//=========================================================
Task_t tlIdleStand1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT, (float)5 },// repick IDLESTAND every five seconds. gives us a chance to pick an active idle, fidget, etc.
};
Schedule_t slIdleStand[] =
{
{
tlIdleStand1,
ARRAYSIZE ( tlIdleStand1 ),
bits_COND_NEW_ENEMY |
bits_COND_SEE_FEAR |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND |
bits_COND_SMELL_FOOD |
bits_COND_SMELL |
bits_COND_PROVOKED,
bits_SOUND_COMBAT |// sound flags
bits_SOUND_WORLD |
bits_SOUND_PLAYER |
bits_SOUND_DANGER |
bits_SOUND_MEAT |// scents
bits_SOUND_CARCASS |
bits_SOUND_GARBAGE,
"IdleStand"
},
};
Schedule_t slIdleTrigger[] =
{
{
tlIdleStand1,
ARRAYSIZE ( tlIdleStand1 ),
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE,
0,
"Idle Trigger"
},
};
Task_t tlIdleWalk1[] =
{
{ TASK_WALK_PATH, (float)9999 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
};
Schedule_t slIdleWalk[] =
{
{
tlIdleWalk1,
ARRAYSIZE ( tlIdleWalk1 ),
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND |
bits_COND_SMELL_FOOD |
bits_COND_SMELL |
bits_COND_PROVOKED,
bits_SOUND_COMBAT |// sound flags
bits_SOUND_MEAT |// scents
bits_SOUND_CARCASS |
bits_SOUND_GARBAGE,
"Idle Walk"
},
};
//=========================================================
// Ambush - monster stands in place and waits for a new
// enemy, or chance to attack an existing enemy.
//=========================================================
Task_t tlAmbush[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT_INDEFINITE, (float)0 },
};
Schedule_t slAmbush[] =
{
{
tlAmbush,
ARRAYSIZE ( tlAmbush ),
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_PROVOKED,
0,
"Ambush"
},
};
//=========================================================
// ActiveIdle schedule - !!!BUGBUG - if this schedule doesn't
// complete on its own, the monster's HintNode will not be
// cleared, and the rest of the monster's group will avoid
// that node because they think the group member that was
// previously interrupted is still using that node to active
// idle.
///=========================================================
Task_t tlActiveIdle[] =
{
{ TASK_FIND_HINTNODE, (float)0 },
{ TASK_GET_PATH_TO_HINTNODE, (float)0 },
{ TASK_STORE_LASTPOSITION, (float)0 },
{ TASK_WALK_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_FACE_HINTNODE, (float)0 },
{ TASK_PLAY_ACTIVE_IDLE, (float)0 },
{ TASK_GET_PATH_TO_LASTPOSITION,(float)0 },
{ TASK_WALK_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_CLEAR_LASTPOSITION, (float)0 },
{ TASK_CLEAR_HINTNODE, (float)0 },
};
Schedule_t slActiveIdle[] =
{
{
tlActiveIdle,
ARRAYSIZE( tlActiveIdle ),
bits_COND_NEW_ENEMY |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_PROVOKED |
bits_COND_HEAR_SOUND,
bits_SOUND_COMBAT |
bits_SOUND_WORLD |
bits_SOUND_PLAYER |
bits_SOUND_DANGER,
"Active Idle"
}
};
//=========================================================
// Wake Schedules
//=========================================================
Task_t tlWakeAngry1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_SOUND_WAKE, (float)0 },
{ TASK_FACE_IDEAL, (float)0 },
};
Schedule_t slWakeAngry[] =
{
{
tlWakeAngry1,
ARRAYSIZE ( tlWakeAngry1 ),
0,
0,
"Wake Angry"
}
};
//=========================================================
// AlertFace Schedules
//=========================================================
Task_t tlAlertFace1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_FACE_IDEAL, (float)0 },
};
Schedule_t slAlertFace[] =
{
{
tlAlertFace1,
ARRAYSIZE ( tlAlertFace1 ),
bits_COND_NEW_ENEMY |
bits_COND_SEE_FEAR |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_PROVOKED,
0,
"Alert Face"
},
};
//=========================================================
// AlertSmallFlinch Schedule - shot, but didn't see attacker,
// flinch then face
//=========================================================
Task_t tlAlertSmallFlinch[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_REMEMBER, (float)bits_MEMORY_FLINCHED },
{ TASK_SMALL_FLINCH, (float)0 },
{ TASK_SET_SCHEDULE, (float)SCHED_ALERT_FACE },
};
Schedule_t slAlertSmallFlinch[] =
{
{
tlAlertSmallFlinch,
ARRAYSIZE ( tlAlertSmallFlinch ),
0,
0,
"Alert Small Flinch"
},
};
//=========================================================
// AlertIdle Schedules
//=========================================================
Task_t tlAlertStand1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT, (float)20 },
{ TASK_SUGGEST_STATE, (float)MONSTERSTATE_IDLE },
};
Schedule_t slAlertStand[] =
{
{
tlAlertStand1,
ARRAYSIZE ( tlAlertStand1 ),
bits_COND_NEW_ENEMY |
bits_COND_SEE_ENEMY |
bits_COND_SEE_FEAR |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_PROVOKED |
bits_COND_SMELL |
bits_COND_SMELL_FOOD |
bits_COND_HEAR_SOUND,
bits_SOUND_COMBAT |// sound flags
bits_SOUND_WORLD |
bits_SOUND_PLAYER |
bits_SOUND_DANGER |
bits_SOUND_MEAT |// scent flags
bits_SOUND_CARCASS |
bits_SOUND_GARBAGE,
"Alert Stand"
},
};
//=========================================================
// InvestigateSound - sends a monster to the location of the
// sound that was just heard, to check things out.
//=========================================================
Task_t tlInvestigateSound[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_STORE_LASTPOSITION, (float)0 },
{ TASK_GET_PATH_TO_BESTSOUND, (float)0 },
{ TASK_FACE_IDEAL, (float)0 },
{ TASK_WALK_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_IDLE },
{ TASK_WAIT, (float)10 },
{ TASK_GET_PATH_TO_LASTPOSITION,(float)0 },
{ TASK_WALK_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_CLEAR_LASTPOSITION, (float)0 },
};
Schedule_t slInvestigateSound[] =
{
{
tlInvestigateSound,
ARRAYSIZE ( tlInvestigateSound ),
bits_COND_NEW_ENEMY |
bits_COND_SEE_FEAR |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"InvestigateSound"
},
};
//=========================================================
// CombatIdle Schedule
//=========================================================
Task_t tlCombatStand1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT_INDEFINITE, (float)0 },
};
Schedule_t slCombatStand[] =
{
{
tlCombatStand1,
ARRAYSIZE ( tlCombatStand1 ),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_CAN_ATTACK,
0,
"Combat Stand"
},
};
//=========================================================
// CombatFace Schedule
//=========================================================
Task_t tlCombatFace1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_FACE_ENEMY, (float)0 },
};
Schedule_t slCombatFace[] =
{
{
tlCombatFace1,
ARRAYSIZE ( tlCombatFace1 ),
bits_COND_CAN_ATTACK |
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD,
0,
"Combat Face"
},
};
//=========================================================
// Standoff schedule. Used in combat when a monster is
// hiding in cover or the enemy has moved out of sight.
// Should we look around in this schedule?
//=========================================================
Task_t tlStandoff[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_SET_ACTIVITY, (float)ACT_IDLE },
{ TASK_WAIT_FACE_ENEMY, (float)2 },
};
Schedule_t slStandoff[] =
{
{
tlStandoff,
ARRAYSIZE ( tlStandoff ),
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2 |
bits_COND_ENEMY_DEAD |
bits_COND_NEW_ENEMY |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"Standoff"
}
};
//=========================================================
// Arm weapon (draw gun)
//=========================================================
Task_t tlArmWeapon[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_PLAY_SEQUENCE, (float) ACT_ARM }
};
Schedule_t slArmWeapon[] =
{
{
tlArmWeapon,
ARRAYSIZE ( tlArmWeapon ),
0,
0,
"Arm Weapon"
}
};
//=========================================================
// reload schedule
//=========================================================
Task_t tlReload[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_PLAY_SEQUENCE, float(ACT_RELOAD) },
};
Schedule_t slReload[] =
{
{
tlReload,
ARRAYSIZE ( tlReload ),
bits_COND_HEAVY_DAMAGE,
0,
"Reload"
}
};
//=========================================================
// Attack Schedules
//=========================================================
// primary range attack
Task_t tlRangeAttack1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_RANGE_ATTACK1, (float)0 },
};
Schedule_t slRangeAttack1[] =
{
{
tlRangeAttack1,
ARRAYSIZE ( tlRangeAttack1 ),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED |
bits_COND_NO_AMMO_LOADED |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"Range Attack1"
},
};
// secondary range attack
Task_t tlRangeAttack2[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_RANGE_ATTACK2, (float)0 },
};
Schedule_t slRangeAttack2[] =
{
{
tlRangeAttack2,
ARRAYSIZE ( tlRangeAttack2 ),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"Range Attack2"
},
};
// primary melee attack
Task_t tlPrimaryMeleeAttack1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_MELEE_ATTACK1, (float)0 },
};
Schedule_t slPrimaryMeleeAttack[] =
{
{
tlPrimaryMeleeAttack1,
ARRAYSIZE ( tlPrimaryMeleeAttack1 ),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED,
0,
"Primary Melee Attack"
},
};
// secondary melee attack
Task_t tlSecondaryMeleeAttack1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_MELEE_ATTACK2, (float)0 },
};
Schedule_t slSecondaryMeleeAttack[] =
{
{
tlSecondaryMeleeAttack1,
ARRAYSIZE ( tlSecondaryMeleeAttack1 ),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED,
0,
"Secondary Melee Attack"
},
};
// special attack1
Task_t tlSpecialAttack1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SPECIAL_ATTACK1, (float)0 },
};
Schedule_t slSpecialAttack1[] =
{
{
tlSpecialAttack1,
ARRAYSIZE ( tlSpecialAttack1 ),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED |
bits_COND_NO_AMMO_LOADED |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"Special Attack1"
},
};
// special attack2
Task_t tlSpecialAttack2[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_SPECIAL_ATTACK2, (float)0 },
};
Schedule_t slSpecialAttack2[] =
{
{
tlSpecialAttack2,
ARRAYSIZE ( tlSpecialAttack2 ),
bits_COND_NEW_ENEMY |
bits_COND_ENEMY_DEAD |
bits_COND_LIGHT_DAMAGE |
bits_COND_HEAVY_DAMAGE |
bits_COND_ENEMY_OCCLUDED |
bits_COND_NO_AMMO_LOADED |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"Special Attack2"
},
};
// Chase enemy schedule
Task_t tlChaseEnemy1[] =
{
{ TASK_SET_FAIL_SCHEDULE, (float)SCHED_CHASE_ENEMY_FAILED },
{ TASK_GET_PATH_TO_ENEMY, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
};
Schedule_t slChaseEnemy[] =
{
{
tlChaseEnemy1,
ARRAYSIZE ( tlChaseEnemy1 ),
bits_COND_NEW_ENEMY |
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_MELEE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2 |
bits_COND_CAN_MELEE_ATTACK2 |
bits_COND_TASK_FAILED |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"Chase Enemy"
},
};
// Chase enemy failure schedule
Task_t tlChaseEnemyFailed[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_WAIT, (float)0.2 },
{ TASK_FIND_COVER_FROM_ENEMY, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_REMEMBER, (float)bits_MEMORY_INCOVER },
// { TASK_TURN_LEFT, (float)179 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_WAIT, (float)1 },
};
Schedule_t slChaseEnemyFailed[] =
{
{
tlChaseEnemyFailed,
ARRAYSIZE ( tlChaseEnemyFailed ),
bits_COND_NEW_ENEMY |
bits_COND_CAN_RANGE_ATTACK1 |
bits_COND_CAN_MELEE_ATTACK1 |
bits_COND_CAN_RANGE_ATTACK2 |
bits_COND_CAN_MELEE_ATTACK2 |
bits_COND_HEAR_SOUND,
bits_SOUND_DANGER,
"tlChaseEnemyFailed"
},
};
//=========================================================
// small flinch, played when minor damage is taken.
//=========================================================
Task_t tlSmallFlinch[] =
{
{ TASK_REMEMBER, (float)bits_MEMORY_FLINCHED },
{ TASK_STOP_MOVING, 0 },
{ TASK_SMALL_FLINCH, 0 },
};
Schedule_t slSmallFlinch[] =
{
{
tlSmallFlinch,
ARRAYSIZE ( tlSmallFlinch ),
0,
0,
"Small Flinch"
},
};
//=========================================================
// Die!
//=========================================================
Task_t tlDie1[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_SOUND_DIE, (float)0 },
{ TASK_DIE, (float)0 },
};
Schedule_t slDie[] =
{
{
tlDie1,
ARRAYSIZE( tlDie1 ),
0,
0,
"Die"
},
};
//=========================================================
// Victory Dance
//=========================================================
Task_t tlVictoryDance[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_VICTORY_DANCE },
{ TASK_WAIT, (float)0 },
};
Schedule_t slVictoryDance[] =
{
{
tlVictoryDance,
ARRAYSIZE( tlVictoryDance ),
0,
0,
"Victory Dance"
},
};
//=========================================================
// BarnacleVictimGrab - barnacle tongue just hit the monster,
// so play a hit animation, then play a cycling pull animation
// as the creature is hoisting the monster.
//=========================================================
Task_t tlBarnacleVictimGrab[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_BARNACLE_HIT },
{ TASK_SET_ACTIVITY, (float)ACT_BARNACLE_PULL },
{ TASK_WAIT_INDEFINITE, (float)0 },// just cycle barnacle pull anim while barnacle hoists.
};
Schedule_t slBarnacleVictimGrab[] =
{
{
tlBarnacleVictimGrab,
ARRAYSIZE ( tlBarnacleVictimGrab ),
0,
0,
"Barnacle Victim"
}
};
//=========================================================
// BarnacleVictimChomp - barnacle has pulled the prey to its
// mouth. Victim should play the BARNCLE_CHOMP animation
// once, then loop the BARNACLE_CHEW animation indefinitely
//=========================================================
Task_t tlBarnacleVictimChomp[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_BARNACLE_CHOMP },
{ TASK_SET_ACTIVITY, (float)ACT_BARNACLE_CHEW },
{ TASK_WAIT_INDEFINITE, (float)0 },// just cycle barnacle pull anim while barnacle hoists.
};
Schedule_t slBarnacleVictimChomp[] =
{
{
tlBarnacleVictimChomp,
ARRAYSIZE ( tlBarnacleVictimChomp ),
0,
0,
"Barnacle Chomp"
}
};
// Universal Error Schedule
Task_t tlError[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_WAIT_INDEFINITE, (float)0 },
};
Schedule_t slError[] =
{
{
tlError,
ARRAYSIZE ( tlError ),
0,
0,
"Error"
},
};
Task_t tlScriptedWalk[] =
{
{ TASK_WALK_TO_TARGET, (float)TARGET_MOVE_SCRIPTED },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_PLANT_ON_SCRIPT, (float)0 },
{ TASK_FACE_SCRIPT, (float)0 },
{ TASK_FACE_IDEAL, (float)0 },
{ TASK_ENABLE_SCRIPT, (float)0 },
{ TASK_WAIT_FOR_SCRIPT, (float)0 },
{ TASK_PLAY_SCRIPT, (float)0 },
};
Schedule_t slWalkToScript[] =
{
{
tlScriptedWalk,
ARRAYSIZE ( tlScriptedWalk ),
SCRIPT_BREAK_CONDITIONS,
0,
"WalkToScript"
},
};
Task_t tlScriptedRun[] =
{
{ TASK_RUN_TO_TARGET, (float)TARGET_MOVE_SCRIPTED },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_PLANT_ON_SCRIPT, (float)0 },
{ TASK_FACE_SCRIPT, (float)0 },
{ TASK_FACE_IDEAL, (float)0 },
{ TASK_ENABLE_SCRIPT, (float)0 },
{ TASK_WAIT_FOR_SCRIPT, (float)0 },
{ TASK_PLAY_SCRIPT, (float)0 },
};
Schedule_t slRunToScript[] =
{
{
tlScriptedRun,
ARRAYSIZE ( tlScriptedRun ),
SCRIPT_BREAK_CONDITIONS,
0,
"RunToScript"
},
};
Task_t tlScriptedWait[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_WAIT_FOR_SCRIPT, (float)0 },
{ TASK_PLAY_SCRIPT, (float)0 },
};
Schedule_t slWaitScript[] =
{
{
tlScriptedWait,
ARRAYSIZE ( tlScriptedWait ),
SCRIPT_BREAK_CONDITIONS,
0,
"WaitForScript"
},
};
Task_t tlScriptedFace[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_FACE_SCRIPT, (float)0 },
{ TASK_FACE_IDEAL, (float)0 },
{ TASK_WAIT_FOR_SCRIPT, (float)0 },
{ TASK_PLAY_SCRIPT, (float)0 },
};
Schedule_t slFaceScript[] =
{
{
tlScriptedFace,
ARRAYSIZE ( tlScriptedFace ),
SCRIPT_BREAK_CONDITIONS,
0,
"FaceScript"
},
};
//=========================================================
// Cower - this is what is usually done when attempts
// to escape danger fail.
//=========================================================
Task_t tlCower[] =
{
{ TASK_STOP_MOVING, 0 },
{ TASK_PLAY_SEQUENCE, (float)ACT_COWER },
};
Schedule_t slCower[] =
{
{
tlCower,
ARRAYSIZE ( tlCower ),
0,
0,
"Cower"
},
};
//=========================================================
// move away from where you're currently standing.
//=========================================================
Task_t tlTakeCoverFromOrigin[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_FIND_COVER_FROM_ORIGIN, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_REMEMBER, (float)bits_MEMORY_INCOVER },
{ TASK_TURN_LEFT, (float)179 },
};
Schedule_t slTakeCoverFromOrigin[] =
{
{
tlTakeCoverFromOrigin,
ARRAYSIZE ( tlTakeCoverFromOrigin ),
bits_COND_NEW_ENEMY,
0,
"TakeCoverFromOrigin"
},
};
//=========================================================
// hide from the loudest sound source
//=========================================================
Task_t tlTakeCoverFromBestSound[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_FIND_COVER_FROM_BEST_SOUND, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_REMEMBER, (float)bits_MEMORY_INCOVER },
{ TASK_TURN_LEFT, (float)179 },
};
Schedule_t slTakeCoverFromBestSound[] =
{
{
tlTakeCoverFromBestSound,
ARRAYSIZE ( tlTakeCoverFromBestSound ),
bits_COND_NEW_ENEMY,
0,
"TakeCoverFromBestSound"
},
};
//=========================================================
// Take cover from enemy! Tries lateral cover before node
// cover!
//=========================================================
Task_t tlTakeCoverFromEnemy[] =
{
{ TASK_STOP_MOVING, (float)0 },
{ TASK_WAIT, (float)0.2 },
{ TASK_FIND_COVER_FROM_ENEMY, (float)0 },
{ TASK_RUN_PATH, (float)0 },
{ TASK_WAIT_FOR_MOVEMENT, (float)0 },
{ TASK_REMEMBER, (float)bits_MEMORY_INCOVER },
// { TASK_TURN_LEFT, (float)179 },
{ TASK_FACE_ENEMY, (float)0 },
{ TASK_WAIT, (float)1 },
};
Schedule_t slTakeCoverFromEnemy[] =
{
{
tlTakeCoverFromEnemy,
ARRAYSIZE ( tlTakeCoverFromEnemy ),
bits_COND_NEW_ENEMY,
0,
"tlTakeCoverFromEnemy"
},
};
BEGIN_SCHEDULES_NOBASE( CBaseMonster )
slIdleStand,
slIdleTrigger,
slIdleWalk,
slAmbush,
slActiveIdle,
slWakeAngry,
slAlertFace,
slAlertSmallFlinch,
slAlertStand,
slInvestigateSound,
slCombatStand,
slCombatFace,
slStandoff,
slArmWeapon,
slReload,
slRangeAttack1,
slRangeAttack2,
slPrimaryMeleeAttack,
slSecondaryMeleeAttack,
slSpecialAttack1,
slSpecialAttack2,
slChaseEnemy,
slChaseEnemyFailed,
slSmallFlinch,
slDie,
slVictoryDance,
slBarnacleVictimGrab,
slBarnacleVictimChomp,
slError,
slWalkToScript,
slRunToScript,
slWaitScript,
slFaceScript,
slCower,
slTakeCoverFromOrigin,
slTakeCoverFromBestSound,
slTakeCoverFromEnemy,
slFail
END_SCHEDULES()
const Schedule_t* CBaseMonster::ScheduleFromName( const char* const pszName ) const
{
const Schedules_t* pSchedules = GetSchedulesList();
while( pSchedules )
{
if( const Schedule_t* pSchedule = ScheduleInList( pszName, pSchedules->ppSchedules, pSchedules->uiNumSchedules ) )
return pSchedule;
pSchedules = pSchedules->pBaseList;
}
return nullptr;
}
const Schedule_t* CBaseMonster::ScheduleInList( const char* const pszName, const Schedule_t* const* pList, size_t listCount ) const
{
if ( !pszName )
{
ALERT( at_console, "%s set to unnamed schedule!\n", GetClassname() );
return nullptr;
}
for ( size_t i = 0; i < listCount; ++i )
{
if ( !pList[i]->pName )
{
ALERT( at_console, "Unnamed schedule!\n" );
continue;
}
if ( stricmp( pszName, pList[i]->pName ) == 0 )
return pList[i];
}
return nullptr;
}
//=========================================================
// GetScheduleOfType - returns a pointer to one of the
// monster's available schedules of the indicated type.
//=========================================================
Schedule_t* CBaseMonster :: GetScheduleOfType ( int Type )
{
// ALERT ( at_console, "Sched Type:%d\n", Type );
switch ( Type )
{
// This is the schedule for scripted sequences AND scripted AI
case SCHED_AISCRIPT:
{
ASSERT( m_pCine != NULL );
if ( !m_pCine )
{
ALERT( at_aiconsole, "Script failed for %s\n", GetClassname() );
CineCleanup();
return GetScheduleOfType( SCHED_IDLE_STAND );
}
// else
// ALERT( at_aiconsole, "Starting script %s for %s\n", STRING( m_pCine->m_iszPlay ), GetClassname() );
switch ( m_pCine->m_fMoveTo )
{
case 0:
case 4:
return slWaitScript;
case 1:
return slWalkToScript;
case 2:
return slRunToScript;
case 5:
return slFaceScript;
}
break;
}
case SCHED_IDLE_STAND:
{
if ( RANDOM_LONG(0,14) == 0 && FCanActiveIdle() )
{
return &slActiveIdle[ 0 ];
}
return &slIdleStand[ 0 ];
}
case SCHED_IDLE_WALK:
{
return &slIdleWalk[ 0 ];
}
case SCHED_WAIT_TRIGGER:
{
return &slIdleTrigger[ 0 ];
}
case SCHED_WAKE_ANGRY:
{
return &slWakeAngry[ 0 ];
}
case SCHED_ALERT_FACE:
{
return &slAlertFace[ 0 ];
}
case SCHED_ALERT_STAND:
{
return &slAlertStand[ 0 ];
}
case SCHED_COMBAT_STAND:
{
return &slCombatStand[ 0 ];
}
case SCHED_COMBAT_FACE:
{
return &slCombatFace[ 0 ];
}
case SCHED_CHASE_ENEMY:
{
return &slChaseEnemy[ 0 ];
}
case SCHED_CHASE_ENEMY_FAILED:
{
return &slFail[ 0 ];
}
case SCHED_SMALL_FLINCH:
{
return &slSmallFlinch[ 0 ];
}
case SCHED_ALERT_SMALL_FLINCH:
{
return &slAlertSmallFlinch[ 0 ];
}
case SCHED_RELOAD:
{
return &slReload[ 0 ];
}
case SCHED_ARM_WEAPON:
{
return &slArmWeapon[ 0 ];
}
case SCHED_STANDOFF:
{
return &slStandoff[ 0 ];
}
case SCHED_RANGE_ATTACK1:
{
return &slRangeAttack1[ 0 ];
}
case SCHED_RANGE_ATTACK2:
{
return &slRangeAttack2[ 0 ];
}
case SCHED_MELEE_ATTACK1:
{
return &slPrimaryMeleeAttack[ 0 ];
}
case SCHED_MELEE_ATTACK2:
{
return &slSecondaryMeleeAttack[ 0 ];
}
case SCHED_SPECIAL_ATTACK1:
{
return &slSpecialAttack1[ 0 ];
}
case SCHED_SPECIAL_ATTACK2:
{
return &slSpecialAttack2[ 0 ];
}
case SCHED_TAKE_COVER_FROM_BEST_SOUND:
{
return &slTakeCoverFromBestSound[ 0 ];
}
case SCHED_TAKE_COVER_FROM_ENEMY:
{
return &slTakeCoverFromEnemy[ 0 ];
}
case SCHED_COWER:
{
return &slCower[ 0 ];
}
case SCHED_AMBUSH:
{
return &slAmbush[ 0 ];
}
case SCHED_BARNACLE_VICTIM_GRAB:
{
return &slBarnacleVictimGrab[ 0 ];
}
case SCHED_BARNACLE_VICTIM_CHOMP:
{
return &slBarnacleVictimChomp[ 0 ];
}
case SCHED_INVESTIGATE_SOUND:
{
return &slInvestigateSound[ 0 ];
}
case SCHED_DIE:
{
return &slDie[ 0 ];
}
case SCHED_TAKE_COVER_FROM_ORIGIN:
{
return &slTakeCoverFromOrigin[ 0 ];
}
case SCHED_VICTORY_DANCE:
{
return &slVictoryDance[ 0 ];
}
case SCHED_FAIL:
{
return slFail;
}
default:
{
ALERT ( at_console, "GetScheduleOfType()\nNo CASE for Schedule Type %d!\n", Type );
return &slIdleStand[ 0 ];
break;
}
}
return NULL;
}
|
#include <Arduino.h>
#include "publisher.hpp"
#include "subscriber.hpp"
#include "parameter.hpp"
#include <watchdog.h>
// Node settings
static constexpr uint32_t nodeID = 100;
static constexpr uint8_t swVersion = 1;
static constexpr uint8_t hwVersion = 1;
static const char *nodeName = "org.arvp.example_node";
// application framerate
static constexpr float framerate = 1000;
void setup()
{
delay(1000);
Serial.begin(115200);
Serial.println("Setup");
// init LEDs
initLeds();
// Create a node
systemClock = &initSystemClock();
canDriver = &initCanDriver();
node = new Node<NodeMemoryPoolSize>(*canDriver, *systemClock);
initNode(node, nodeID, nodeName, swVersion, hwVersion);
// init publisher
initPublisher(node);
// init subscriber
initSubscriber(node);
// set up filters (must be after publisher & subscriber setup!)
configureCanAcceptanceFilters(*node);
// init parameter
initParameter(node);
// start up node
node->setModeOperational();
Serial.println("Setup Finished");
}
void loop()
{
KickDog();
Serial.println("loop");
// wait in cycle
cycleWait(framerate);
// do some CAN stuff
cycleNode(node);
// publish messages
cyclePublisher(50);
// toggle heartbeat
toggleHeartBeat();
}
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/nigori/nigori_model_type_processor.h"
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "components/sync/base/client_tag_hash.h"
#include "components/sync/base/sync_base_switches.h"
#include "components/sync/base/time.h"
#include "components/sync/engine/commit_queue.h"
#include "components/sync/engine/data_type_activation_response.h"
#include "components/sync/model/type_entities_count.h"
#include "components/sync/nigori/nigori_sync_bridge.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
namespace {
using testing::_;
using testing::Eq;
using testing::Ne;
using testing::NotNull;
// TODO(mamir): remove those and adjust the code accordingly.
const char kRawNigoriClientTagHash[] = "NigoriClientTagHash";
const char kNigoriNonUniqueName[] = "nigori";
const char kNigoriServerId[] = "nigori_server_id";
const char kCacheGuid[] = "generated_id";
// |*arg| must be of type absl::optional<EntityData>.
MATCHER_P(OptionalEntityDataHasDecryptorTokenKeyName, expected_key_name, "") {
return arg->specifics.nigori().keystore_decryptor_token().key_name() ==
expected_key_name;
}
void CaptureCommitRequest(CommitRequestDataList* dst,
CommitRequestDataList&& src) {
*dst = std::move(src);
}
sync_pb::ModelTypeState CreateDummyModelTypeState() {
sync_pb::ModelTypeState model_type_state;
model_type_state.set_cache_guid(kCacheGuid);
model_type_state.set_initial_sync_done(true);
return model_type_state;
}
// Creates a dummy Nigori UpdateResponseData that has the keystore decryptor
// token key name set.
syncer::UpdateResponseData CreateDummyNigoriUpdateResponseData(
const std::string keystore_decryptor_token_key_name,
int response_version) {
syncer::EntityData entity_data;
entity_data.id = kNigoriServerId;
sync_pb::NigoriSpecifics* nigori_specifics =
entity_data.specifics.mutable_nigori();
nigori_specifics->mutable_keystore_decryptor_token()->set_key_name(
keystore_decryptor_token_key_name);
entity_data.name = kNigoriNonUniqueName;
syncer::UpdateResponseData response_data;
response_data.entity = std::move(entity_data);
response_data.response_version = response_version;
return response_data;
}
CommitResponseData CreateNigoriCommitResponseData(
const CommitRequestData& commit_request_data,
int response_version) {
CommitResponseData commit_response_data;
commit_response_data.id = kNigoriServerId;
commit_response_data.client_tag_hash =
ClientTagHash::FromHashed(kRawNigoriClientTagHash);
commit_response_data.sequence_number = commit_request_data.sequence_number;
commit_response_data.response_version = response_version;
commit_response_data.specifics_hash = commit_request_data.specifics_hash;
commit_response_data.unsynced_time = commit_request_data.unsynced_time;
return commit_response_data;
}
class MockNigoriSyncBridge : public NigoriSyncBridge {
public:
MockNigoriSyncBridge() = default;
~MockNigoriSyncBridge() override = default;
MOCK_METHOD(absl::optional<ModelError>,
MergeSyncData,
(absl::optional<EntityData> data),
(override));
MOCK_METHOD(absl::optional<ModelError>,
ApplySyncChanges,
(absl::optional<EntityData> data),
(override));
MOCK_METHOD(std::unique_ptr<EntityData>, GetData, (), (override));
MOCK_METHOD(void, ApplyDisableSyncChanges, (), (override));
};
class MockCommitQueue : public CommitQueue {
public:
MockCommitQueue() = default;
~MockCommitQueue() override = default;
MOCK_METHOD(void, NudgeForCommit, (), (override));
};
class NigoriModelTypeProcessorTest : public testing::Test {
public:
NigoriModelTypeProcessorTest() {
mock_commit_queue_ = std::make_unique<testing::NiceMock<MockCommitQueue>>();
mock_commit_queue_ptr_ = mock_commit_queue_.get();
}
void SimulateModelReadyToSync(bool initial_sync_done, int server_version) {
NigoriMetadataBatch nigori_metadata_batch;
nigori_metadata_batch.model_type_state.set_initial_sync_done(
initial_sync_done);
nigori_metadata_batch.model_type_state.set_cache_guid(kCacheGuid);
nigori_metadata_batch.entity_metadata = sync_pb::EntityMetadata();
nigori_metadata_batch.entity_metadata->set_creation_time(
TimeToProtoTime(base::Time::Now()));
nigori_metadata_batch.entity_metadata->set_sequence_number(0);
nigori_metadata_batch.entity_metadata->set_acked_sequence_number(0);
nigori_metadata_batch.entity_metadata->set_server_version(server_version);
processor_.ModelReadyToSync(mock_nigori_sync_bridge(),
std::move(nigori_metadata_batch));
}
void SimulateModelReadyToSync(bool initial_sync_done) {
SimulateModelReadyToSync(initial_sync_done, /*server_version=*/1);
}
void SimulateConnectSync() {
processor_.ConnectSync(std::move(mock_commit_queue_));
}
MockNigoriSyncBridge* mock_nigori_sync_bridge() {
return &mock_nigori_sync_bridge_;
}
MockCommitQueue* mock_commit_queue() { return mock_commit_queue_ptr_; }
NigoriModelTypeProcessor* processor() { return &processor_; }
bool ProcessorHasEntity() {
TypeEntitiesCount count(NIGORI);
base::MockCallback<base::OnceCallback<void(const TypeEntitiesCount&)>>
capture_callback;
EXPECT_CALL(capture_callback, Run).WillOnce(testing::SaveArg<0>(&count));
processor()->GetTypeEntitiesCountForDebugging(capture_callback.Get());
return count.non_tombstone_entities > 0;
}
private:
testing::NiceMock<MockNigoriSyncBridge> mock_nigori_sync_bridge_;
std::unique_ptr<testing::NiceMock<MockCommitQueue>> mock_commit_queue_;
raw_ptr<MockCommitQueue> mock_commit_queue_ptr_;
NigoriModelTypeProcessor processor_;
};
TEST_F(NigoriModelTypeProcessorTest,
ShouldTrackTheMetadataWhenInitialSyncDone) {
// Build a model type state with a specific cache guid.
const std::string kOtherCacheGuid = "cache_guid";
sync_pb::ModelTypeState model_type_state;
model_type_state.set_initial_sync_done(true);
model_type_state.set_cache_guid(kOtherCacheGuid);
// Build entity metadata with a specific sequence number.
const int kSequenceNumber = 100;
sync_pb::EntityMetadata entity_metadata;
entity_metadata.set_sequence_number(kSequenceNumber);
entity_metadata.set_creation_time(TimeToProtoTime(base::Time::Now()));
NigoriMetadataBatch nigori_metadata_batch;
nigori_metadata_batch.model_type_state = model_type_state;
nigori_metadata_batch.entity_metadata = entity_metadata;
processor()->ModelReadyToSync(mock_nigori_sync_bridge(),
std::move(nigori_metadata_batch));
// The model type state and the metadata should have been stored in the
// processor.
NigoriMetadataBatch processor_metadata_batch = processor()->GetMetadata();
EXPECT_THAT(processor_metadata_batch.model_type_state.cache_guid(),
Eq(kOtherCacheGuid));
ASSERT_TRUE(processor_metadata_batch.entity_metadata);
EXPECT_THAT(processor_metadata_batch.entity_metadata->sequence_number(),
Eq(kSequenceNumber));
}
TEST_F(NigoriModelTypeProcessorTest, ShouldIncrementSequenceNumberWhenPut) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
absl::optional<sync_pb::EntityMetadata> entity_metadata1 =
processor()->GetMetadata().entity_metadata;
ASSERT_TRUE(entity_metadata1);
auto entity_data = std::make_unique<syncer::EntityData>();
entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
processor()->Put(std::move(entity_data));
absl::optional<sync_pb::EntityMetadata> entity_metadata2 =
processor()->GetMetadata().entity_metadata;
ASSERT_TRUE(entity_metadata1);
EXPECT_THAT(entity_metadata2->sequence_number(),
Eq(entity_metadata1->sequence_number() + 1));
}
TEST_F(NigoriModelTypeProcessorTest, ShouldGetEmptyLocalChanges) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
CommitRequestDataList commit_request;
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request));
EXPECT_EQ(0U, commit_request.size());
}
TEST_F(NigoriModelTypeProcessorTest, ShouldGetLocalChangesWhenPut) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
auto entity_data = std::make_unique<syncer::EntityData>();
entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
processor()->Put(std::move(entity_data));
CommitRequestDataList commit_request;
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request));
ASSERT_EQ(1U, commit_request.size());
EXPECT_EQ(kNigoriNonUniqueName, commit_request[0]->entity->name);
}
TEST_F(NigoriModelTypeProcessorTest,
ShouldSquashCommitRequestUponCommitCompleted) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
auto entity_data = std::make_unique<syncer::EntityData>();
entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
processor()->Put(std::move(entity_data));
CommitRequestDataList commit_request_list;
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request_list));
ASSERT_EQ(1U, commit_request_list.size());
CommitResponseDataList commit_response_list;
commit_response_list.push_back(CreateNigoriCommitResponseData(
*commit_request_list[0], /*response_version=*/processor()
->GetMetadata()
.entity_metadata->server_version() +
1));
// ApplySyncChanges() should be called to trigger persistence of the metadata.
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplySyncChanges(Eq(absl::nullopt)));
processor()->OnCommitCompleted(
CreateDummyModelTypeState(), std::move(commit_response_list),
/*error_response_list=*/FailedCommitResponseDataList());
// There should be no more local changes.
commit_response_list.clear();
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request_list));
EXPECT_TRUE(commit_request_list.empty());
}
TEST_F(NigoriModelTypeProcessorTest,
ShouldNotSquashCommitRequestUponEmptyCommitResponse) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
auto entity_data = std::make_unique<syncer::EntityData>();
entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
processor()->Put(std::move(entity_data));
CommitRequestDataList commit_request_list;
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request_list));
ASSERT_EQ(1U, commit_request_list.size());
// ApplySyncChanges() should be called to trigger persistence of the metadata.
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplySyncChanges(Eq(absl::nullopt)));
processor()->OnCommitCompleted(
CreateDummyModelTypeState(),
/*committed_response_list=*/CommitResponseDataList(),
/*error_response_list=*/FailedCommitResponseDataList());
// Data has been moved into the previous request, so the processor will ask
// for the commit data once more.
ON_CALL(*mock_nigori_sync_bridge(), GetData()).WillByDefault([&]() {
auto entity_data = std::make_unique<syncer::EntityData>();
entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
return entity_data;
});
// The commit should still be pending.
CommitResponseDataList commit_response_list;
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request_list));
EXPECT_EQ(1U, commit_request_list.size());
}
TEST_F(NigoriModelTypeProcessorTest,
ShouldKeepAnotherCommitRequestUponCommitCompleted) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
auto entity_data = std::make_unique<syncer::EntityData>();
sync_pb::NigoriSpecifics* nigori_specifics =
entity_data->specifics.mutable_nigori();
nigori_specifics->set_encrypt_bookmarks(true);
entity_data->name = kNigoriNonUniqueName;
processor()->Put(std::move(entity_data));
CommitRequestDataList commit_request_list;
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request_list));
ASSERT_EQ(1U, commit_request_list.size());
CommitResponseDataList commit_response_list;
commit_response_list.push_back(CreateNigoriCommitResponseData(
*commit_request_list[0], /*response_version=*/processor()
->GetMetadata()
.entity_metadata->server_version() +
1));
// Make another local change before the commit response is received.
entity_data = std::make_unique<syncer::EntityData>();
nigori_specifics = entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
nigori_specifics->set_encrypt_preferences(true);
processor()->Put(std::move(entity_data));
// ApplySyncChanges() should be called to trigger persistence of the metadata.
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplySyncChanges(Eq(absl::nullopt)));
// Receive the commit response of the first request.
processor()->OnCommitCompleted(
CreateDummyModelTypeState(), std::move(commit_response_list),
/*error_response_list=*/FailedCommitResponseDataList());
// There should still be a local change.
commit_response_list.clear();
processor()->GetLocalChanges(
/*max_entries=*/10,
base::BindOnce(&CaptureCommitRequest, &commit_request_list));
EXPECT_EQ(1U, commit_request_list.size());
}
TEST_F(NigoriModelTypeProcessorTest,
ShouldNudgeForCommitUponConnectSyncIfReadyToSyncAndLocalChanges) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
auto entity_data = std::make_unique<syncer::EntityData>();
entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
processor()->Put(std::move(entity_data));
EXPECT_CALL(*mock_commit_queue(), NudgeForCommit());
SimulateConnectSync();
}
TEST_F(NigoriModelTypeProcessorTest, ShouldNudgeForCommitUponPutIfReadyToSync) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
SimulateConnectSync();
auto entity_data = std::make_unique<syncer::EntityData>();
entity_data->specifics.mutable_nigori();
entity_data->name = kNigoriNonUniqueName;
EXPECT_CALL(*mock_commit_queue(), NudgeForCommit());
processor()->Put(std::move(entity_data));
}
TEST_F(NigoriModelTypeProcessorTest, ShouldInvokeSyncStartCallback) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
syncer::DataTypeActivationRequest request;
request.error_handler = base::DoNothing();
request.cache_guid = kCacheGuid;
base::MockCallback<ModelTypeControllerDelegate::StartCallback> start_callback;
std::unique_ptr<DataTypeActivationResponse> captured_response;
EXPECT_CALL(start_callback, Run)
.WillOnce(testing::Invoke(
[&captured_response](
std::unique_ptr<DataTypeActivationResponse> response) {
captured_response = std::move(response);
}));
processor()->OnSyncStarting(request, start_callback.Get());
ASSERT_THAT(captured_response, NotNull());
EXPECT_EQ(kCacheGuid, captured_response->model_type_state.cache_guid());
// Test that the |processor()| has been set in the activation response.
ASSERT_FALSE(processor()->IsConnectedForTest());
captured_response->type_processor->ConnectSync(
std::make_unique<testing::NiceMock<MockCommitQueue>>());
EXPECT_TRUE(processor()->IsConnectedForTest());
}
TEST_F(NigoriModelTypeProcessorTest, ShouldMergeSyncData) {
SimulateModelReadyToSync(/*initial_sync_done=*/false);
const std::string kDecryptorTokenKeyName = "key_name";
UpdateResponseDataList updates;
updates.push_back(CreateDummyNigoriUpdateResponseData(kDecryptorTokenKeyName,
/*server_version=*/1));
EXPECT_CALL(*mock_nigori_sync_bridge(),
MergeSyncData(OptionalEntityDataHasDecryptorTokenKeyName(
kDecryptorTokenKeyName)));
processor()->OnUpdateReceived(CreateDummyModelTypeState(),
std::move(updates));
}
TEST_F(NigoriModelTypeProcessorTest, ShouldApplySyncChanges) {
SimulateModelReadyToSync(/*initial_sync_done=*/true, /*server_version=*/1);
const std::string kDecryptorTokenKeyName = "key_name";
UpdateResponseDataList updates;
updates.push_back(CreateDummyNigoriUpdateResponseData(kDecryptorTokenKeyName,
/*server_version=*/2));
EXPECT_CALL(*mock_nigori_sync_bridge(),
ApplySyncChanges(OptionalEntityDataHasDecryptorTokenKeyName(
kDecryptorTokenKeyName)));
processor()->OnUpdateReceived(CreateDummyModelTypeState(),
std::move(updates));
}
TEST_F(NigoriModelTypeProcessorTest, ShouldApplySyncChangesWhenEmptyUpdates) {
const int kServerVersion = 1;
SimulateModelReadyToSync(/*initial_sync_done=*/true, kServerVersion);
// ApplySyncChanges() should still be called to trigger persistence of the
// metadata.
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplySyncChanges(Eq(absl::nullopt)));
processor()->OnUpdateReceived(CreateDummyModelTypeState(),
UpdateResponseDataList());
}
TEST_F(NigoriModelTypeProcessorTest, ShouldApplySyncChangesWhenReflection) {
const int kServerVersion = 1;
SimulateModelReadyToSync(/*initial_sync_done=*/true, kServerVersion);
UpdateResponseDataList updates;
updates.push_back(CreateDummyNigoriUpdateResponseData(
/*keystore_decryptor_token_key_name=*/"key_name", kServerVersion));
// ApplySyncChanges() should still be called to trigger persistence of the
// metadata.
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplySyncChanges(Eq(absl::nullopt)));
processor()->OnUpdateReceived(CreateDummyModelTypeState(),
std::move(updates));
}
TEST_F(NigoriModelTypeProcessorTest, ShouldStopSyncingAndKeepMetadata) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
syncer::DataTypeActivationRequest request;
request.error_handler = base::DoNothing();
request.cache_guid = kCacheGuid;
processor()->OnSyncStarting(request, base::DoNothing());
SimulateConnectSync();
ASSERT_TRUE(processor()->IsConnectedForTest());
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplyDisableSyncChanges()).Times(0);
processor()->OnSyncStopping(syncer::KEEP_METADATA);
EXPECT_FALSE(processor()->IsConnectedForTest());
}
TEST_F(NigoriModelTypeProcessorTest, ShouldStopSyncingAndClearMetadata) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
syncer::DataTypeActivationRequest request;
request.error_handler = base::DoNothing();
request.cache_guid = kCacheGuid;
processor()->OnSyncStarting(request, base::DoNothing());
SimulateConnectSync();
ASSERT_TRUE(processor()->IsConnectedForTest());
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplyDisableSyncChanges());
processor()->OnSyncStopping(syncer::CLEAR_METADATA);
EXPECT_FALSE(processor()->IsConnectedForTest());
}
TEST_F(NigoriModelTypeProcessorTest, ShouldResetDataOnCacheGuidMismatch) {
SimulateModelReadyToSync(/*initial_sync_done=*/true);
ASSERT_TRUE(ProcessorHasEntity());
syncer::DataTypeActivationRequest request;
request.error_handler = base::DoNothing();
const char kOtherCacheGuid[] = "OtherCacheGuid";
request.cache_guid = kOtherCacheGuid;
ASSERT_NE(processor()->GetMetadata().model_type_state.cache_guid(),
kOtherCacheGuid);
ASSERT_TRUE(processor()->IsTrackingMetadata());
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplyDisableSyncChanges());
processor()->OnSyncStarting(request, base::DoNothing());
EXPECT_FALSE(processor()->IsTrackingMetadata());
EXPECT_EQ(processor()->GetModelTypeStateForTest().cache_guid(),
kOtherCacheGuid);
EXPECT_FALSE(ProcessorHasEntity());
// Check that sync can be started.
const std::string kDecryptorTokenKeyName = "key_name";
UpdateResponseDataList updates;
updates.push_back(CreateDummyNigoriUpdateResponseData(kDecryptorTokenKeyName,
/*server_version=*/1));
EXPECT_CALL(*mock_nigori_sync_bridge(),
MergeSyncData(OptionalEntityDataHasDecryptorTokenKeyName(
kDecryptorTokenKeyName)));
processor()->OnUpdateReceived(CreateDummyModelTypeState(),
std::move(updates));
}
TEST_F(NigoriModelTypeProcessorTest,
ShouldNotResetDataOnCacheGuidMismatchWhenDisabled) {
base::test::ScopedFeatureList features;
features.InitAndDisableFeature(
switches::kSyncNigoriRemoveMetadataOnCacheGuidMismatch);
SimulateModelReadyToSync(/*initial_sync_done=*/true);
ASSERT_TRUE(ProcessorHasEntity());
syncer::DataTypeActivationRequest request;
request.error_handler = base::DoNothing();
const char kOtherCacheGuid[] = "OtherCacheGuid";
request.cache_guid = kOtherCacheGuid;
ASSERT_NE(processor()->GetMetadata().model_type_state.cache_guid(),
kOtherCacheGuid);
ASSERT_TRUE(processor()->IsTrackingMetadata());
EXPECT_CALL(*mock_nigori_sync_bridge(), ApplyDisableSyncChanges()).Times(0);
processor()->OnSyncStarting(request, base::DoNothing());
EXPECT_TRUE(processor()->IsTrackingMetadata());
EXPECT_EQ(processor()->GetModelTypeStateForTest().cache_guid(), kCacheGuid);
EXPECT_TRUE(ProcessorHasEntity());
}
TEST_F(NigoriModelTypeProcessorTest, ShouldDisconnectWhenMergeSyncDataFails) {
SimulateModelReadyToSync(/*initial_sync_done=*/false);
syncer::DataTypeActivationRequest request;
base::MockCallback<ModelErrorHandler> error_handler_callback;
request.error_handler = error_handler_callback.Get();
request.cache_guid = kCacheGuid;
processor()->OnSyncStarting(request, base::DoNothing());
SimulateConnectSync();
// Simulate returning error at MergeSyncData()
ON_CALL(*mock_nigori_sync_bridge(), MergeSyncData)
.WillByDefault([&](const absl::optional<EntityData>& data) {
return ModelError(FROM_HERE, "some error");
});
UpdateResponseDataList updates;
updates.push_back(CreateDummyNigoriUpdateResponseData(
/*keystore_decryptor_token_key_name=*/"some key",
/*server_version=*/1));
ASSERT_TRUE(processor()->IsConnectedForTest());
EXPECT_CALL(error_handler_callback, Run);
processor()->OnUpdateReceived(CreateDummyModelTypeState(),
std::move(updates));
EXPECT_FALSE(processor()->IsConnectedForTest());
}
TEST_F(NigoriModelTypeProcessorTest,
ShouldDisconnectWhenApplySyncChangesFails) {
SimulateModelReadyToSync(/*initial_sync_done=*/true, /*server_version=*/1);
syncer::DataTypeActivationRequest request;
base::MockCallback<ModelErrorHandler> error_handler_callback;
request.error_handler = error_handler_callback.Get();
request.cache_guid = kCacheGuid;
processor()->OnSyncStarting(request, base::DoNothing());
SimulateConnectSync();
// Simulate returning error at ApplySyncChanges()
ON_CALL(*mock_nigori_sync_bridge(), ApplySyncChanges)
.WillByDefault([&](const absl::optional<EntityData>& data) {
return ModelError(FROM_HERE, "some error");
});
UpdateResponseDataList updates;
updates.push_back(CreateDummyNigoriUpdateResponseData(
/*keystore_decryptor_token_key_name=*/"some key",
/*server_version=*/2));
ASSERT_TRUE(processor()->IsConnectedForTest());
EXPECT_CALL(error_handler_callback, Run);
processor()->OnUpdateReceived(CreateDummyModelTypeState(),
std::move(updates));
EXPECT_FALSE(processor()->IsConnectedForTest());
}
TEST_F(NigoriModelTypeProcessorTest,
ShouldCallErrorHandlerIfModelErrorBeforeSyncStarts) {
processor()->ReportError(ModelError(FROM_HERE, "some error"));
syncer::DataTypeActivationRequest request;
base::MockCallback<ModelErrorHandler> error_handler_callback;
request.error_handler = error_handler_callback.Get();
request.cache_guid = kCacheGuid;
EXPECT_CALL(error_handler_callback, Run);
processor()->OnSyncStarting(request, base::DoNothing());
}
} // namespace
} // namespace syncer
|
/*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include <Gwen/Gwen.h>
#include <Gwen/Skin.h>
#include <Gwen/Controls/TabButton.h>
#include <Gwen/Controls/TabControl.h>
#include <Gwen/Controls/Highlight.h>
#include <Gwen/DragAndDrop.h>
using namespace Gwen;
using namespace Gwen::Controls;
GWEN_CONTROL_CONSTRUCTOR( TabButton )
{
m_Page = NULL;
m_Control = NULL;
DragAndDrop_SetPackage( true, "TabButtonMove" );
SetAlignment( Pos::Top | Pos::Left );
SetTextPadding( Padding( 2, 2, 2, 2 ) );
}
void TabButton::Layout( Skin::Base* skin )
{
int iParentDock = m_Control->GetTabStrip()->GetDock();
if ( iParentDock == Pos::Bottom )
{ SetPadding( Padding( 3, 1, 5, 4 ) ); }
else if ( iParentDock == Pos::Top )
{ SetPadding( Padding( 3, 3, 5, 2 ) ); }
else
{ SetPadding( Padding( 3, 2, 5, 2 ) ); }
BaseClass::Layout( skin );
}
void TabButton::Render( Skin::Base* skin )
{
skin->DrawTabButton( this, IsActive(), m_Control->GetTabStrip()->GetDock() );
}
void TabButton::SetTabControl( TabControl* ctrl )
{
if ( m_Control == ctrl ) { return; }
if ( m_Control )
{
m_Control->OnLoseTab( this );
}
m_Control = ctrl;
}
bool TabButton::DragAndDrop_ShouldStartDrag()
{
return m_Control->DoesAllowDrag();
}
bool TabButton::OnKeyUp( bool bDown )
{
OnKeyLeft( bDown );
return true;
}
bool TabButton::OnKeyDown( bool bDown )
{
OnKeyRight( bDown );
return true;
}
bool TabButton::OnKeyLeft( bool bDown )
{
if ( bDown )
{
Base::List::reverse_iterator it = std::find( m_Parent->Children.rbegin(), m_Parent->Children.rend(), this );
if ( it != m_Parent->Children.rend() && ( ++it != m_Parent->Children.rend() ) )
{
Base* pNextTab = *it;
GetTabControl()->OnTabPressed( pNextTab );
Gwen::KeyboardFocus = pNextTab;
}
}
return true;
}
bool TabButton::OnKeyRight( bool bDown )
{
if ( bDown )
{
Base::List::iterator it = std::find( m_Parent->Children.begin(), m_Parent->Children.end(), this );
if ( it != m_Parent->Children.end() && ( ++it != m_Parent->Children.end() ) )
{
Base* pNextTab = *it;
GetTabControl()->OnTabPressed( pNextTab );
Gwen::KeyboardFocus = pNextTab;
}
}
return true;
}
void TabButton::UpdateColours()
{
if ( !IsActive() )
{
SetImageAlpha( 0.5 );
if ( IsDisabled() ) { return SetTextColor( GetSkin()->Colors.Tab.Inactive.Disabled ); }
if ( IsDepressed() ) { return SetTextColor( GetSkin()->Colors.Tab.Inactive.Down ); }
if ( IsHovered() ) { return SetTextColor( GetSkin()->Colors.Tab.Inactive.Hover ); }
return SetTextColor( GetSkin()->Colors.Tab.Inactive.Normal );
}
SetImageAlpha( 1.0 );
if ( IsDisabled() ) { return SetTextColor( GetSkin()->Colors.Tab.Active.Disabled ); }
if ( IsDepressed() ) { return SetTextColor( GetSkin()->Colors.Tab.Active.Down ); }
if ( IsHovered() ) { return SetTextColor( GetSkin()->Colors.Tab.Active.Hover ); }
SetTextColor( GetSkin()->Colors.Tab.Active.Normal );
}
|
//===- MLIRContext.cpp - MLIR Type Classes --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/IR/MLIRContext.h"
#include "AffineExprDetail.h"
#include "AffineMapDetail.h"
#include "AttributeDetail.h"
#include "IntegerSetDetail.h"
#include "LocationDetail.h"
#include "TypeDetail.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/Identifier.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/Module.h"
#include "mlir/IR/Types.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/RWMutex.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
using namespace mlir;
using namespace mlir::detail;
using llvm::hash_combine;
using llvm::hash_combine_range;
//===----------------------------------------------------------------------===//
// MLIRContext CommandLine Options
//===----------------------------------------------------------------------===//
namespace {
/// This struct contains command line options that can be used to initialize
/// various bits of an MLIRContext. This uses a struct wrapper to avoid the need
/// for global command line options.
struct MLIRContextOptions {
llvm::cl::opt<bool> disableThreading{
"mlir-disable-threading",
llvm::cl::desc("Disabling multi-threading within MLIR")};
llvm::cl::opt<bool> printOpOnDiagnostic{
"mlir-print-op-on-diagnostic",
llvm::cl::desc("When a diagnostic is emitted on an operation, also print "
"the operation as an attached note"),
llvm::cl::init(true)};
llvm::cl::opt<bool> printStackTraceOnDiagnostic{
"mlir-print-stacktrace-on-diagnostic",
llvm::cl::desc("When a diagnostic is emitted, also print the stack trace "
"as an attached note")};
};
} // end anonymous namespace
static llvm::ManagedStatic<MLIRContextOptions> clOptions;
/// Register a set of useful command-line options that can be used to configure
/// various flags within the MLIRContext. These flags are used when constructing
/// an MLIR context for initialization.
void mlir::registerMLIRContextCLOptions() {
// Make sure that the options struct has been initialized.
*clOptions;
}
//===----------------------------------------------------------------------===//
// Builtin Dialect
//===----------------------------------------------------------------------===//
namespace {
/// A builtin dialect to define types/etc that are necessary for the validity of
/// the IR.
struct BuiltinDialect : public Dialect {
BuiltinDialect(MLIRContext *context)
: Dialect(/*name=*/"", context, TypeID::get<BuiltinDialect>()) {
addAttributes<AffineMapAttr, ArrayAttr, DenseIntOrFPElementsAttr,
DenseStringElementsAttr, DictionaryAttr, FloatAttr,
SymbolRefAttr, IntegerAttr, IntegerSetAttr, OpaqueAttr,
OpaqueElementsAttr, SparseElementsAttr, StringAttr, TypeAttr,
UnitAttr>();
addAttributes<CallSiteLoc, FileLineColLoc, FusedLoc, NameLoc, OpaqueLoc,
UnknownLoc>();
addTypes<ComplexType, FloatType, FunctionType, IndexType, IntegerType,
MemRefType, UnrankedMemRefType, NoneType, OpaqueType,
RankedTensorType, TupleType, UnrankedTensorType, VectorType>();
// TODO: These operations should be moved to a different dialect when they
// have been fully decoupled from the core.
addOperations<FuncOp, ModuleOp, ModuleTerminatorOp>();
}
static StringRef getDialectNamespace() { return ""; }
};
} // end anonymous namespace.
//===----------------------------------------------------------------------===//
// Locking Utilities
//===----------------------------------------------------------------------===//
namespace {
/// Utility reader lock that takes a runtime flag that specifies if we really
/// need to lock.
struct ScopedReaderLock {
ScopedReaderLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
: mutex(shouldLock ? &mutexParam : nullptr) {
if (mutex)
mutex->lock_shared();
}
~ScopedReaderLock() {
if (mutex)
mutex->unlock_shared();
}
llvm::sys::SmartRWMutex<true> *mutex;
};
/// Utility writer lock that takes a runtime flag that specifies if we really
/// need to lock.
struct ScopedWriterLock {
ScopedWriterLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
: mutex(shouldLock ? &mutexParam : nullptr) {
if (mutex)
mutex->lock();
}
~ScopedWriterLock() {
if (mutex)
mutex->unlock();
}
llvm::sys::SmartRWMutex<true> *mutex;
};
} // end anonymous namespace.
//===----------------------------------------------------------------------===//
// AffineMap and IntegerSet hashing
//===----------------------------------------------------------------------===//
/// A utility function to safely get or create a uniqued instance within the
/// given set container.
template <typename ValueT, typename DenseInfoT, typename KeyT,
typename ConstructorFn>
static ValueT safeGetOrCreate(DenseSet<ValueT, DenseInfoT> &container,
KeyT &&key, llvm::sys::SmartRWMutex<true> &mutex,
bool threadingIsEnabled,
ConstructorFn &&constructorFn) {
// Check for an existing instance in read-only mode.
if (threadingIsEnabled) {
llvm::sys::SmartScopedReader<true> instanceLock(mutex);
auto it = container.find_as(key);
if (it != container.end())
return *it;
}
// Acquire a writer-lock so that we can safely create the new instance.
ScopedWriterLock instanceLock(mutex, threadingIsEnabled);
// Check for an existing instance again here, because another writer thread
// may have already created one. Otherwise, construct a new instance.
auto existing = container.insert_as(ValueT(), key);
if (existing.second)
return *existing.first = constructorFn();
return *existing.first;
}
namespace {
struct AffineMapKeyInfo : DenseMapInfo<AffineMap> {
// Affine maps are uniqued based on their dim/symbol counts and affine
// expressions.
using KeyTy = std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>>;
using DenseMapInfo<AffineMap>::isEqual;
static unsigned getHashValue(const AffineMap &key) {
return getHashValue(
KeyTy(key.getNumDims(), key.getNumSymbols(), key.getResults()));
}
static unsigned getHashValue(KeyTy key) {
return hash_combine(
std::get<0>(key), std::get<1>(key),
hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()));
}
static bool isEqual(const KeyTy &lhs, AffineMap rhs) {
if (rhs == getEmptyKey() || rhs == getTombstoneKey())
return false;
return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
rhs.getResults());
}
};
struct IntegerSetKeyInfo : DenseMapInfo<IntegerSet> {
// Integer sets are uniqued based on their dim/symbol counts, affine
// expressions appearing in the LHS of constraints, and eqFlags.
using KeyTy =
std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>, ArrayRef<bool>>;
using DenseMapInfo<IntegerSet>::isEqual;
static unsigned getHashValue(const IntegerSet &key) {
return getHashValue(KeyTy(key.getNumDims(), key.getNumSymbols(),
key.getConstraints(), key.getEqFlags()));
}
static unsigned getHashValue(KeyTy key) {
return hash_combine(
std::get<0>(key), std::get<1>(key),
hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
hash_combine_range(std::get<3>(key).begin(), std::get<3>(key).end()));
}
static bool isEqual(const KeyTy &lhs, IntegerSet rhs) {
if (rhs == getEmptyKey() || rhs == getTombstoneKey())
return false;
return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
rhs.getConstraints(), rhs.getEqFlags());
}
};
} // end anonymous namespace.
//===----------------------------------------------------------------------===//
// MLIRContextImpl
//===----------------------------------------------------------------------===//
namespace mlir {
/// This is the implementation of the MLIRContext class, using the pImpl idiom.
/// This class is completely private to this file, so everything is public.
class MLIRContextImpl {
public:
//===--------------------------------------------------------------------===//
// Identifier uniquing
//===--------------------------------------------------------------------===//
// Identifier allocator and mutex for thread safety.
llvm::BumpPtrAllocator identifierAllocator;
llvm::sys::SmartRWMutex<true> identifierMutex;
//===--------------------------------------------------------------------===//
// Diagnostics
//===--------------------------------------------------------------------===//
DiagnosticEngine diagEngine;
//===--------------------------------------------------------------------===//
// Options
//===--------------------------------------------------------------------===//
/// In most cases, creating operation in unregistered dialect is not desired
/// and indicate a misconfiguration of the compiler. This option enables to
/// detect such use cases
bool allowUnregisteredDialects = false;
/// Enable support for multi-threading within MLIR.
bool threadingIsEnabled = true;
/// If the operation should be attached to diagnostics printed via the
/// Operation::emit methods.
bool printOpOnDiagnostic = true;
/// If the current stack trace should be attached when emitting diagnostics.
bool printStackTraceOnDiagnostic = false;
//===--------------------------------------------------------------------===//
// Other
//===--------------------------------------------------------------------===//
/// This is a list of dialects that are created referring to this context.
/// The MLIRContext owns the objects.
std::vector<std::unique_ptr<Dialect>> dialects;
/// This is a mapping from operation name to AbstractOperation for registered
/// operations.
llvm::StringMap<AbstractOperation> registeredOperations;
/// These are identifiers uniqued into this MLIRContext.
llvm::StringSet<llvm::BumpPtrAllocator &> identifiers;
/// An allocator used for AbstractAttribute and AbstractType objects.
llvm::BumpPtrAllocator abstractDialectSymbolAllocator;
//===--------------------------------------------------------------------===//
// Affine uniquing
//===--------------------------------------------------------------------===//
// Affine allocator and mutex for thread safety.
llvm::BumpPtrAllocator affineAllocator;
llvm::sys::SmartRWMutex<true> affineMutex;
// Affine map uniquing.
using AffineMapSet = DenseSet<AffineMap, AffineMapKeyInfo>;
AffineMapSet affineMaps;
// Integer set uniquing.
using IntegerSets = DenseSet<IntegerSet, IntegerSetKeyInfo>;
IntegerSets integerSets;
// Affine expression uniquing.
StorageUniquer affineUniquer;
//===--------------------------------------------------------------------===//
// Type uniquing
//===--------------------------------------------------------------------===//
DenseMap<TypeID, const AbstractType *> registeredTypes;
StorageUniquer typeUniquer;
/// Cached Type Instances.
FloatType bf16Ty, f16Ty, f32Ty, f64Ty;
IndexType indexTy;
IntegerType int1Ty, int8Ty, int16Ty, int32Ty, int64Ty, int128Ty;
NoneType noneType;
//===--------------------------------------------------------------------===//
// Attribute uniquing
//===--------------------------------------------------------------------===//
DenseMap<TypeID, const AbstractAttribute *> registeredAttributes;
StorageUniquer attributeUniquer;
/// Cached Attribute Instances.
BoolAttr falseAttr, trueAttr;
UnitAttr unitAttr;
UnknownLoc unknownLocAttr;
DictionaryAttr emptyDictionaryAttr;
public:
MLIRContextImpl() : identifiers(identifierAllocator) {}
~MLIRContextImpl() {
for (auto typeMapping : registeredTypes)
typeMapping.second->~AbstractType();
for (auto attrMapping : registeredAttributes)
attrMapping.second->~AbstractAttribute();
}
};
} // end namespace mlir
MLIRContext::MLIRContext() : impl(new MLIRContextImpl()) {
// Initialize values based on the command line flags if they were provided.
if (clOptions.isConstructed()) {
disableMultithreading(clOptions->disableThreading);
printOpOnDiagnostic(clOptions->printOpOnDiagnostic);
printStackTraceOnDiagnostic(clOptions->printStackTraceOnDiagnostic);
}
// Register dialects with this context.
getOrCreateDialect<BuiltinDialect>();
registerAllDialects(this);
// Initialize several common attributes and types to avoid the need to lock
// the context when accessing them.
//// Types.
/// Floating-point Types.
impl->bf16Ty = TypeUniquer::get<FloatType>(this, StandardTypes::BF16);
impl->f16Ty = TypeUniquer::get<FloatType>(this, StandardTypes::F16);
impl->f32Ty = TypeUniquer::get<FloatType>(this, StandardTypes::F32);
impl->f64Ty = TypeUniquer::get<FloatType>(this, StandardTypes::F64);
/// Index Type.
impl->indexTy = TypeUniquer::get<IndexType>(this, StandardTypes::Index);
/// Integer Types.
impl->int1Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer, 1,
IntegerType::Signless);
impl->int8Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer, 8,
IntegerType::Signless);
impl->int16Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
16, IntegerType::Signless);
impl->int32Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
32, IntegerType::Signless);
impl->int64Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
64, IntegerType::Signless);
impl->int128Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
128, IntegerType::Signless);
/// None Type.
impl->noneType = TypeUniquer::get<NoneType>(this, StandardTypes::None);
//// Attributes.
//// Note: These must be registered after the types as they may generate one
//// of the above types internally.
/// Bool Attributes.
impl->falseAttr = AttributeUniquer::get<IntegerAttr>(
this, StandardAttributes::Integer, impl->int1Ty,
APInt(/*numBits=*/1, false))
.cast<BoolAttr>();
impl->trueAttr = AttributeUniquer::get<IntegerAttr>(
this, StandardAttributes::Integer, impl->int1Ty,
APInt(/*numBits=*/1, true))
.cast<BoolAttr>();
/// Unit Attribute.
impl->unitAttr =
AttributeUniquer::get<UnitAttr>(this, StandardAttributes::Unit);
/// Unknown Location Attribute.
impl->unknownLocAttr = AttributeUniquer::get<UnknownLoc>(
this, StandardAttributes::UnknownLocation);
/// The empty dictionary attribute.
impl->emptyDictionaryAttr = AttributeUniquer::get<DictionaryAttr>(
this, StandardAttributes::Dictionary, ArrayRef<NamedAttribute>());
// Register the affine storage objects with the uniquer.
impl->affineUniquer.registerStorageType(
TypeID::get<AffineBinaryOpExprStorage>());
impl->affineUniquer.registerStorageType(
TypeID::get<AffineConstantExprStorage>());
impl->affineUniquer.registerStorageType(TypeID::get<AffineDimExprStorage>());
}
MLIRContext::~MLIRContext() {}
/// Copy the specified array of elements into memory managed by the provided
/// bump pointer allocator. This assumes the elements are all PODs.
template <typename T>
static ArrayRef<T> copyArrayRefInto(llvm::BumpPtrAllocator &allocator,
ArrayRef<T> elements) {
auto result = allocator.Allocate<T>(elements.size());
std::uninitialized_copy(elements.begin(), elements.end(), result);
return ArrayRef<T>(result, elements.size());
}
//===----------------------------------------------------------------------===//
// Diagnostic Handlers
//===----------------------------------------------------------------------===//
/// Returns the diagnostic engine for this context.
DiagnosticEngine &MLIRContext::getDiagEngine() { return getImpl().diagEngine; }
//===----------------------------------------------------------------------===//
// Dialect and Operation Registration
//===----------------------------------------------------------------------===//
/// Return information about all registered IR dialects.
std::vector<Dialect *> MLIRContext::getRegisteredDialects() {
std::vector<Dialect *> result;
result.reserve(impl->dialects.size());
for (auto &dialect : impl->dialects)
result.push_back(dialect.get());
return result;
}
/// Get a registered IR dialect with the given namespace. If none is found,
/// then return nullptr.
Dialect *MLIRContext::getRegisteredDialect(StringRef name) {
// Dialects are sorted by name, so we can use binary search for lookup.
auto it = llvm::lower_bound(
impl->dialects, name,
[](const auto &lhs, StringRef rhs) { return lhs->getNamespace() < rhs; });
return (it != impl->dialects.end() && (*it)->getNamespace() == name)
? (*it).get()
: nullptr;
}
/// Get a dialect for the provided namespace and TypeID: abort the program if a
/// dialect exist for this namespace with different TypeID. Returns a pointer to
/// the dialect owned by the context.
Dialect *
MLIRContext::getOrCreateDialect(StringRef dialectNamespace, TypeID dialectID,
function_ref<std::unique_ptr<Dialect>()> ctor) {
auto &impl = getImpl();
// Get the correct insertion position sorted by namespace.
auto insertPt =
llvm::lower_bound(impl.dialects, nullptr,
[&](const std::unique_ptr<Dialect> &lhs,
const std::unique_ptr<Dialect> &rhs) {
if (!lhs)
return dialectNamespace < rhs->getNamespace();
return lhs->getNamespace() < dialectNamespace;
});
// Abort if dialect with namespace has already been registered.
if (insertPt != impl.dialects.end() &&
(*insertPt)->getNamespace() == dialectNamespace) {
if ((*insertPt)->getTypeID() == dialectID)
return insertPt->get();
llvm::report_fatal_error("a dialect with namespace '" + dialectNamespace +
"' has already been registered");
}
auto it = impl.dialects.insert(insertPt, ctor());
return &**it;
}
bool MLIRContext::allowsUnregisteredDialects() {
return impl->allowUnregisteredDialects;
}
void MLIRContext::allowUnregisteredDialects(bool allowing) {
impl->allowUnregisteredDialects = allowing;
}
/// Return true if multi-threading is disabled by the context.
bool MLIRContext::isMultithreadingEnabled() {
return impl->threadingIsEnabled && llvm::llvm_is_multithreaded();
}
/// Set the flag specifying if multi-threading is disabled by the context.
void MLIRContext::disableMultithreading(bool disable) {
impl->threadingIsEnabled = !disable;
// Update the threading mode for each of the uniquers.
impl->affineUniquer.disableMultithreading(disable);
impl->attributeUniquer.disableMultithreading(disable);
impl->typeUniquer.disableMultithreading(disable);
}
/// Return true if we should attach the operation to diagnostics emitted via
/// Operation::emit.
bool MLIRContext::shouldPrintOpOnDiagnostic() {
return impl->printOpOnDiagnostic;
}
/// Set the flag specifying if we should attach the operation to diagnostics
/// emitted via Operation::emit.
void MLIRContext::printOpOnDiagnostic(bool enable) {
impl->printOpOnDiagnostic = enable;
}
/// Return true if we should attach the current stacktrace to diagnostics when
/// emitted.
bool MLIRContext::shouldPrintStackTraceOnDiagnostic() {
return impl->printStackTraceOnDiagnostic;
}
/// Set the flag specifying if we should attach the current stacktrace when
/// emitting diagnostics.
void MLIRContext::printStackTraceOnDiagnostic(bool enable) {
impl->printStackTraceOnDiagnostic = enable;
}
/// Return information about all registered operations. This isn't very
/// efficient, typically you should ask the operations about their properties
/// directly.
std::vector<AbstractOperation *> MLIRContext::getRegisteredOperations() {
// We just have the operations in a non-deterministic hash table order. Dump
// into a temporary array, then sort it by operation name to get a stable
// ordering.
llvm::StringMap<AbstractOperation> ®isteredOps =
impl->registeredOperations;
std::vector<AbstractOperation *> result;
result.reserve(registeredOps.size());
for (auto &elt : registeredOps)
result.push_back(&elt.second);
llvm::array_pod_sort(
result.begin(), result.end(),
[](AbstractOperation *const *lhs, AbstractOperation *const *rhs) {
return (*lhs)->name.compare((*rhs)->name);
});
return result;
}
bool MLIRContext::isOperationRegistered(StringRef name) {
return impl->registeredOperations.count(name);
}
void Dialect::addOperation(AbstractOperation opInfo) {
assert((getNamespace().empty() || opInfo.dialect.name == getNamespace()) &&
"op name doesn't start with dialect namespace");
assert(&opInfo.dialect == this && "Dialect object mismatch");
auto &impl = context->getImpl();
StringRef opName = opInfo.name;
if (!impl.registeredOperations.insert({opName, std::move(opInfo)}).second) {
llvm::errs() << "error: operation named '" << opInfo.name
<< "' is already registered.\n";
abort();
}
}
void Dialect::addType(TypeID typeID, AbstractType &&typeInfo) {
auto &impl = context->getImpl();
auto *newInfo =
new (impl.abstractDialectSymbolAllocator.Allocate<AbstractType>())
AbstractType(std::move(typeInfo));
if (!impl.registeredTypes.insert({typeID, newInfo}).second)
llvm::report_fatal_error("Dialect Type already registered.");
impl.typeUniquer.registerStorageType(typeID);
}
void Dialect::addAttribute(TypeID typeID, AbstractAttribute &&attrInfo) {
auto &impl = context->getImpl();
auto *newInfo =
new (impl.abstractDialectSymbolAllocator.Allocate<AbstractAttribute>())
AbstractAttribute(std::move(attrInfo));
if (!impl.registeredAttributes.insert({typeID, newInfo}).second)
llvm::report_fatal_error("Dialect Attribute already registered.");
impl.attributeUniquer.registerStorageType(typeID);
}
/// Get the dialect that registered the attribute with the provided typeid.
const AbstractAttribute &AbstractAttribute::lookup(TypeID typeID,
MLIRContext *context) {
auto &impl = context->getImpl();
auto it = impl.registeredAttributes.find(typeID);
if (it == impl.registeredAttributes.end())
llvm::report_fatal_error("Trying to create an Attribute that was not "
"registered in this MLIRContext.");
return *it->second;
}
/// Look up the specified operation in the operation set and return a pointer
/// to it if present. Otherwise, return a null pointer.
const AbstractOperation *AbstractOperation::lookup(StringRef opName,
MLIRContext *context) {
auto &impl = context->getImpl();
auto it = impl.registeredOperations.find(opName);
if (it != impl.registeredOperations.end())
return &it->second;
return nullptr;
}
/// Get the dialect that registered the type with the provided typeid.
const AbstractType &AbstractType::lookup(TypeID typeID, MLIRContext *context) {
auto &impl = context->getImpl();
auto it = impl.registeredTypes.find(typeID);
if (it == impl.registeredTypes.end())
llvm::report_fatal_error(
"Trying to create a Type that was not registered in this MLIRContext.");
return *it->second;
}
//===----------------------------------------------------------------------===//
// Identifier uniquing
//===----------------------------------------------------------------------===//
/// Return an identifier for the specified string.
Identifier Identifier::get(StringRef str, MLIRContext *context) {
auto &impl = context->getImpl();
// Check for an existing identifier in read-only mode.
if (context->isMultithreadingEnabled()) {
llvm::sys::SmartScopedReader<true> contextLock(impl.identifierMutex);
auto it = impl.identifiers.find(str);
if (it != impl.identifiers.end())
return Identifier(&*it);
}
// Check invariants after seeing if we already have something in the
// identifier table - if we already had it in the table, then it already
// passed invariant checks.
assert(!str.empty() && "Cannot create an empty identifier");
assert(str.find('\0') == StringRef::npos &&
"Cannot create an identifier with a nul character");
// Acquire a writer-lock so that we can safely create the new instance.
ScopedWriterLock contextLock(impl.identifierMutex, impl.threadingIsEnabled);
auto it = impl.identifiers.insert(str).first;
return Identifier(&*it);
}
//===----------------------------------------------------------------------===//
// Type uniquing
//===----------------------------------------------------------------------===//
/// Returns the storage uniquer used for constructing type storage instances.
/// This should not be used directly.
StorageUniquer &MLIRContext::getTypeUniquer() { return getImpl().typeUniquer; }
FloatType FloatType::get(StandardTypes::Kind kind, MLIRContext *context) {
switch (kind) {
case StandardTypes::BF16:
return context->getImpl().bf16Ty;
case StandardTypes::F16:
return context->getImpl().f16Ty;
case StandardTypes::F32:
return context->getImpl().f32Ty;
case StandardTypes::F64:
return context->getImpl().f64Ty;
default:
llvm_unreachable("unexpected floating-point kind");
}
}
/// Get an instance of the IndexType.
IndexType IndexType::get(MLIRContext *context) {
return context->getImpl().indexTy;
}
/// Return an existing integer type instance if one is cached within the
/// context.
static IntegerType
getCachedIntegerType(unsigned width,
IntegerType::SignednessSemantics signedness,
MLIRContext *context) {
if (signedness != IntegerType::Signless)
return IntegerType();
switch (width) {
case 1:
return context->getImpl().int1Ty;
case 8:
return context->getImpl().int8Ty;
case 16:
return context->getImpl().int16Ty;
case 32:
return context->getImpl().int32Ty;
case 64:
return context->getImpl().int64Ty;
case 128:
return context->getImpl().int128Ty;
default:
return IntegerType();
}
}
IntegerType IntegerType::get(unsigned width, MLIRContext *context) {
return get(width, IntegerType::Signless, context);
}
IntegerType IntegerType::get(unsigned width,
IntegerType::SignednessSemantics signedness,
MLIRContext *context) {
if (auto cached = getCachedIntegerType(width, signedness, context))
return cached;
return Base::get(context, StandardTypes::Integer, width, signedness);
}
IntegerType IntegerType::getChecked(unsigned width, Location location) {
return getChecked(width, IntegerType::Signless, location);
}
IntegerType IntegerType::getChecked(unsigned width,
SignednessSemantics signedness,
Location location) {
if (auto cached =
getCachedIntegerType(width, signedness, location->getContext()))
return cached;
return Base::getChecked(location, StandardTypes::Integer, width, signedness);
}
/// Get an instance of the NoneType.
NoneType NoneType::get(MLIRContext *context) {
return context->getImpl().noneType;
}
//===----------------------------------------------------------------------===//
// Attribute uniquing
//===----------------------------------------------------------------------===//
/// Returns the storage uniquer used for constructing attribute storage
/// instances. This should not be used directly.
StorageUniquer &MLIRContext::getAttributeUniquer() {
return getImpl().attributeUniquer;
}
/// Initialize the given attribute storage instance.
void AttributeUniquer::initializeAttributeStorage(AttributeStorage *storage,
MLIRContext *ctx,
TypeID attrID) {
storage->initialize(AbstractAttribute::lookup(attrID, ctx));
// If the attribute did not provide a type, then default to NoneType.
if (!storage->getType())
storage->setType(NoneType::get(ctx));
}
BoolAttr BoolAttr::get(bool value, MLIRContext *context) {
return value ? context->getImpl().trueAttr : context->getImpl().falseAttr;
}
UnitAttr UnitAttr::get(MLIRContext *context) {
return context->getImpl().unitAttr;
}
Location UnknownLoc::get(MLIRContext *context) {
return context->getImpl().unknownLocAttr;
}
/// Return empty dictionary.
DictionaryAttr DictionaryAttr::getEmpty(MLIRContext *context) {
return context->getImpl().emptyDictionaryAttr;
}
//===----------------------------------------------------------------------===//
// AffineMap uniquing
//===----------------------------------------------------------------------===//
StorageUniquer &MLIRContext::getAffineUniquer() {
return getImpl().affineUniquer;
}
AffineMap AffineMap::getImpl(unsigned dimCount, unsigned symbolCount,
ArrayRef<AffineExpr> results,
MLIRContext *context) {
auto &impl = context->getImpl();
auto key = std::make_tuple(dimCount, symbolCount, results);
// Safely get or create an AffineMap instance.
return safeGetOrCreate(
impl.affineMaps, key, impl.affineMutex, impl.threadingIsEnabled, [&] {
auto *res = impl.affineAllocator.Allocate<detail::AffineMapStorage>();
// Copy the results into the bump pointer.
results = copyArrayRefInto(impl.affineAllocator, results);
// Initialize the memory using placement new.
new (res)
detail::AffineMapStorage{dimCount, symbolCount, results, context};
return AffineMap(res);
});
}
AffineMap AffineMap::get(MLIRContext *context) {
return getImpl(/*dimCount=*/0, /*symbolCount=*/0, /*results=*/{}, context);
}
AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
MLIRContext *context) {
return getImpl(dimCount, symbolCount, /*results=*/{}, context);
}
AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
AffineExpr result) {
return getImpl(dimCount, symbolCount, {result}, result.getContext());
}
AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
ArrayRef<AffineExpr> results, MLIRContext *context) {
return getImpl(dimCount, symbolCount, results, context);
}
//===----------------------------------------------------------------------===//
// Integer Sets: these are allocated into the bump pointer, and are immutable.
// Unlike AffineMap's, these are uniqued only if they are small.
//===----------------------------------------------------------------------===//
IntegerSet IntegerSet::get(unsigned dimCount, unsigned symbolCount,
ArrayRef<AffineExpr> constraints,
ArrayRef<bool> eqFlags) {
// The number of constraints can't be zero.
assert(!constraints.empty());
assert(constraints.size() == eqFlags.size());
auto &impl = constraints[0].getContext()->getImpl();
// A utility function to construct a new IntegerSetStorage instance.
auto constructorFn = [&] {
auto *res = impl.affineAllocator.Allocate<detail::IntegerSetStorage>();
// Copy the results and equality flags into the bump pointer.
constraints = copyArrayRefInto(impl.affineAllocator, constraints);
eqFlags = copyArrayRefInto(impl.affineAllocator, eqFlags);
// Initialize the memory using placement new.
new (res)
detail::IntegerSetStorage{dimCount, symbolCount, constraints, eqFlags};
return IntegerSet(res);
};
// If this instance is uniqued, then we handle it separately so that multiple
// threads may simultaneously access existing instances.
if (constraints.size() < IntegerSet::kUniquingThreshold) {
auto key = std::make_tuple(dimCount, symbolCount, constraints, eqFlags);
return safeGetOrCreate(impl.integerSets, key, impl.affineMutex,
impl.threadingIsEnabled, constructorFn);
}
// Otherwise, acquire a writer-lock so that we can safely create the new
// instance.
ScopedWriterLock affineLock(impl.affineMutex, impl.threadingIsEnabled);
return constructorFn();
}
//===----------------------------------------------------------------------===//
// StorageUniquerSupport
//===----------------------------------------------------------------------===//
/// Utility method to generate a default location for use when checking the
/// construction invariants of a storage object. This is defined out-of-line to
/// avoid the need to include Location.h.
const AttributeStorage *
mlir::detail::generateUnknownStorageLocation(MLIRContext *ctx) {
return reinterpret_cast<const AttributeStorage *>(
ctx->getImpl().unknownLocAttr.getAsOpaquePointer());
}
|
#include <click/config.h>
#include "automarkipheader.hh"
#include <click/args.hh>
#include <clicknet/ip.h>
#include <clicknet/ether.h>
CLICK_DECLS
AutoMarkIPHeader::AutoMarkIPHeader() :
_ethertype_8021q(htons(ETHERTYPE_8021Q)),
_ethertype_ip(htons(ETHERTYPE_IP)),
_ethertype_ip6(htons(ETHERTYPE_IP6))
{
}
AutoMarkIPHeader::~AutoMarkIPHeader()
{
}
Packet *
AutoMarkIPHeader::simple_action(Packet *p)
{
assert(!p->mac_header() || p->mac_header() == p->data());
const click_ether_vlan *vlan = reinterpret_cast<const click_ether_vlan *>(p->data());
if (vlan->ether_vlan_proto == _ethertype_8021q) {
if (vlan->ether_vlan_encap_proto == _ethertype_ip) {
const click_ip *ip = reinterpret_cast<const click_ip *>(p->data() + sizeof(click_ether_vlan));
p->set_ip_header(ip, ip->ip_hl << 2);
} else if (vlan->ether_vlan_encap_proto == _ethertype_ip6) {
const click_ip6 *ip6 = reinterpret_cast<const click_ip6 *>(p->data() + sizeof(click_ether_vlan));
p->set_ip6_header(ip6, 10 << 2);
}
} else if (vlan->ether_vlan_proto == _ethertype_ip) {
const click_ip *ip = reinterpret_cast<const click_ip *>(p->data() + sizeof(click_ether));
p->set_ip_header(ip, ip->ip_hl << 2);
} else if (vlan->ether_vlan_proto == _ethertype_ip6) {
const click_ip6 *ip6 = reinterpret_cast<const click_ip6 *>(p->data() + sizeof(click_ether_vlan));
p->set_ip6_header(ip6, 10 << 2);
}
return p;
}
CLICK_ENDDECLS
EXPORT_ELEMENT(AutoMarkIPHeader)
ELEMENT_MT_SAFE(AutoMarkIPHeader)
|
//
// AABox.cpp
// libraries/octree/src
//
// Created by Brad Hefta-Gaub on 04/11/13.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "AABox.h"
#include "AACube.h"
#include "Transform.h"
#include "Extents.h"
#include "GeometryUtil.h"
#include "NumericalConstants.h"
const glm::vec3 AABox::INFINITY_VECTOR(std::numeric_limits<float>::infinity());
AABox::AABox(const AACube& other) :
_corner(other.getCorner()), _scale(other.getScale(), other.getScale(), other.getScale()) {
}
AABox::AABox(const Extents& other) :
_corner(other.minimum),
_scale(other.maximum - other.minimum) {
}
AABox::AABox(const glm::vec3& corner, float size) :
_corner(corner), _scale(size, size, size) {
};
AABox::AABox(const glm::vec3& corner, const glm::vec3& dimensions) :
_corner(corner), _scale(dimensions) {
};
AABox::AABox() : _corner(INFINITY_VECTOR), _scale(0.0f) {
};
glm::vec3 AABox::calcCenter() const {
glm::vec3 center(_corner);
center += (_scale * 0.5f);
return center;
}
glm::vec3 AABox::getVertex(BoxVertex vertex) const {
switch (vertex) {
case BOTTOM_LEFT_NEAR:
return _corner + glm::vec3(_scale.x, 0, 0);
case BOTTOM_RIGHT_NEAR:
return _corner;
case TOP_RIGHT_NEAR:
return _corner + glm::vec3(0, _scale.y, 0);
case TOP_LEFT_NEAR:
return _corner + glm::vec3(_scale.x, _scale.y, 0);
case BOTTOM_LEFT_FAR:
return _corner + glm::vec3(_scale.x, 0, _scale.z);
case BOTTOM_RIGHT_FAR:
return _corner + glm::vec3(0, 0, _scale.z);
case TOP_RIGHT_FAR:
return _corner + glm::vec3(0, _scale.y, _scale.z);
default: //quiet windows warnings
case TOP_LEFT_FAR:
return _corner + _scale;
}
}
void AABox::setBox(const glm::vec3& corner, float scale) {
_corner = corner;
_scale = glm::vec3(scale, scale, scale);
}
void AABox::setBox(const glm::vec3& corner, const glm::vec3& scale) {
_corner = corner;
_scale = scale;
}
glm::vec3 AABox::getFarthestVertex(const glm::vec3& normal) const {
glm::vec3 result = _corner;
// This is a branchless version of:
//if (normal.x > 0.0f) {
// result.x += _scale.x;
//}
//if (normal.y > 0.0f) {
// result.y += _scale.y;
//}
//if (normal.z > 0.0f) {
// result.z += _scale.z;
//}
float blend = (float)(normal.x > 0.0f);
result.x += blend * _scale.x + (1.0f - blend) * 0.0f;
blend = (float)(normal.y > 0.0f);
result.y += blend * _scale.y + (1.0f - blend) * 0.0f;
blend = (float)(normal.z > 0.0f);
result.z += blend * _scale.z + (1.0f - blend) * 0.0f;
return result;
}
glm::vec3 AABox::getNearestVertex(const glm::vec3& normal) const {
glm::vec3 result = _corner;
// This is a branchless version of:
//if (normal.x < 0.0f) {
// result.x += _scale.x;
//}
//if (normal.y < 0.0f) {
// result.y += _scale.y;
//}
//if (normal.z < 0.0f) {
// result.z += _scale.z;
//}
float blend = (float)(normal.x < 0.0f);
result.x += blend * _scale.x + (1.0f - blend) * 0.0f;
blend = (float)(normal.y < 0.0f);
result.y += blend * _scale.y + (1.0f - blend) * 0.0f;
blend = (float)(normal.z < 0.0f);
result.z += blend * _scale.z + (1.0f - blend) * 0.0f;
return result;
}
bool AABox::contains(const Triangle& triangle) const {
return contains(triangle.v0) && contains(triangle.v1) && contains(triangle.v2);
}
bool AABox::contains(const glm::vec3& point) const {
return aaBoxContains(point, _corner, _scale);
}
bool AABox::contains(const AABox& otherBox) const {
for (int v = BOTTOM_LEFT_NEAR; v < TOP_LEFT_FAR; v++) {
glm::vec3 vertex = otherBox.getVertex((BoxVertex)v);
if (!contains(vertex)) {
return false;
}
}
return true;
}
bool AABox::touches(const AABox& otherBox) const {
glm::vec3 relativeCenter = _corner - otherBox._corner + ((_scale - otherBox._scale) * 0.5f);
glm::vec3 totalHalfScale = (_scale + otherBox._scale) * 0.5f;
return fabsf(relativeCenter.x) <= totalHalfScale.x &&
fabsf(relativeCenter.y) <= totalHalfScale.y &&
fabsf(relativeCenter.z) <= totalHalfScale.z;
}
bool AABox::contains(const AACube& otherCube) const {
for (int v = BOTTOM_LEFT_NEAR; v < TOP_LEFT_FAR; v++) {
glm::vec3 vertex = otherCube.getVertex((BoxVertex)v);
if (!contains(vertex)) {
return false;
}
}
return true;
}
bool AABox::touches(const AACube& otherCube) const {
glm::vec3 relativeCenter = _corner - otherCube.getCorner() + ((_scale - otherCube.getDimensions()) * 0.5f);
glm::vec3 totalHalfScale = (_scale + otherCube.getDimensions()) * 0.5f;
return fabsf(relativeCenter.x) <= totalHalfScale.x &&
fabsf(relativeCenter.y) <= totalHalfScale.y &&
fabsf(relativeCenter.z) <= totalHalfScale.z;
}
// determines whether a value is within the expanded extents
static bool isWithinExpanded(float value, float corner, float size, float expansion) {
return value >= corner - expansion && value <= corner + size + expansion;
}
bool AABox::expandedContains(const glm::vec3& point, float expansion) const {
return isWithinExpanded(point.x, _corner.x, _scale.x, expansion) &&
isWithinExpanded(point.y, _corner.y, _scale.y, expansion) &&
isWithinExpanded(point.z, _corner.z, _scale.z, expansion);
}
bool AABox::expandedIntersectsSegment(const glm::vec3& start, const glm::vec3& end, float expansion) const {
// handle the trivial cases where the expanded box contains the start or end
if (expandedContains(start, expansion) || expandedContains(end, expansion)) {
return true;
}
// check each axis
glm::vec3 expandedCorner = _corner - glm::vec3(expansion, expansion, expansion);
glm::vec3 expandedSize = _scale + glm::vec3(expansion, expansion, expansion) * 2.0f;
glm::vec3 direction = end - start;
float axisDistance;
return (findIntersection(start.x, direction.x, expandedCorner.x, expandedSize.x, axisDistance) &&
axisDistance >= 0.0f && axisDistance <= 1.0f &&
isWithin(start.y + axisDistance*direction.y, expandedCorner.y, expandedSize.y) &&
isWithin(start.z + axisDistance*direction.z, expandedCorner.z, expandedSize.z)) ||
(findIntersection(start.y, direction.y, expandedCorner.y, expandedSize.y, axisDistance) &&
axisDistance >= 0.0f && axisDistance <= 1.0f &&
isWithin(start.x + axisDistance*direction.x, expandedCorner.x, expandedSize.x) &&
isWithin(start.z + axisDistance*direction.z, expandedCorner.z, expandedSize.z)) ||
(findIntersection(start.z, direction.z, expandedCorner.z, expandedSize.z, axisDistance) &&
axisDistance >= 0.0f && axisDistance <= 1.0f &&
isWithin(start.y + axisDistance*direction.y, expandedCorner.y, expandedSize.y) &&
isWithin(start.x + axisDistance*direction.x, expandedCorner.x, expandedSize.x));
}
bool AABox::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, const glm::vec3& invDirection,
float& distance, BoxFace& face, glm::vec3& surfaceNormal) const {
return findRayAABoxIntersection(origin, direction, invDirection, _corner, _scale, distance, face, surfaceNormal);
}
bool AABox::findParabolaIntersection(const glm::vec3& origin, const glm::vec3& velocity, const glm::vec3& acceleration,
float& parabolicDistance, BoxFace& face, glm::vec3& surfaceNormal) const {
return findParabolaAABoxIntersection(origin, velocity, acceleration, _corner, _scale, parabolicDistance, face, surfaceNormal);
}
bool AABox::rayHitsBoundingSphere(const glm::vec3& origin, const glm::vec3& direction) const {
glm::vec3 localCenter = calcCenter() - origin;
float distance = glm::dot(localCenter, direction);
const float ONE_OVER_TWO_SQUARED = 0.25f;
float radiusSquared = ONE_OVER_TWO_SQUARED * glm::length2(_scale);
return (glm::length2(localCenter) < radiusSquared
|| (glm::abs(distance) > 0.0f && glm::distance2(distance * direction, localCenter) < radiusSquared));
}
bool AABox::parabolaPlaneIntersectsBoundingSphere(const glm::vec3& origin, const glm::vec3& velocity, const glm::vec3& acceleration, const glm::vec3& normal) const {
glm::vec3 localCenter = calcCenter() - origin;
const float ONE_OVER_TWO_SQUARED = 0.25f;
float radiusSquared = ONE_OVER_TWO_SQUARED * glm::length2(_scale);
// origin is inside the sphere
if (glm::length2(localCenter) < radiusSquared) {
return true;
}
if (glm::length2(acceleration) < EPSILON) {
// Handle the degenerate case where acceleration == (0, 0, 0)
return rayHitsBoundingSphere(origin, glm::normalize(velocity));
} else {
// Project vector from plane to sphere center onto the normal
float distance = glm::dot(localCenter, normal);
if (distance * distance < radiusSquared) {
return true;
}
}
return false;
}
bool AABox::touchesSphere(const glm::vec3& center, float radius) const {
// Avro's algorithm from this paper: http://www.mrtc.mdh.se/projects/3Dgraphics/paperF.pdf
glm::vec3 e = glm::max(_corner - center, Vectors::ZERO) + glm::max(center - _corner - _scale, Vectors::ZERO);
return glm::length2(e) <= radius * radius;
}
bool AABox::findSpherePenetration(const glm::vec3& center, float radius, glm::vec3& penetration) const {
glm::vec4 center4 = glm::vec4(center, 1.0f);
float minPenetrationLength = FLT_MAX;
for (int i = 0; i < FACE_COUNT; i++) {
glm::vec4 facePlane = getPlane((BoxFace)i);
glm::vec3 vector = getClosestPointOnFace(center, (BoxFace)i) - center;
if (glm::dot(center4, getPlane((BoxFace)i)) >= 0.0f) {
// outside this face, so use vector to closest point to determine penetration
return ::findSpherePenetration(vector, glm::vec3(-facePlane), radius, penetration);
}
float vectorLength = glm::length(vector);
if (vectorLength < minPenetrationLength) {
// remember the smallest penetration vector; if we're inside all faces, we'll use that
penetration = (vectorLength < EPSILON) ? glm::vec3(-facePlane) * radius :
vector * ((vectorLength + radius) / -vectorLength);
minPenetrationLength = vectorLength;
}
}
return true;
}
bool AABox::findCapsulePenetration(const glm::vec3& start, const glm::vec3& end, float radius, glm::vec3& penetration) const {
glm::vec4 start4 = glm::vec4(start, 1.0f);
glm::vec4 end4 = glm::vec4(end, 1.0f);
glm::vec4 startToEnd = glm::vec4(end - start, 0.0f);
float minPenetrationLength = FLT_MAX;
for (int i = 0; i < FACE_COUNT; i++) {
// find the vector from the segment to the closest point on the face (starting from deeper end)
glm::vec4 facePlane = getPlane((BoxFace)i);
glm::vec3 closest = (glm::dot(start4, facePlane) <= glm::dot(end4, facePlane)) ?
getClosestPointOnFace(start4, startToEnd, (BoxFace)i) : getClosestPointOnFace(end4, -startToEnd, (BoxFace)i);
glm::vec3 vector = -computeVectorFromPointToSegment(closest, start, end);
if (glm::dot(vector, glm::vec3(facePlane)) < 0.0f) {
// outside this face, so use vector to closest point to determine penetration
return ::findSpherePenetration(vector, glm::vec3(-facePlane), radius, penetration);
}
float vectorLength = glm::length(vector);
if (vectorLength < minPenetrationLength) {
// remember the smallest penetration vector; if we're inside all faces, we'll use that
penetration = (vectorLength < EPSILON) ? glm::vec3(-facePlane) * radius :
vector * ((vectorLength + radius) / -vectorLength);
minPenetrationLength = vectorLength;
}
}
return true;
}
glm::vec3 AABox::getClosestPointOnFace(const glm::vec3& point, BoxFace face) const {
switch (face) {
case MIN_X_FACE:
return glm::clamp(point, glm::vec3(_corner.x, _corner.y, _corner.z),
glm::vec3(_corner.x, _corner.y + _scale.y, _corner.z + _scale.z));
case MAX_X_FACE:
return glm::clamp(point, glm::vec3(_corner.x + _scale.x, _corner.y, _corner.z),
glm::vec3(_corner.x + _scale.x, _corner.y + _scale.y, _corner.z + _scale.z));
case MIN_Y_FACE:
return glm::clamp(point, glm::vec3(_corner.x, _corner.y, _corner.z),
glm::vec3(_corner.x + _scale.x, _corner.y, _corner.z + _scale.z));
case MAX_Y_FACE:
return glm::clamp(point, glm::vec3(_corner.x, _corner.y + _scale.y, _corner.z),
glm::vec3(_corner.x + _scale.x, _corner.y + _scale.y, _corner.z + _scale.z));
case MIN_Z_FACE:
return glm::clamp(point, glm::vec3(_corner.x, _corner.y, _corner.z),
glm::vec3(_corner.x + _scale.x, _corner.y + _scale.y, _corner.z));
default: //quiet windows warnings
case MAX_Z_FACE:
return glm::clamp(point, glm::vec3(_corner.x, _corner.y, _corner.z + _scale.z),
glm::vec3(_corner.x + _scale.x, _corner.y + _scale.y, _corner.z + _scale.z));
}
}
glm::vec3 AABox::getClosestPointOnFace(const glm::vec4& origin, const glm::vec4& direction, BoxFace face) const {
// check against the four planes that border the face
BoxFace oppositeFace = getOppositeFace(face);
bool anyOutside = false;
for (int i = 0; i < FACE_COUNT; i++) {
if (i == face || i == oppositeFace) {
continue;
}
glm::vec4 iPlane = getPlane((BoxFace)i);
float originDistance = glm::dot(origin, iPlane);
if (originDistance < 0.0f) {
continue; // inside the border
}
anyOutside = true;
float divisor = glm::dot(direction, iPlane);
if (fabsf(divisor) < EPSILON) {
continue; // segment is parallel to plane
}
// find intersection and see if it lies within face bounds
float directionalDistance = -originDistance / divisor;
glm::vec4 intersection = origin + direction * directionalDistance;
BoxFace iOppositeFace = getOppositeFace((BoxFace)i);
for (int j = 0; j < FACE_COUNT; j++) {
if (j == face || j == oppositeFace || j == i || j == iOppositeFace) {
continue;
}
if (glm::dot(intersection, getPlane((BoxFace)j)) > 0.0f) {
goto outerContinue; // intersection is out of bounds
}
}
return getClosestPointOnFace(glm::vec3(intersection), face);
outerContinue: ;
}
// if we were outside any of the sides, we must check against the diagonals
if (anyOutside) {
int faceAxis = face / 2;
int secondAxis = (faceAxis + 1) % 3;
int thirdAxis = (faceAxis + 2) % 3;
glm::vec4 secondAxisMinPlane = getPlane((BoxFace)(secondAxis * 2));
glm::vec4 secondAxisMaxPlane = getPlane((BoxFace)(secondAxis * 2 + 1));
glm::vec4 thirdAxisMaxPlane = getPlane((BoxFace)(thirdAxis * 2 + 1));
glm::vec4 offset = glm::vec4(0.0f, 0.0f, 0.0f,
glm::dot(glm::vec3(secondAxisMaxPlane + thirdAxisMaxPlane), _scale) * 0.5f);
glm::vec4 diagonals[] = { secondAxisMinPlane + thirdAxisMaxPlane + offset,
secondAxisMaxPlane + thirdAxisMaxPlane + offset };
float minDistance = FLT_MAX;
for (size_t i = 0; i < sizeof(diagonals) / sizeof(diagonals[0]); i++) {
float divisor = glm::dot(direction, diagonals[i]);
if (fabsf(divisor) < EPSILON) {
continue; // segment is parallel to diagonal plane
}
minDistance = glm::min(-glm::dot(origin, diagonals[i]) / divisor, minDistance);
}
if (minDistance != FLT_MAX) {
return getClosestPointOnFace(glm::vec3(origin + direction * minDistance), face);
}
}
// last resort or all inside: clamp origin to face
return getClosestPointOnFace(glm::vec3(origin), face);
}
bool AABox::touchesAAEllipsoid(const glm::vec3& center, const glm::vec3& radials) const {
// handle case where ellipsoid's alix-aligned box doesn't touch this AABox
if (_corner.x - radials.x > center.x ||
_corner.y - radials.y > center.y ||
_corner.z - radials.z > center.z ||
_corner.x + _scale.x + radials.x < center.x ||
_corner.y + _scale.y + radials.y < center.y ||
_corner.z + _scale.z + radials.z < center.z) {
return false;
}
// handle case where ellipsoid is entirely inside this AABox
if (contains(center)) {
return true;
}
for (int i = 0; i < FACE_COUNT; i++) {
glm::vec3 closest = getClosestPointOnFace(center, (BoxFace)i) - center;
float x = closest.x;
float y = closest.y;
float z = closest.z;
float a = radials.x;
float b = radials.y;
float c = radials.z;
if (x*x/(a*a) + y*y/(b*b) + z*z/(c*c) < 1.0f) {
return true;
}
}
return false;
}
glm::vec4 AABox::getPlane(BoxFace face) const {
switch (face) {
case MIN_X_FACE: return glm::vec4(-1.0f, 0.0f, 0.0f, _corner.x);
case MAX_X_FACE: return glm::vec4(1.0f, 0.0f, 0.0f, -_corner.x - _scale.x);
case MIN_Y_FACE: return glm::vec4(0.0f, -1.0f, 0.0f, _corner.y);
case MAX_Y_FACE: return glm::vec4(0.0f, 1.0f, 0.0f, -_corner.y - _scale.y);
case MIN_Z_FACE: return glm::vec4(0.0f, 0.0f, -1.0f, _corner.z);
default: //quiet windows warnings
case MAX_Z_FACE: return glm::vec4(0.0f, 0.0f, 1.0f, -_corner.z - _scale.z);
}
}
BoxFace AABox::getOppositeFace(BoxFace face) {
switch (face) {
case MIN_X_FACE: return MAX_X_FACE;
case MAX_X_FACE: return MIN_X_FACE;
case MIN_Y_FACE: return MAX_Y_FACE;
case MAX_Y_FACE: return MIN_Y_FACE;
case MIN_Z_FACE: return MAX_Z_FACE;
default: //quiet windows warnings
case MAX_Z_FACE: return MIN_Z_FACE;
}
}
AABox AABox::clamp(const glm::vec3& min, const glm::vec3& max) const {
glm::vec3 clampedCorner = glm::clamp(_corner, min, max);
glm::vec3 clampedTopFarLeft = glm::clamp(calcTopFarLeft(), min, max);
glm::vec3 clampedScale = clampedTopFarLeft - clampedCorner;
return AABox(clampedCorner, clampedScale);
}
AABox AABox::clamp(float min, float max) const {
glm::vec3 clampedCorner = glm::clamp(_corner, min, max);
glm::vec3 clampedTopFarLeft = glm::clamp(calcTopFarLeft(), min, max);
glm::vec3 clampedScale = clampedTopFarLeft - clampedCorner;
return AABox(clampedCorner, clampedScale);
}
void AABox::embiggen(float scale) {
_corner += scale * (-0.5f * _scale);
_scale *= scale;
}
void AABox::embiggen(const glm::vec3& scale) {
_corner += scale * (-0.5f * _scale);
_scale *= scale;
}
void AABox::setScaleStayCentered(const glm::vec3& scale) {
_corner += -0.5f * scale;
_scale = scale;
}
void AABox::scale(float scale) {
_corner *= scale;
_scale *= scale;
}
void AABox::scale(const glm::vec3& scale) {
_corner *= scale;
_scale *= scale;
}
void AABox::rotate(const glm::quat& rotation) {
auto minimum = _corner;
auto maximum = _corner + _scale;
glm::vec3 bottomLeftNear(minimum.x, minimum.y, minimum.z);
glm::vec3 bottomRightNear(maximum.x, minimum.y, minimum.z);
glm::vec3 bottomLeftFar(minimum.x, minimum.y, maximum.z);
glm::vec3 bottomRightFar(maximum.x, minimum.y, maximum.z);
glm::vec3 topLeftNear(minimum.x, maximum.y, minimum.z);
glm::vec3 topRightNear(maximum.x, maximum.y, minimum.z);
glm::vec3 topLeftFar(minimum.x, maximum.y, maximum.z);
glm::vec3 topRightFar(maximum.x, maximum.y, maximum.z);
glm::vec3 bottomLeftNearRotated = rotation * bottomLeftNear;
glm::vec3 bottomRightNearRotated = rotation * bottomRightNear;
glm::vec3 bottomLeftFarRotated = rotation * bottomLeftFar;
glm::vec3 bottomRightFarRotated = rotation * bottomRightFar;
glm::vec3 topLeftNearRotated = rotation * topLeftNear;
glm::vec3 topRightNearRotated = rotation * topRightNear;
glm::vec3 topLeftFarRotated = rotation * topLeftFar;
glm::vec3 topRightFarRotated = rotation * topRightFar;
minimum = glm::min(bottomLeftNearRotated,
glm::min(bottomRightNearRotated,
glm::min(bottomLeftFarRotated,
glm::min(bottomRightFarRotated,
glm::min(topLeftNearRotated,
glm::min(topRightNearRotated,
glm::min(topLeftFarRotated,
topRightFarRotated)))))));
maximum = glm::max(bottomLeftNearRotated,
glm::max(bottomRightNearRotated,
glm::max(bottomLeftFarRotated,
glm::max(bottomRightFarRotated,
glm::max(topLeftNearRotated,
glm::max(topRightNearRotated,
glm::max(topLeftFarRotated,
topRightFarRotated)))))));
_corner = minimum;
_scale = maximum - minimum;
}
void AABox::transform(const Transform& transform) {
scale(transform.getScale());
rotate(transform.getRotation());
translate(transform.getTranslation());
}
// Logic based on http://clb.demon.fi/MathGeoLib/nightly/docs/AABB.cpp_code.html#471
void AABox::transform(const glm::mat4& matrix) {
// FIXME use simd operations
auto halfSize = _scale * 0.5f;
auto center = _corner + halfSize;
halfSize = abs(halfSize);
auto mm = glm::transpose(glm::mat3(matrix));
vec3 newDir = vec3(
glm::dot(glm::abs(mm[0]), halfSize),
glm::dot(glm::abs(mm[1]), halfSize),
glm::dot(glm::abs(mm[2]), halfSize)
);
auto newCenter = transformPoint(matrix, center);
_corner = newCenter - newDir;
_scale = newDir * 2.0f;
}
AABox AABox::getOctreeChild(OctreeChild child) const {
AABox result(*this); // self
switch (child) {
case topLeftNear:
result._corner.y += _scale.y / 2.0f;
break;
case topLeftFar:
result._corner.y += _scale.y / 2.0f;
result._corner.z += _scale.z / 2.0f;
break;
case topRightNear:
result._corner.y += _scale.y / 2.0f;
result._corner.x += _scale.x / 2.0f;
break;
case topRightFar:
result._corner.y += _scale.y / 2.0f;
result._corner.x += _scale.x / 2.0f;
result._corner.z += _scale.z / 2.0f;
break;
case bottomLeftNear:
// _corner = same as parent
break;
case bottomLeftFar:
result._corner.z += _scale.z / 2.0f;
break;
case bottomRightNear:
result._corner.x += _scale.x / 2.0f;
break;
case bottomRightFar:
result._corner.x += _scale.x / 2.0f;
result._corner.z += _scale.z / 2.0f;
break;
}
result._scale /= 2.0f; // everything is half the scale
return result;
}
|
#include "ffmpges.h"
#include <QDebug>
#include <QFile>
#include <QDateTime>
extern "C" {
// 设备
//#include <libavdevice/avdevice.h>
// 工具(比如错误处理)
#include <libavutil/avutil.h>
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
}
FFmpges::FFmpges()
{
}
void printErrorMessage(const char *message, int errorCode){
char errbuf[1024];
av_strerror(errorCode, errbuf, sizeof(errbuf));
qDebug() << message << errbuf << errorCode;
}
/* check that a given sample format is supported by the encoder */
static int check_pix_fmt(const AVCodec *codec, enum AVPixelFormat pix_fmt)
{
const enum AVPixelFormat *p = codec->pix_fmts;
while (*p != AV_PIX_FMT_NONE) {
if (*p == pix_fmt)
return 1;
p++;
}
return 0;
}
static int encode(AVCodecContext *ctx, AVFrame *frame, AVPacket *pkt,
QFile *out)
{
int ret;
/* send the frame for encoding */
ret = avcodec_send_frame(ctx, frame);
if (ret < 0) {
qDebug() << "Error sending the frame to the encoder";
return ret;
}
/* read all the available output packets (in general there may be any
* number of them */
while (ret >= 0) {
ret = avcodec_receive_packet(ctx, pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
// 继续
return 0;
else if (ret < 0) {
qDebug() << "Error encoding audio frame";
// 出错了退出
return ret;
}
// fwrite(pkt->data, 1, pkt->size, output);
out->write((char *)pkt->data, pkt->size);
av_packet_unref(pkt);
}
}
void FFmpges::h264Encode(VideoEncodeSpec in, const char *out){
// 文件
QFile inFile(in.fileName);
QFile outFile(out);
// 返回值
int ret = 0;
// 编码器
AVCodec *codec = nullptr;
// 编码上下文
AVCodecContext *ctx = nullptr;
// 存放编码前的数据
AVFrame *frame = nullptr;
// 存放编码后的数据
AVPacket *pkt = nullptr;
AVDictionary *options = nullptr;
int frameSize = av_image_get_buffer_size(in.format, in.width, in.height, 1);
uint8_t *buf = ( uint8_t *)malloc(frameSize);
// 创建编码器
const char* encoderName = "libx264";
codec = avcodec_find_encoder_by_name(encoderName);
if (!codec){
qDebug() << "encoder not found " << encoderName;
return;
}
qDebug() << codec->name;
// 创建编码上下文
ctx = avcodec_alloc_context3(codec);
if (!ctx){
qDebug() << "Could not allocate audio codec context";
return;
}
// 检查输入数据的采样格式。libfdk_aac必须是16位整数
/* check that the encoder supports sample_fmt input */
if (!check_pix_fmt(codec, in.format)) {
qDebug() << "Encoder does not support sample format " << av_get_sample_fmt_name(ctx->sample_fmt);
goto end;
}
ctx->pix_fmt = in.format;
// 设置输入参数
ctx->width = in.width;
ctx->height = in.height;
ctx->time_base = {1, in.fps};
// 设置输出参数
// ctx->bit_rate = 48000;
// ctx->profile = FF_PROFILE_AAC_HE_V2;
// // 设置一些编码器特殊的属性
// av_dict_set(&options,"vbr","1",0);
// 打开编码器
ret = avcodec_open2(ctx, codec, &options);
if (ret < 0){
qDebug() << "codec open error";
goto end;
}
// 打开文件
if (!inFile.open(QFile::ReadOnly)){
qDebug() << "file open error:" << in.fileName;
goto end;
}
if (!outFile.open(QFile::WriteOnly)){
qDebug() << "file open error:" << out;
goto end;
}
// 创建AVPacket
pkt = av_packet_alloc();
if (!pkt){
qDebug() << "could not allocate the packet";
goto end;
}
// 创建AVFrame
frame = av_frame_alloc();
if (!frame){
qDebug() << "Could not allocate audio frame";
goto end;
}
frame->format = ctx->pix_fmt;
frame->width = ctx->width;
frame->height = ctx->height;
frame->pts = 0;
// ret = av_frame_get_buffer(frame, 0);
// 创建输入缓冲区方法一
// ret = av_image_alloc(frame->data, frame->linesize, in.width, in.height, in.format,1);
ret = av_image_fill_arrays(frame->data, frame->linesize, buf,in.format, in.width, in.height, 1);
if (ret < 0) {
qDebug() << "Could not allocate audio data buffers";
goto end;
}
while ((ret = inFile.read((char *)frame->data[0], frameSize)) > 0) {
// if (ret < frame->linesize[0]){
// int bytes_per_sample = av_get_bytes_per_sample((AVSampleFormat)frame->format);
// int channels = av_get_channel_layout_nb_channels(frame->channel_layout);
// frame->nb_samples = ret/( bytes_per_sample * channels );
// }
if(encode(ctx, frame, pkt, &outFile) < 0){
goto end;
}
frame->pts++;
}
/* flush the encoder */
encode(ctx, NULL, pkt, &outFile);
end:
inFile.close();
outFile.close();
if (frame){
av_freep(&frame->data[0]);
av_frame_free(&frame);
}
av_packet_free(&pkt);
avcodec_free_context(&ctx);
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 <vector>
#include <mesos/resources.hpp>
#include <mesos/scheduler.hpp>
#include <process/clock.hpp>
#include <process/gtest.hpp>
#include <process/owned.hpp>
#include <stout/gtest.hpp>
#include <stout/os.hpp>
#include "master/master.hpp"
#include "slave/slave.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/fetcher.hpp"
#include "messages/messages.hpp"
#include "tests/mesos.hpp"
using namespace process;
using mesos::internal::master::Master;
using mesos::internal::slave::Fetcher;
using mesos::internal::slave::MesosContainerizer;
using mesos::internal::slave::MesosContainerizerProcess;
using mesos::internal::slave::Slave;
using mesos::master::detector::MasterDetector;
using std::vector;
using testing::_;
using testing::Eq;
using testing::Return;
using testing::Unused;
namespace mesos {
namespace internal {
namespace tests {
class MemoryPressureMesosTest : public ContainerizerTest<MesosContainerizer>
{
public:
static void SetUpTestCase()
{
ContainerizerTest<MesosContainerizer>::SetUpTestCase();
// Verify that the dd command and its flags used in a bit are valid
// on this system.
ASSERT_EQ(0, os::system("dd count=1 bs=1M if=/dev/zero of=/dev/null"))
<< "Cannot find a compatible 'dd' command";
}
};
TEST_F(MemoryPressureMesosTest, CGROUPS_ROOT_Statistics)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
// We only care about memory cgroup for this test.
flags.isolation = "cgroups/mem";
flags.agent_subsystems = None();
Fetcher fetcher;
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
Offer offer = offers.get()[0];
// Run a task that triggers memory pressure event. We request 1G
// disk because we are going to write a 512 MB file repeatedly.
TaskInfo task = createTask(
offer.slave_id(),
Resources::parse("cpus:1;mem:256;disk:1024").get(),
"while true; do dd count=512 bs=1M if=/dev/zero of=./temp; done");
Future<TaskStatus> running;
Future<TaskStatus> killed;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&running))
.WillOnce(FutureArg<1>(&killed))
.WillRepeatedly(Return()); // Ignore subsequent updates.
driver.launchTasks(offer.id(), {task});
AWAIT_READY(running);
EXPECT_EQ(task.task_id(), running.get().task_id());
EXPECT_EQ(TASK_RUNNING, running.get().state());
Future<hashset<ContainerID>> containers = containerizer->containers();
AWAIT_READY(containers);
ASSERT_EQ(1u, containers.get().size());
ContainerID containerId = *(containers.get().begin());
// Wait a while for some memory pressure events to occur.
Duration waited = Duration::zero();
do {
Future<ResourceStatistics> usage = containerizer->usage(containerId);
AWAIT_READY(usage);
if (usage.get().mem_low_pressure_counter() > 0) {
// We will check the correctness of the memory pressure counters
// later, because the memory-hammering task is still active
// and potentially incrementing these counters.
break;
}
os::sleep(Milliseconds(100));
waited += Milliseconds(100);
} while (waited < Seconds(5));
EXPECT_LE(waited, Seconds(5));
// Pause the clock to ensure that the reaper doesn't reap the exited
// command executor and inform the containerizer/slave.
Clock::pause();
Clock::settle();
// Stop the memory-hammering task.
driver.killTask(task.task_id());
AWAIT_READY_FOR(killed, Seconds(120));
EXPECT_EQ(task.task_id(), killed->task_id());
EXPECT_EQ(TASK_KILLED, killed->state());
// Now check the correctness of the memory pressure counters.
Future<ResourceStatistics> usage = containerizer->usage(containerId);
AWAIT_READY(usage);
EXPECT_GE(usage.get().mem_low_pressure_counter(),
usage.get().mem_medium_pressure_counter());
EXPECT_GE(usage.get().mem_medium_pressure_counter(),
usage.get().mem_critical_pressure_counter());
Clock::resume();
driver.stop();
driver.join();
}
// Test that memory pressure listening is restarted after recovery.
TEST_F(MemoryPressureMesosTest, CGROUPS_ROOT_SlaveRecovery)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
// We only care about memory cgroup for this test.
flags.isolation = "cgroups/mem";
flags.agent_subsystems = None();
Fetcher fetcher;
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
// Enable checkpointing for the framework.
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.set_checkpoint(true);
MesosSchedulerDriver driver(
&sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
Offer offer = offers.get()[0];
// Run a task that triggers memory pressure event. We request 1G
// disk because we are going to write a 512 MB file repeatedly.
TaskInfo task = createTask(
offer.slave_id(),
Resources::parse("cpus:1;mem:256;disk:1024").get(),
"while true; do dd count=512 bs=1M if=/dev/zero of=./temp; done");
Future<TaskStatus> running;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&running));
Future<Nothing> _statusUpdateAcknowledgement =
FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement);
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(running);
EXPECT_EQ(task.task_id(), running.get().task_id());
EXPECT_EQ(TASK_RUNNING, running.get().state());
// Wait for the ACK to be checkpointed.
AWAIT_READY_FOR(_statusUpdateAcknowledgement, Seconds(120));
// We restart the slave to let it recover.
slave.get()->terminate();
// Set up so we can wait until the new slave updates the container's
// resources (this occurs after the executor has re-registered).
Future<Nothing> update =
FUTURE_DISPATCH(_, &MesosContainerizerProcess::update);
// Use the same flags.
_containerizer = MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(_containerizer);
containerizer.reset(_containerizer.get());
Future<SlaveReregisteredMessage> reregistered =
FUTURE_PROTOBUF(SlaveReregisteredMessage(), master.get()->pid, _);
slave = StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
AWAIT_READY(reregistered);
// Wait until the containerizer is updated.
AWAIT_READY(update);
Future<hashset<ContainerID>> containers = containerizer->containers();
AWAIT_READY(containers);
ASSERT_EQ(1u, containers.get().size());
ContainerID containerId = *(containers.get().begin());
// Wait a while for some memory pressure events to occur.
Duration waited = Duration::zero();
do {
Future<ResourceStatistics> usage = containerizer->usage(containerId);
AWAIT_READY(usage);
if (usage.get().mem_low_pressure_counter() > 0) {
// We will check the correctness of the memory pressure counters
// later, because the memory-hammering task is still active
// and potentially incrementing these counters.
break;
}
os::sleep(Milliseconds(100));
waited += Milliseconds(100);
} while (waited < Seconds(5));
EXPECT_LE(waited, Seconds(5));
// Pause the clock to ensure that the reaper doesn't reap the exited
// command executor and inform the containerizer/slave.
Clock::pause();
Clock::settle();
Future<TaskStatus> killed;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&killed));
// Stop the memory-hammering task.
driver.killTask(task.task_id());
AWAIT_READY_FOR(killed, Seconds(120));
EXPECT_EQ(task.task_id(), killed->task_id());
EXPECT_EQ(TASK_KILLED, killed->state());
// Now check the correctness of the memory pressure counters.
Future<ResourceStatistics> usage = containerizer->usage(containerId);
AWAIT_READY(usage);
EXPECT_GE(usage.get().mem_low_pressure_counter(),
usage.get().mem_medium_pressure_counter());
EXPECT_GE(usage.get().mem_medium_pressure_counter(),
usage.get().mem_critical_pressure_counter());
Clock::resume();
driver.stop();
driver.join();
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreD3D9TextureManager.h"
#include "OgreD3D9Texture.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreD3D9Mappings.h"
#include "OgreRoot.h"
#include "OgreD3D9RenderSystem.h"
namespace Ogre
{
D3D9TextureManager::D3D9TextureManager() : TextureManager()
{
// register with group manager
ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this);
}
D3D9TextureManager::~D3D9TextureManager()
{
// unregister with group manager
ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType);
}
Resource* D3D9TextureManager::createImpl(const String& name,
ResourceHandle handle, const String& group, bool isManual,
ManualResourceLoader* loader, const NameValuePairList* createParams)
{
D3D9Texture* ret = OGRE_NEW D3D9Texture(this, name, handle, group, isManual, loader);
return ret;
}
PixelFormat D3D9TextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage)
{
// Basic filtering
D3DFORMAT d3dPF = D3D9Mappings::_getPF(D3D9Mappings::_getClosestSupportedPF(format));
// Calculate usage
DWORD d3dusage = 0;
D3DPOOL pool = D3DPOOL_MANAGED;
if (usage & TU_RENDERTARGET)
{
d3dusage |= D3DUSAGE_RENDERTARGET;
pool = D3DPOOL_DEFAULT;
}
if (usage & TU_DYNAMIC)
{
d3dusage |= D3DUSAGE_DYNAMIC;
pool = D3DPOOL_DEFAULT;
}
IDirect3DDevice9* pCurDevice = D3D9RenderSystem::getActiveD3D9Device();
// Use D3DX to adjust pixel format
switch(ttype)
{
case TEX_TYPE_1D:
case TEX_TYPE_2D:
D3DXCheckTextureRequirements(pCurDevice, NULL, NULL, NULL, d3dusage, &d3dPF, pool);
break;
case TEX_TYPE_3D:
D3DXCheckVolumeTextureRequirements(pCurDevice, NULL, NULL, NULL, NULL, d3dusage, &d3dPF, pool);
break;
case TEX_TYPE_CUBE_MAP:
D3DXCheckCubeTextureRequirements(pCurDevice, NULL, NULL, d3dusage, &d3dPF, pool);
break;
};
return D3D9Mappings::_getPF(d3dPF);
}
bool D3D9TextureManager::isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage,
bool preciseFormatOnly)
{
if (!preciseFormatOnly)
format = getNativeFormat(ttype, format, usage);
D3D9RenderSystem* rs = static_cast<D3D9RenderSystem*>(
Root::getSingleton().getRenderSystem());
return rs->_checkTextureFilteringSupported(ttype, format, usage);
}
}
|
#line 17 "./glslang.l"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is auto-generated by generate_parser.sh. DO NOT EDIT!
// Ignore errors in auto-generated code.
#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wswitch-enum"
#elif defined(_MSC_VER)
#pragma warning(disable: 4005)
#pragma warning(disable: 4065)
#pragma warning(disable: 4189)
#pragma warning(disable: 4244)
#pragma warning(disable: 4505)
#pragma warning(disable: 4701)
#pragma warning(disable: 4702)
#endif
#line 28 "./glslang_lex.cpp"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 39
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
typedef uint64_t flex_uint64_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
#define YY_TYPEDEF_YY_SCANNER_T
typedef void* yyscan_t;
#endif
/* For convenience, these vars (plus the bison vars far below)
are macros in the reentrant scanner. */
#define yyin yyg->yyin_r
#define yyout yyg->yyout_r
#define yyextra yyg->yyextra_r
#define yyleng yyg->yyleng_r
#define yytext yyg->yytext_r
#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno)
#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
#define yy_flex_debug yyg->yy_flex_debug_r
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE yyrestart(yyin ,yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
/* Note: We specifically omit the test for yy_rule_can_match_eol because it requires
* access to the local variable yy_act. Since yyless() is a macro, it would break
* existing scanners that call yyless() from OUTSIDE yylex.
* One obvious solution it to make yy_act a global. I tried that, and saw
* a 5% performance hit in a non-yylineno scanner, because yy_act is
* normally declared as a register variable-- so it is not worth it.
*/
#define YY_LESS_LINENO(n) \
do { \
yy_size_t yyl;\
for ( yyl = n; yyl < yyleng; ++yyl )\
if ( yytext[yyl] == '\n' )\
--yylineno;\
}while(0)
#define YY_LINENO_REWIND_TO(dst) \
do {\
const char *p;\
for ( p = yy_cp-1; p >= (dst); --p)\
if ( *p == '\n' )\
--yylineno;\
}while(0)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = yyg->yy_hold_char; \
YY_RESTORE_YY_MORE_OFFSET \
yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
yy_size_t yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
void yyrestart (FILE *input_file ,yyscan_t yyscanner );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
void yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
void yypop_buffer_state (yyscan_t yyscanner );
static void yyensure_buffer_stack (yyscan_t yyscanner );
static void yy_load_buffer_state (yyscan_t yyscanner );
static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner );
void *yyalloc (yy_size_t ,yyscan_t yyscanner );
void *yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
void yyfree (void * ,yyscan_t yyscanner );
#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define yywrap(yyscanner) 1
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
static int yy_get_next_buffer (yyscan_t yyscanner );
static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
*/
#define YY_DO_BEFORE_ACTION \
yyg->yytext_ptr = yy_bp; \
yyleng = (yy_size_t) (yy_cp - yy_bp); \
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
#define YY_NUM_RULES 240
#define YY_END_OF_BUFFER 241
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[820] =
{ 0,
0, 0, 0, 0, 241, 239, 238, 238, 222, 228,
233, 217, 218, 226, 225, 214, 223, 221, 227, 180,
180, 215, 211, 229, 216, 230, 234, 177, 219, 220,
232, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 212, 231, 213, 224, 237, 236, 240, 235, 208,
194, 213, 202, 197, 192, 200, 190, 201, 191, 186,
193, 185, 179, 180, 0, 183, 0, 220, 212, 219,
209, 205, 207, 206, 210, 177, 198, 204, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
12, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 15, 177, 177, 23, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 199, 203, 235, 0, 189, 185, 0, 188, 182,
0, 184, 178, 195, 196, 177, 136, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
13, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 27, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 24, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 0, 186,
0, 185, 187, 181, 177, 177, 177, 30, 177, 177,
18, 174, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 16, 139, 177, 177, 177, 177, 21, 177,
177, 143, 155, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 152, 4, 35, 36, 37,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 142, 31, 177, 177, 28, 177,
177, 177, 177, 177, 177, 177, 47, 48, 49, 29,
177, 177, 177, 177, 177, 177, 10, 53, 54, 55,
177, 137, 177, 177, 7, 177, 177, 177, 177, 164,
165, 166, 177, 32, 177, 156, 26, 167, 168, 169,
2, 161, 162, 163, 177, 177, 177, 25, 159, 177,
177, 177, 50, 51, 52, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 86, 177, 177, 177,
177, 177, 177, 177, 153, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 138, 177, 177, 176,
56, 57, 58, 177, 177, 14, 177, 91, 177, 177,
177, 177, 89, 177, 177, 177, 154, 149, 92, 177,
177, 177, 177, 177, 177, 144, 177, 177, 177, 78,
38, 41, 43, 42, 39, 45, 44, 46, 40, 177,
177, 177, 177, 160, 135, 177, 177, 147, 177, 177,
177, 34, 87, 173, 22, 148, 77, 177, 158, 17,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 19, 33, 177, 177, 177, 177,
177, 177, 93, 94, 95, 177, 177, 177, 177, 177,
3, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 140, 177, 177, 177, 177, 177, 8, 177,
177, 9, 177, 177, 177, 177, 20, 79, 11, 150,
97, 98, 99, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 145, 177, 177, 177, 81,
83, 80, 177, 177, 177, 177, 177, 177, 177, 141,
101, 102, 103, 177, 177, 157, 177, 146, 177, 177,
6, 177, 177, 177, 177, 177, 177, 177, 177, 177,
96, 151, 1, 177, 177, 177, 177, 177, 175, 177,
90, 5, 170, 59, 62, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 177, 82, 177,
177, 177, 177, 100, 177, 177, 177, 177, 177, 120,
66, 67, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 88, 177, 177, 177, 104,
122, 70, 71, 177, 177, 84, 177, 177, 177, 177,
177, 177, 177, 115, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 129, 177, 177, 177, 177, 60,
177, 177, 177, 177, 177, 177, 177, 177, 177, 177,
177, 177, 116, 105, 177, 106, 177, 177, 177, 130,
177, 177, 68, 177, 177, 177, 177, 177, 177, 177,
177, 177, 177, 177, 177, 177, 117, 177, 177, 131,
177, 177, 72, 107, 108, 177, 111, 177, 112, 177,
177, 177, 177, 177, 85, 177, 177, 177, 177, 64,
177, 63, 126, 177, 177, 109, 110, 177, 177, 177,
177, 177, 177, 177, 177, 177, 177, 124, 127, 118,
177, 65, 177, 177, 177, 177, 177, 177, 177, 177,
125, 128, 177, 177, 121, 69, 177, 177, 171, 177,
177, 177, 74, 177, 177, 123, 73, 177, 177, 177,
177, 177, 177, 132, 177, 177, 177, 177, 177, 177,
133, 177, 177, 177, 75, 177, 134, 113, 114, 177,
177, 177, 61, 177, 177, 172, 119, 76, 0
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 4, 1, 1, 1, 5, 6, 1, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 20, 20, 21, 21, 22, 23, 24,
25, 26, 27, 1, 28, 29, 30, 31, 32, 33,
34, 34, 34, 34, 34, 34, 35, 34, 36, 34,
34, 37, 38, 34, 39, 34, 34, 40, 34, 34,
41, 1, 42, 43, 44, 1, 45, 46, 47, 48,
49, 50, 51, 52, 53, 34, 54, 55, 56, 57,
58, 59, 34, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_int32_t yy_meta[73] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 1, 3, 3, 3,
3, 2, 2, 4, 4, 4, 4, 4, 4, 4,
1, 1, 1, 4, 3, 3, 3, 3, 2, 2,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 1, 1,
1, 1
} ;
static yyconst flex_int16_t yy_base[825] =
{ 0,
0, 0, 72, 0, 1016, 1017, 1017, 1017, 990, 120,
141, 1017, 1017, 989, 138, 1017, 137, 135, 988, 154,
208, 986, 1017, 154, 986, 132, 1017, 0, 1017, 1017,
139, 130, 123, 140, 147, 133, 177, 952, 186, 151,
139, 116, 161, 946, 173, 959, 193, 199, 208, 215,
108, 1017, 184, 1017, 1017, 1017, 1017, 1017, 0, 1017,
1017, 1017, 1017, 1017, 1017, 1017, 1017, 1017, 1017, 230,
1017, 235, 235, 0, 271, 1017, 0, 1017, 1017, 1017,
982, 1017, 1017, 1017, 981, 0, 1017, 1017, 943, 948,
152, 945, 953, 952, 939, 942, 953, 243, 947, 935,
932, 945, 932, 929, 929, 935, 147, 248, 929, 939,
925, 931, 934, 935, 0, 927, 937, 249, 936, 931,
912, 177, 916, 929, 920, 184, 913, 250, 925, 927,
257, 916, 913, 902, 911, 249, 257, 915, 911, 913,
902, 905, 196, 217, 269, 914, 902, 914, 262, 907,
906, 1017, 1017, 0, 311, 1017, 292, 328, 1017, 1017,
335, 342, 257, 1017, 1017, 905, 0, 901, 896, 900,
909, 906, 315, 890, 890, 901, 893, 215, 903, 900,
900, 898, 895, 887, 893, 880, 878, 890, 876, 892,
0, 889, 877, 884, 881, 885, 886, 879, 876, 865,
864, 877, 880, 868, 876, 864, 870, 861, 316, 866,
869, 860, 867, 856, 860, 851, 865, 864, 855, 861,
307, 845, 848, 846, 856, 846, 841, 839, 841, 851,
837, 839, 836, 847, 846, 849, 831, 316, 839, 835,
833, 842, 821, 353, 839, 841, 830, 822, 363, 370,
378, 389, 1017, 1017, 819, 829, 828, 0, 826, 383,
0, 0, 819, 817, 817, 818, 813, 821, 810, 827,
816, 394, 0, 0, 810, 820, 819, 819, 0, 804,
397, 0, 0, 806, 400, 813, 814, 805, 799, 798,
799, 798, 798, 406, 793, 0, 0, 789, 788, 787,
789, 790, 795, 789, 785, 798, 793, 793, 791, 790,
784, 778, 780, 779, 783, 775, 778, 773, 781, 786,
774, 771, 783, 774, 0, 0, 780, 776, 0, 768,
768, 773, 764, 771, 409, 768, 0, 0, 0, 0,
758, 770, 769, 768, 769, 769, 0, 0, 0, 0,
756, 0, 764, 755, 0, 754, 755, 749, 759, 0,
0, 0, 750, 0, 746, 0, 0, 0, 0, 0,
0, 0, 0, 0, 756, 413, 755, 0, 0, 753,
749, 746, 0, 0, 0, 738, 415, 418, 427, 743,
739, 744, 735, 733, 746, 731, 0, 731, 744, 733,
729, 735, 730, 737, 0, 735, 732, 736, 720, 718,
721, 727, 733, 728, 727, 715, 0, 717, 718, 0,
0, 0, 0, 715, 718, 0, 712, 0, 725, 705,
714, 709, 0, 702, 702, 715, 0, 717, 0, 431,
730, 729, 728, 695, 694, 0, 711, 710, 705, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 694,
707, 694, 691, 0, 0, 696, 695, 0, 692, 699,
698, 0, 684, 0, 0, 0, 0, 681, 0, 0,
680, 691, 434, 684, 690, 689, 686, 681, 678, 671,
671, 684, 669, 681, 0, 0, 674, 697, 696, 695,
662, 661, 427, 428, 0, 673, 676, 674, 663, 659,
0, 671, 668, 667, 657, 656, 646, 663, 649, 441,
657, 660, 0, 677, 676, 675, 642, 641, 0, 655,
642, 0, 652, 645, 646, 649, 0, 0, 0, 0,
669, 668, 0, 645, 648, 633, 640, 631, 638, 639,
639, 638, 624, 451, 636, 0, 637, 626, 625, 0,
0, 0, 650, 649, 648, 615, 614, 610, 618, 0,
646, 645, 0, 622, 625, 0, 458, 0, 603, 612,
0, 608, 607, 616, 616, 604, 618, 602, 616, 611,
0, 0, 0, 628, 627, 626, 593, 592, 0, 592,
0, 0, 434, 454, 616, 602, 605, 588, 600, 588,
587, 596, 596, 613, 612, 611, 578, 577, 0, 577,
578, 577, 587, 0, 590, 586, 588, 584, 571, 602,
449, 0, 579, 582, 574, 566, 573, 564, 585, 573,
569, 571, 569, 569, 568, 0, 556, 555, 565, 0,
585, 462, 0, 562, 565, 0, 565, 564, 548, 540,
548, 538, 546, 0, 543, 542, 563, 551, 549, 549,
533, 536, 550, 534, 565, 545, 546, 543, 540, 550,
527, 541, 540, 524, 523, 522, 543, 531, 529, 529,
510, 509, 0, 537, 509, 535, 507, 511, 510, 541,
521, 518, 0, 517, 520, 516, 518, 502, 499, 512,
497, 498, 505, 499, 488, 487, 0, 493, 492, 523,
503, 500, 0, 0, 0, 496, 0, 495, 0, 501,
500, 484, 481, 482, 0, 474, 482, 472, 478, 499,
478, 0, 0, 490, 489, 0, 0, 488, 487, 471,
468, 469, 483, 482, 459, 458, 464, 0, 0, 485,
457, 483, 475, 467, 453, 132, 161, 177, 215, 245,
0, 0, 288, 289, 0, 0, 294, 315, 0, 316,
306, 331, 0, 363, 402, 0, 0, 395, 383, 395,
387, 433, 434, 0, 435, 420, 461, 427, 430, 431,
0, 450, 452, 443, 0, 464, 0, 0, 0, 445,
446, 440, 0, 441, 442, 0, 0, 0, 1017, 506,
509, 512, 513, 514
} ;
static yyconst flex_int16_t yy_def[825] =
{ 0,
819, 1, 819, 3, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 820, 819, 819,
819, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 819, 819, 819, 819, 819, 819, 819, 821, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 822,
819, 823, 20, 21, 819, 819, 824, 819, 819, 819,
819, 819, 819, 819, 819, 820, 819, 819, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 819, 819, 821, 819, 819, 823, 819, 819, 819,
819, 819, 824, 819, 819, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 819, 819,
819, 819, 819, 819, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 820, 820,
820, 820, 820, 820, 820, 820, 820, 820, 0, 819,
819, 819, 819, 819
} ;
static yyconst flex_int16_t yy_nxt[1090] =
{ 0,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 21, 21, 21, 21,
21, 22, 23, 24, 25, 26, 27, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
29, 30, 31, 28, 32, 33, 34, 35, 36, 37,
38, 39, 40, 28, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 28, 28, 28, 52, 53,
54, 55, 56, 57, 58, 56, 56, 56, 56, 56,
56, 56, 56, 56, 56, 56, 56, 56, 56, 56,
56, 56, 56, 56, 56, 56, 56, 56, 56, 59,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 56, 56, 56, 59, 59, 59, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59, 59, 59,
56, 56, 56, 56, 61, 62, 63, 66, 68, 70,
70, 70, 70, 70, 70, 70, 84, 85, 79, 150,
123, 69, 67, 87, 124, 64, 72, 151, 73, 73,
73, 73, 73, 73, 74, 80, 89, 81, 82, 784,
92, 88, 93, 121, 95, 75, 94, 103, 96, 104,
90, 91, 76, 77, 97, 99, 122, 98, 105, 100,
115, 187, 75, 116, 101, 125, 117, 118, 152, 168,
102, 119, 188, 169, 120, 785, 76, 128, 126, 77,
72, 106, 74, 74, 74, 74, 74, 74, 74, 107,
112, 108, 129, 207, 109, 130, 212, 132, 113, 75,
110, 208, 213, 786, 133, 134, 76, 139, 135, 114,
140, 236, 237, 153, 136, 137, 75, 138, 141, 147,
143, 155, 156, 148, 144, 142, 158, 159, 145, 238,
76, 146, 149, 160, 819, 267, 268, 239, 155, 156,
161, 787, 161, 158, 159, 162, 162, 162, 162, 162,
162, 162, 189, 227, 176, 254, 215, 160, 177, 178,
819, 220, 229, 199, 788, 190, 200, 201, 228, 216,
202, 217, 203, 240, 245, 230, 246, 221, 222, 254,
249, 241, 249, 158, 159, 250, 250, 250, 250, 250,
250, 250, 298, 299, 300, 789, 790, 251, 791, 251,
158, 159, 252, 252, 252, 252, 252, 252, 252, 162,
162, 162, 162, 162, 162, 162, 162, 162, 162, 162,
162, 162, 162, 261, 312, 330, 792, 793, 313, 337,
338, 339, 794, 331, 253, 795, 262, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250, 250, 250,
250, 253, 252, 252, 252, 252, 252, 252, 252, 348,
349, 350, 156, 252, 252, 252, 252, 252, 252, 252,
360, 361, 362, 368, 369, 370, 372, 373, 374, 156,
796, 159, 383, 384, 385, 421, 422, 423, 441, 442,
443, 451, 452, 453, 454, 455, 456, 797, 159, 798,
799, 444, 445, 457, 458, 459, 498, 499, 500, 524,
525, 526, 800, 801, 546, 548, 563, 564, 565, 501,
502, 636, 527, 528, 547, 549, 594, 595, 596, 566,
567, 637, 568, 614, 615, 616, 666, 802, 803, 597,
598, 638, 804, 667, 805, 668, 617, 618, 639, 686,
640, 641, 806, 807, 808, 809, 687, 810, 688, 811,
812, 813, 814, 815, 816, 817, 818, 86, 86, 86,
154, 154, 154, 70, 157, 163, 163, 783, 782, 781,
780, 779, 778, 777, 776, 775, 774, 773, 772, 771,
770, 769, 768, 767, 766, 765, 764, 763, 762, 761,
760, 759, 758, 757, 756, 755, 754, 753, 752, 751,
750, 749, 748, 747, 746, 745, 744, 743, 742, 741,
740, 739, 738, 737, 736, 735, 734, 733, 732, 731,
730, 729, 728, 727, 726, 725, 724, 723, 722, 721,
720, 719, 718, 717, 716, 715, 714, 713, 712, 711,
710, 709, 708, 707, 706, 705, 704, 703, 702, 701,
700, 699, 698, 697, 696, 695, 694, 693, 692, 691,
690, 689, 685, 684, 683, 682, 681, 680, 679, 678,
677, 676, 675, 674, 673, 672, 671, 670, 669, 665,
664, 663, 662, 661, 660, 659, 658, 657, 656, 655,
654, 653, 652, 651, 650, 649, 648, 647, 646, 645,
644, 643, 642, 635, 634, 633, 632, 631, 630, 629,
628, 627, 626, 625, 624, 623, 622, 621, 620, 619,
613, 612, 611, 610, 609, 608, 607, 606, 605, 604,
603, 602, 601, 600, 599, 593, 592, 591, 590, 589,
588, 587, 586, 585, 584, 583, 582, 581, 580, 579,
578, 577, 576, 575, 574, 573, 572, 571, 570, 569,
562, 561, 560, 559, 558, 557, 556, 555, 554, 553,
552, 551, 550, 545, 544, 543, 542, 541, 540, 539,
538, 537, 536, 535, 534, 533, 532, 531, 530, 529,
523, 522, 521, 520, 519, 518, 517, 516, 515, 514,
513, 512, 511, 510, 509, 508, 507, 506, 505, 504,
503, 497, 496, 495, 494, 493, 492, 491, 490, 489,
488, 487, 486, 485, 484, 483, 482, 481, 480, 479,
478, 477, 476, 475, 474, 473, 472, 471, 470, 469,
468, 467, 466, 465, 464, 463, 462, 461, 460, 450,
449, 448, 447, 446, 440, 439, 438, 437, 436, 435,
434, 433, 432, 431, 430, 429, 428, 427, 426, 425,
424, 420, 419, 418, 417, 416, 415, 414, 413, 412,
411, 410, 409, 408, 407, 406, 405, 404, 403, 402,
401, 400, 399, 398, 397, 396, 395, 394, 393, 392,
391, 390, 389, 388, 387, 386, 382, 381, 380, 379,
378, 377, 376, 375, 371, 367, 366, 365, 364, 363,
359, 358, 357, 356, 355, 354, 353, 352, 351, 347,
346, 345, 344, 343, 342, 341, 340, 336, 335, 334,
333, 332, 329, 328, 327, 326, 325, 324, 323, 322,
321, 320, 319, 318, 317, 316, 315, 314, 311, 310,
309, 308, 307, 306, 305, 304, 303, 302, 301, 297,
296, 295, 294, 293, 292, 291, 290, 289, 288, 287,
286, 285, 284, 283, 282, 281, 280, 279, 278, 277,
276, 275, 274, 273, 272, 271, 270, 269, 266, 265,
264, 263, 260, 259, 258, 257, 256, 255, 248, 247,
244, 243, 242, 235, 234, 233, 232, 231, 226, 225,
224, 223, 219, 218, 214, 211, 210, 209, 206, 205,
204, 198, 197, 196, 195, 194, 193, 192, 191, 186,
185, 184, 183, 182, 181, 180, 179, 175, 174, 173,
172, 171, 170, 167, 166, 165, 164, 131, 127, 111,
83, 78, 71, 65, 60, 819, 5, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819
} ;
static yyconst flex_int16_t yy_chk[1090] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 10, 10, 11, 15, 17, 18,
18, 18, 18, 18, 18, 18, 26, 26, 24, 51,
42, 17, 15, 31, 42, 11, 20, 51, 20, 20,
20, 20, 20, 20, 20, 24, 32, 24, 24, 766,
33, 31, 33, 41, 34, 20, 33, 36, 34, 36,
32, 32, 20, 20, 34, 35, 41, 34, 36, 35,
40, 107, 20, 40, 35, 43, 40, 40, 53, 91,
35, 40, 107, 91, 40, 767, 20, 45, 43, 20,
21, 37, 21, 21, 21, 21, 21, 21, 21, 37,
39, 37, 45, 122, 37, 45, 126, 47, 39, 21,
37, 122, 126, 768, 47, 47, 21, 48, 47, 39,
48, 143, 143, 53, 47, 47, 21, 47, 48, 50,
49, 70, 70, 50, 49, 48, 72, 72, 49, 144,
21, 49, 50, 73, 73, 178, 178, 144, 70, 70,
75, 769, 75, 72, 72, 75, 75, 75, 75, 75,
75, 75, 108, 136, 98, 163, 128, 73, 98, 98,
73, 131, 137, 118, 770, 108, 118, 118, 136, 128,
118, 128, 118, 145, 149, 137, 149, 131, 131, 163,
155, 145, 155, 157, 157, 155, 155, 155, 155, 155,
155, 155, 209, 209, 209, 773, 774, 158, 777, 158,
157, 157, 158, 158, 158, 158, 158, 158, 158, 161,
161, 161, 161, 161, 161, 161, 162, 162, 162, 162,
162, 162, 162, 173, 221, 238, 778, 780, 221, 244,
244, 244, 781, 238, 162, 782, 173, 249, 249, 249,
249, 249, 249, 249, 250, 250, 250, 250, 250, 250,
250, 162, 251, 251, 251, 251, 251, 251, 251, 260,
260, 260, 250, 252, 252, 252, 252, 252, 252, 252,
272, 272, 272, 281, 281, 281, 285, 285, 285, 250,
784, 252, 294, 294, 294, 335, 335, 335, 376, 376,
376, 387, 387, 387, 388, 388, 388, 785, 252, 788,
789, 376, 376, 389, 389, 389, 440, 440, 440, 483,
483, 483, 790, 791, 503, 504, 520, 520, 520, 440,
440, 603, 483, 483, 503, 504, 554, 554, 554, 520,
520, 603, 520, 577, 577, 577, 631, 792, 793, 554,
554, 604, 795, 631, 796, 631, 577, 577, 604, 652,
604, 604, 797, 798, 799, 800, 652, 802, 652, 803,
804, 806, 810, 811, 812, 814, 815, 820, 820, 820,
821, 821, 821, 822, 823, 824, 824, 765, 764, 763,
762, 761, 760, 757, 756, 755, 754, 753, 752, 751,
750, 749, 748, 745, 744, 741, 740, 739, 738, 737,
736, 734, 733, 732, 731, 730, 728, 726, 722, 721,
720, 719, 718, 716, 715, 714, 713, 712, 711, 710,
709, 708, 707, 706, 705, 704, 702, 701, 700, 699,
698, 697, 696, 695, 694, 692, 691, 690, 689, 688,
687, 686, 685, 684, 683, 682, 681, 680, 679, 678,
677, 676, 675, 674, 673, 672, 671, 670, 669, 668,
667, 666, 665, 663, 662, 661, 660, 659, 658, 657,
655, 654, 651, 649, 648, 647, 645, 644, 643, 642,
641, 640, 639, 638, 637, 636, 635, 634, 633, 630,
629, 628, 627, 626, 625, 623, 622, 621, 620, 618,
617, 616, 615, 614, 613, 612, 611, 610, 609, 608,
607, 606, 605, 600, 598, 597, 596, 595, 594, 590,
589, 588, 587, 586, 585, 584, 583, 582, 580, 579,
575, 574, 572, 571, 569, 568, 567, 566, 565, 564,
563, 559, 558, 557, 555, 553, 552, 551, 550, 549,
548, 547, 546, 545, 544, 542, 541, 536, 535, 534,
533, 531, 530, 528, 527, 526, 525, 524, 522, 521,
519, 518, 517, 516, 515, 514, 513, 512, 510, 509,
508, 507, 506, 502, 501, 500, 499, 498, 497, 494,
493, 492, 491, 490, 489, 488, 487, 486, 485, 484,
482, 481, 478, 473, 471, 470, 469, 467, 466, 463,
462, 461, 460, 449, 448, 447, 445, 444, 443, 442,
441, 438, 436, 435, 434, 432, 431, 430, 429, 427,
425, 424, 419, 418, 416, 415, 414, 413, 412, 411,
410, 409, 408, 407, 406, 404, 403, 402, 401, 400,
399, 398, 396, 395, 394, 393, 392, 391, 390, 386,
382, 381, 380, 377, 375, 365, 363, 359, 358, 357,
356, 354, 353, 351, 346, 345, 344, 343, 342, 341,
336, 334, 333, 332, 331, 330, 328, 327, 324, 323,
322, 321, 320, 319, 318, 317, 316, 315, 314, 313,
312, 311, 310, 309, 308, 307, 306, 305, 304, 303,
302, 301, 300, 299, 298, 295, 293, 292, 291, 290,
289, 288, 287, 286, 284, 280, 278, 277, 276, 275,
271, 270, 269, 268, 267, 266, 265, 264, 263, 259,
257, 256, 255, 248, 247, 246, 245, 243, 242, 241,
240, 239, 237, 236, 235, 234, 233, 232, 231, 230,
229, 228, 227, 226, 225, 224, 223, 222, 220, 219,
218, 217, 216, 215, 214, 213, 212, 211, 210, 208,
207, 206, 205, 204, 203, 202, 201, 200, 199, 198,
197, 196, 195, 194, 193, 192, 190, 189, 188, 187,
186, 185, 184, 183, 182, 181, 180, 179, 177, 176,
175, 174, 172, 171, 170, 169, 168, 166, 151, 150,
148, 147, 146, 142, 141, 140, 139, 138, 135, 134,
133, 132, 130, 129, 127, 125, 124, 123, 121, 120,
119, 117, 116, 114, 113, 112, 111, 110, 109, 106,
105, 104, 103, 102, 101, 100, 99, 97, 96, 95,
94, 93, 92, 90, 89, 85, 81, 46, 44, 38,
25, 22, 19, 14, 9, 5, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819, 819,
819, 819, 819, 819, 819, 819, 819, 819, 819
} ;
/* Table of booleans, true if rule could match eol. */
static yyconst flex_int32_t yy_rule_can_match_eol[241] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
0, };
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
/*
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
This file contains the Lex specification for GLSL ES.
Based on ANSI C grammar, Lex specification:
http://www.lysator.liu.se/c/ANSI-C-grammar-l.html
IF YOU MODIFY THIS FILE YOU ALSO NEED TO RUN generate_parser.sh,
WHICH GENERATES THE GLSL ES LEXER (glslang_lex.cpp).
*/
#include "compiler/translator/glslang.h"
#include "compiler/translator/ParseContext.h"
#include "compiler/preprocessor/Token.h"
#include "compiler/translator/util.h"
#include "compiler/translator/length_limits.h"
#include "glslang_tab.h"
/* windows only pragma */
#ifdef _MSC_VER
#pragma warning(disable : 4102)
#endif
// Workaround for flex using the register keyword, deprecated in C++11.
#ifdef __cplusplus
#if __cplusplus > 199711L
#define register
#endif
#endif
#define YY_USER_ACTION \
yylloc->first_file = yylloc->last_file = yycolumn; \
yylloc->first_line = yylloc->last_line = yylineno;
#define YY_INPUT(buf, result, max_size) \
result = string_input(buf, max_size, yyscanner);
static yy_size_t string_input(char* buf, yy_size_t max_size, yyscan_t yyscanner);
static int check_type(yyscan_t yyscanner);
static int reserved_word(yyscan_t yyscanner);
static int ES2_reserved_ES3_keyword(TParseContext *context, int token);
static int ES2_keyword_ES3_reserved(TParseContext *context, int token);
static int ES2_ident_ES3_keyword(TParseContext *context, int token);
static int uint_constant(TParseContext *context);
static int int_constant(TParseContext *context);
static int float_constant(yyscan_t yyscanner);
static int floatsuffix_check(TParseContext* context);
#define INITIAL 0
#define FIELDS 1
#define YY_EXTRA_TYPE TParseContext*
/* Holds the entire state of the reentrant scanner. */
struct yyguts_t
{
/* User-defined. Not touched by flex. */
YY_EXTRA_TYPE yyextra_r;
/* The rest are the same as the globals declared in the non-reentrant scanner. */
FILE *yyin_r, *yyout_r;
size_t yy_buffer_stack_top; /**< index of top of stack. */
size_t yy_buffer_stack_max; /**< capacity of stack. */
YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */
char yy_hold_char;
yy_size_t yy_n_chars;
yy_size_t yyleng_r;
char *yy_c_buf_p;
int yy_init;
int yy_start;
int yy_did_buffer_switch_on_eof;
int yy_start_stack_ptr;
int yy_start_stack_depth;
int *yy_start_stack;
yy_state_type yy_last_accepting_state;
char* yy_last_accepting_cpos;
int yylineno_r;
int yy_flex_debug_r;
char *yytext_r;
int yy_more_flag;
int yy_more_len;
YYSTYPE * yylval_r;
YYLTYPE * yylloc_r;
}; /* end struct yyguts_t */
static int yy_init_globals (yyscan_t yyscanner );
/* This must go here because YYSTYPE and YYLTYPE are included
* from bison output in section 1.*/
# define yylval yyg->yylval_r
# define yylloc yyg->yylloc_r
int yylex_init (yyscan_t* scanner);
int yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (yyscan_t yyscanner );
int yyget_debug (yyscan_t yyscanner );
void yyset_debug (int debug_flag ,yyscan_t yyscanner );
YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner );
void yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
FILE *yyget_in (yyscan_t yyscanner );
void yyset_in (FILE * in_str ,yyscan_t yyscanner );
FILE *yyget_out (yyscan_t yyscanner );
void yyset_out (FILE * out_str ,yyscan_t yyscanner );
yy_size_t yyget_leng (yyscan_t yyscanner );
char *yyget_text (yyscan_t yyscanner );
int yyget_lineno (yyscan_t yyscanner );
void yyset_lineno (int line_number ,yyscan_t yyscanner );
int yyget_column (yyscan_t yyscanner );
void yyset_column (int column_no ,yyscan_t yyscanner );
YYSTYPE * yyget_lval (yyscan_t yyscanner );
void yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner );
YYLTYPE *yyget_lloc (yyscan_t yyscanner );
void yyset_lloc (YYLTYPE * yylloc_param ,yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (yyscan_t yyscanner );
#else
extern int yywrap (yyscan_t yyscanner );
#endif
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (yyscan_t yyscanner );
#else
static int input (yyscan_t yyscanner );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
size_t n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( yyin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(yyin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner)
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex \
(YYSTYPE * yylval_param,YYLTYPE * yylloc_param ,yyscan_t yyscanner);
#define YY_DECL int yylex \
(YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
yylloc = yylloc_param;
if ( !yyg->yy_init )
{
yyg->yy_init = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! yyg->yy_start )
yyg->yy_start = 1; /* first start state */
if ( ! yyin )
yyin = stdin;
if ( ! yyout )
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
}
yy_load_buffer_state(yyscanner );
}
{
TParseContext* context = yyextra;
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = yyg->yy_c_buf_p;
/* Support of yytext. */
*yy_cp = yyg->yy_hold_char;
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = yyg->yy_start;
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 820 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_current_state != 819 );
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
yy_find_action:
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] )
{
yy_size_t yyl;
for ( yyl = 0; yyl < yyleng; ++yyl )
if ( yytext[yyl] == '\n' )
do{ yylineno++;
yycolumn=0;
}while(0)
;
}
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = yyg->yy_hold_char;
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
case 1:
YY_RULE_SETUP
{ return INVARIANT; }
YY_BREAK
case 2:
YY_RULE_SETUP
{ return HIGH_PRECISION; }
YY_BREAK
case 3:
YY_RULE_SETUP
{ return MEDIUM_PRECISION; }
YY_BREAK
case 4:
YY_RULE_SETUP
{ return LOW_PRECISION; }
YY_BREAK
case 5:
YY_RULE_SETUP
{ return PRECISION; }
YY_BREAK
case 6:
YY_RULE_SETUP
{ return ES2_keyword_ES3_reserved(context, ATTRIBUTE); }
YY_BREAK
case 7:
YY_RULE_SETUP
{ return CONST_QUAL; }
YY_BREAK
case 8:
YY_RULE_SETUP
{ return UNIFORM; }
YY_BREAK
case 9:
YY_RULE_SETUP
{ return ES2_keyword_ES3_reserved(context, VARYING); }
YY_BREAK
case 10:
YY_RULE_SETUP
{ return BREAK; }
YY_BREAK
case 11:
YY_RULE_SETUP
{ return CONTINUE; }
YY_BREAK
case 12:
YY_RULE_SETUP
{ return DO; }
YY_BREAK
case 13:
YY_RULE_SETUP
{ return FOR; }
YY_BREAK
case 14:
YY_RULE_SETUP
{ return WHILE; }
YY_BREAK
case 15:
YY_RULE_SETUP
{ return IF; }
YY_BREAK
case 16:
YY_RULE_SETUP
{ return ELSE; }
YY_BREAK
case 17:
YY_RULE_SETUP
{ return ES2_reserved_ES3_keyword(context, SWITCH); }
YY_BREAK
case 18:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, CASE); }
YY_BREAK
case 19:
YY_RULE_SETUP
{ return ES2_reserved_ES3_keyword(context, DEFAULT); }
YY_BREAK
case 20:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, CENTROID); }
YY_BREAK
case 21:
YY_RULE_SETUP
{ return ES2_reserved_ES3_keyword(context, FLAT); }
YY_BREAK
case 22:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, SMOOTH); }
YY_BREAK
case 23:
YY_RULE_SETUP
{ return IN_QUAL; }
YY_BREAK
case 24:
YY_RULE_SETUP
{ return OUT_QUAL; }
YY_BREAK
case 25:
YY_RULE_SETUP
{ return INOUT_QUAL; }
YY_BREAK
case 26:
YY_RULE_SETUP
{ return FLOAT_TYPE; }
YY_BREAK
case 27:
YY_RULE_SETUP
{ return INT_TYPE; }
YY_BREAK
case 28:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, UINT_TYPE); }
YY_BREAK
case 29:
YY_RULE_SETUP
{ return VOID_TYPE; }
YY_BREAK
case 30:
YY_RULE_SETUP
{ return BOOL_TYPE; }
YY_BREAK
case 31:
YY_RULE_SETUP
{ yylval->lex.b = true; return BOOLCONSTANT; }
YY_BREAK
case 32:
YY_RULE_SETUP
{ yylval->lex.b = false; return BOOLCONSTANT; }
YY_BREAK
case 33:
YY_RULE_SETUP
{ return DISCARD; }
YY_BREAK
case 34:
YY_RULE_SETUP
{ return RETURN; }
YY_BREAK
case 35:
YY_RULE_SETUP
{ return MATRIX2; }
YY_BREAK
case 36:
YY_RULE_SETUP
{ return MATRIX3; }
YY_BREAK
case 37:
YY_RULE_SETUP
{ return MATRIX4; }
YY_BREAK
case 38:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX2); }
YY_BREAK
case 39:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX3); }
YY_BREAK
case 40:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX4); }
YY_BREAK
case 41:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX2x3); }
YY_BREAK
case 42:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX3x2); }
YY_BREAK
case 43:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX2x4); }
YY_BREAK
case 44:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX4x2); }
YY_BREAK
case 45:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX3x4); }
YY_BREAK
case 46:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, MATRIX4x3); }
YY_BREAK
case 47:
YY_RULE_SETUP
{ return VEC2; }
YY_BREAK
case 48:
YY_RULE_SETUP
{ return VEC3; }
YY_BREAK
case 49:
YY_RULE_SETUP
{ return VEC4; }
YY_BREAK
case 50:
YY_RULE_SETUP
{ return IVEC2; }
YY_BREAK
case 51:
YY_RULE_SETUP
{ return IVEC3; }
YY_BREAK
case 52:
YY_RULE_SETUP
{ return IVEC4; }
YY_BREAK
case 53:
YY_RULE_SETUP
{ return BVEC2; }
YY_BREAK
case 54:
YY_RULE_SETUP
{ return BVEC3; }
YY_BREAK
case 55:
YY_RULE_SETUP
{ return BVEC4; }
YY_BREAK
case 56:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, UVEC2); }
YY_BREAK
case 57:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, UVEC3); }
YY_BREAK
case 58:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, UVEC4); }
YY_BREAK
case 59:
YY_RULE_SETUP
{ return SAMPLER2D; }
YY_BREAK
case 60:
YY_RULE_SETUP
{ return SAMPLERCUBE; }
YY_BREAK
case 61:
YY_RULE_SETUP
{ return SAMPLER_EXTERNAL_OES; }
YY_BREAK
case 62:
YY_RULE_SETUP
{ return ES2_reserved_ES3_keyword(context, SAMPLER3D); }
YY_BREAK
case 63:
YY_RULE_SETUP
{ return ES2_reserved_ES3_keyword(context, SAMPLER3DRECT); }
YY_BREAK
case 64:
YY_RULE_SETUP
{ return SAMPLER2DRECT; }
YY_BREAK
case 65:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, SAMPLER2DARRAY); }
YY_BREAK
case 66:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, ISAMPLER2D); }
YY_BREAK
case 67:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, ISAMPLER3D); }
YY_BREAK
case 68:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, ISAMPLERCUBE); }
YY_BREAK
case 69:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, ISAMPLER2DARRAY); }
YY_BREAK
case 70:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, USAMPLER2D); }
YY_BREAK
case 71:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, USAMPLER3D); }
YY_BREAK
case 72:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, USAMPLERCUBE); }
YY_BREAK
case 73:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, USAMPLER2DARRAY); }
YY_BREAK
case 74:
YY_RULE_SETUP
{ return ES2_reserved_ES3_keyword(context, SAMPLER2DSHADOW); }
YY_BREAK
case 75:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, SAMPLERCUBESHADOW); }
YY_BREAK
case 76:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, SAMPLER2DARRAYSHADOW); }
YY_BREAK
case 77:
YY_RULE_SETUP
{ return STRUCT; }
YY_BREAK
case 78:
YY_RULE_SETUP
{ return ES2_ident_ES3_keyword(context, LAYOUT); }
YY_BREAK
/* Reserved keywords for GLSL ES 3.00 that are not reserved for GLSL ES 1.00 */
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 86:
case 87:
case 88:
case 89:
case 90:
case 91:
case 92:
case 93:
case 94:
case 95:
case 96:
case 97:
case 98:
case 99:
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
case 106:
case 107:
case 108:
case 109:
case 110:
case 111:
case 112:
case 113:
case 114:
case 115:
case 116:
case 117:
case 118:
case 119:
case 120:
case 121:
case 122:
case 123:
case 124:
case 125:
case 126:
case 127:
case 128:
case 129:
case 130:
case 131:
case 132:
case 133:
case 134:
YY_RULE_SETUP
{
if (context->getShaderVersion() < 300) {
yylval->lex.string = NewPoolTString(yytext);
return check_type(yyscanner);
}
return reserved_word(yyscanner);
}
YY_BREAK
/* Reserved keywords in GLSL ES 1.00 that are not reserved in GLSL ES 3.00 */
case 135:
YY_RULE_SETUP
{
if (context->getShaderVersion() >= 300)
{
yylval->lex.string = NewPoolTString(yytext);
return check_type(yyscanner);
}
return reserved_word(yyscanner);
}
YY_BREAK
/* Reserved keywords */
case 136:
case 137:
case 138:
case 139:
case 140:
case 141:
case 142:
case 143:
case 144:
case 145:
case 146:
case 147:
case 148:
case 149:
case 150:
case 151:
case 152:
case 153:
case 154:
case 155:
case 156:
case 157:
case 158:
case 159:
case 160:
case 161:
case 162:
case 163:
case 164:
case 165:
case 166:
case 167:
case 168:
case 169:
case 170:
case 171:
case 172:
case 173:
case 174:
case 175:
case 176:
YY_RULE_SETUP
{ return reserved_word(yyscanner); }
YY_BREAK
case 177:
YY_RULE_SETUP
{
yylval->lex.string = NewPoolTString(yytext);
return check_type(yyscanner);
}
YY_BREAK
case 178:
YY_RULE_SETUP
{ return int_constant(context); }
YY_BREAK
case 179:
YY_RULE_SETUP
{ return int_constant(context); }
YY_BREAK
case 180:
YY_RULE_SETUP
{ return int_constant(context); }
YY_BREAK
case 181:
YY_RULE_SETUP
{ return uint_constant(context); }
YY_BREAK
case 182:
YY_RULE_SETUP
{ return uint_constant(context); }
YY_BREAK
case 183:
YY_RULE_SETUP
{ return uint_constant(context); }
YY_BREAK
case 184:
YY_RULE_SETUP
{ return float_constant(yyscanner); }
YY_BREAK
case 185:
YY_RULE_SETUP
{ return float_constant(yyscanner); }
YY_BREAK
case 186:
YY_RULE_SETUP
{ return float_constant(yyscanner); }
YY_BREAK
case 187:
YY_RULE_SETUP
{ return floatsuffix_check(context); }
YY_BREAK
case 188:
YY_RULE_SETUP
{ return floatsuffix_check(context); }
YY_BREAK
case 189:
YY_RULE_SETUP
{ return floatsuffix_check(context); }
YY_BREAK
case 190:
YY_RULE_SETUP
{ return ADD_ASSIGN; }
YY_BREAK
case 191:
YY_RULE_SETUP
{ return SUB_ASSIGN; }
YY_BREAK
case 192:
YY_RULE_SETUP
{ return MUL_ASSIGN; }
YY_BREAK
case 193:
YY_RULE_SETUP
{ return DIV_ASSIGN; }
YY_BREAK
case 194:
YY_RULE_SETUP
{ return MOD_ASSIGN; }
YY_BREAK
case 195:
YY_RULE_SETUP
{ return LEFT_ASSIGN; }
YY_BREAK
case 196:
YY_RULE_SETUP
{ return RIGHT_ASSIGN; }
YY_BREAK
case 197:
YY_RULE_SETUP
{ return AND_ASSIGN; }
YY_BREAK
case 198:
YY_RULE_SETUP
{ return XOR_ASSIGN; }
YY_BREAK
case 199:
YY_RULE_SETUP
{ return OR_ASSIGN; }
YY_BREAK
case 200:
YY_RULE_SETUP
{ return INC_OP; }
YY_BREAK
case 201:
YY_RULE_SETUP
{ return DEC_OP; }
YY_BREAK
case 202:
YY_RULE_SETUP
{ return AND_OP; }
YY_BREAK
case 203:
YY_RULE_SETUP
{ return OR_OP; }
YY_BREAK
case 204:
YY_RULE_SETUP
{ return XOR_OP; }
YY_BREAK
case 205:
YY_RULE_SETUP
{ return LE_OP; }
YY_BREAK
case 206:
YY_RULE_SETUP
{ return GE_OP; }
YY_BREAK
case 207:
YY_RULE_SETUP
{ return EQ_OP; }
YY_BREAK
case 208:
YY_RULE_SETUP
{ return NE_OP; }
YY_BREAK
case 209:
YY_RULE_SETUP
{ return LEFT_OP; }
YY_BREAK
case 210:
YY_RULE_SETUP
{ return RIGHT_OP; }
YY_BREAK
case 211:
YY_RULE_SETUP
{ return SEMICOLON; }
YY_BREAK
case 212:
YY_RULE_SETUP
{ return LEFT_BRACE; }
YY_BREAK
case 213:
YY_RULE_SETUP
{ return RIGHT_BRACE; }
YY_BREAK
case 214:
YY_RULE_SETUP
{ return COMMA; }
YY_BREAK
case 215:
YY_RULE_SETUP
{ return COLON; }
YY_BREAK
case 216:
YY_RULE_SETUP
{ return EQUAL; }
YY_BREAK
case 217:
YY_RULE_SETUP
{ return LEFT_PAREN; }
YY_BREAK
case 218:
YY_RULE_SETUP
{ return RIGHT_PAREN; }
YY_BREAK
case 219:
YY_RULE_SETUP
{ return LEFT_BRACKET; }
YY_BREAK
case 220:
YY_RULE_SETUP
{ return RIGHT_BRACKET; }
YY_BREAK
case 221:
YY_RULE_SETUP
{ BEGIN(FIELDS); return DOT; }
YY_BREAK
case 222:
YY_RULE_SETUP
{ return BANG; }
YY_BREAK
case 223:
YY_RULE_SETUP
{ return DASH; }
YY_BREAK
case 224:
YY_RULE_SETUP
{ return TILDE; }
YY_BREAK
case 225:
YY_RULE_SETUP
{ return PLUS; }
YY_BREAK
case 226:
YY_RULE_SETUP
{ return STAR; }
YY_BREAK
case 227:
YY_RULE_SETUP
{ return SLASH; }
YY_BREAK
case 228:
YY_RULE_SETUP
{ return PERCENT; }
YY_BREAK
case 229:
YY_RULE_SETUP
{ return LEFT_ANGLE; }
YY_BREAK
case 230:
YY_RULE_SETUP
{ return RIGHT_ANGLE; }
YY_BREAK
case 231:
YY_RULE_SETUP
{ return VERTICAL_BAR; }
YY_BREAK
case 232:
YY_RULE_SETUP
{ return CARET; }
YY_BREAK
case 233:
YY_RULE_SETUP
{ return AMPERSAND; }
YY_BREAK
case 234:
YY_RULE_SETUP
{ return QUESTION; }
YY_BREAK
case 235:
YY_RULE_SETUP
{
BEGIN(INITIAL);
yylval->lex.string = NewPoolTString(yytext);
return FIELD_SELECTION;
}
YY_BREAK
case 236:
YY_RULE_SETUP
{}
YY_BREAK
case 237:
YY_RULE_SETUP
{
yyextra->error(*yylloc, "Illegal character at fieldname start", yytext, "");
yyextra->recover();
return 0;
}
YY_BREAK
case 238:
/* rule 238 can match eol */
YY_RULE_SETUP
{ }
YY_BREAK
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(FIELDS):
{ yyterminate(); }
YY_BREAK
case 239:
YY_RULE_SETUP
{ assert(false); return 0; }
YY_BREAK
case 240:
YY_RULE_SETUP
ECHO;
YY_BREAK
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = yyg->yy_hold_char;
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
* yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++yyg->yy_c_buf_p;
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = yyg->yy_last_accepting_cpos;
yy_current_state = yyg->yy_last_accepting_state;
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_END_OF_FILE:
{
yyg->yy_did_buffer_switch_on_eof = 0;
if ( yywrap(yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* yytext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p =
yyg->yytext_ptr + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
yyg->yy_c_buf_p =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
yy_current_state = yy_get_previous_state( yyscanner );
yy_cp = yyg->yy_c_buf_p;
yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = yyg->yytext_ptr;
register int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
else
{
yy_size_t num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset =
(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
yy_size_t new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
yyg->yy_n_chars, num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
if ( yyg->yy_n_chars == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
yyrestart(yyin ,yyscanner);
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
yyg->yy_n_chars += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
{
register yy_state_type yy_current_state;
register char *yy_cp;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_current_state = yyg->yy_start;
for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 820 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner)
{
register int yy_is_jam;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
register char *yy_cp = yyg->yy_c_buf_p;
register YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
yyg->yy_last_accepting_cpos = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 820 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 819);
(void)yyg;
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (yyscan_t yyscanner)
#else
static int input (yyscan_t yyscanner)
#endif
{
int c;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
*yyg->yy_c_buf_p = yyg->yy_hold_char;
if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
/* This was really a NUL. */
*yyg->yy_c_buf_p = '\0';
else
{ /* need more input */
yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
yyrestart(yyin ,yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( yywrap(yyscanner ) )
return EOF;
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput(yyscanner);
#else
return input(yyscanner);
#endif
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
break;
}
}
}
c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */
*yyg->yy_c_buf_p = '\0'; /* preserve yytext */
yyg->yy_hold_char = *++yyg->yy_c_buf_p;
if ( c == '\n' )
do{ yylineno++;
yycolumn=0;
}while(0)
;
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
}
yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
yy_load_buffer_state(yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
* yypop_buffer_state();
* yypush_buffer_state(new_buffer);
*/
yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
yy_load_buffer_state(yyscanner );
/* We don't actually know whether we did this switch during
* EOF (yywrap()) processing, but the only time this flag
* is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
yyg->yy_hold_char = *yyg->yy_c_buf_p;
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ,yyscanner );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
yy_init_buffer(b,file ,yyscanner);
return b;
}
/** Destroy the buffer.
* @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
yyfree((void *) b->yy_ch_buf ,yyscanner );
yyfree((void *) b ,yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a yyrestart() or at EOF.
*/
static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flush_buffer(b ,yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then yy_init_buffer was _probably_
* called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
yy_load_buffer_state(yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
yyensure_buffer_stack(yyscanner);
/* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*yyg->yy_c_buf_p = yyg->yy_hold_char;
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from yy_switch_to_buffer. */
yy_load_buffer_state(yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
yy_load_buffer_state(yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
yy_switch_to_buffer(b ,yyscanner );
return b;
}
/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* yy_scan_bytes() instead.
*/
YY_BUFFER_STATE yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
{
return yy_scan_bytes(yystr,strlen(yystr) ,yyscanner);
}
/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
yy_size_t i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) yyalloc(n ,yyscanner );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = yy_scan_buffer(buf,n ,yyscanner);
if ( ! b )
YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up yytext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
yytext[yyleng] = yyg->yy_hold_char; \
yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
yyg->yy_hold_char = *yyg->yy_c_buf_p; \
*yyg->yy_c_buf_p = '\0'; \
yyleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
}
/** Get the current line number.
* @param yyscanner The scanner object.
*/
int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
/** Get the current column number.
* @param yyscanner The scanner object.
*/
int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yycolumn;
}
/** Get the input stream.
* @param yyscanner The scanner object.
*/
FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
}
/** Get the output stream.
* @param yyscanner The scanner object.
*/
FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
}
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
yy_size_t yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
}
/** Get the current token.
* @param yyscanner The scanner object.
*/
char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
}
/** Set the user-defined data. This data is never touched by the scanner.
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
}
/** Set the current line number.
* @param line_number
* @param yyscanner The scanner object.
*/
void yyset_lineno (int line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
YY_FATAL_ERROR( "yyset_lineno called with no buffer" );
yylineno = line_number;
}
/** Set the current column.
* @param line_number
* @param yyscanner The scanner object.
*/
void yyset_column (int column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
YY_FATAL_ERROR( "yyset_column called with no buffer" );
yycolumn = column_no;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
* @param yyscanner The scanner object.
* @see yy_switch_to_buffer
*/
void yyset_in (FILE * in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = in_str ;
}
void yyset_out (FILE * out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = out_str ;
}
int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
void yyset_debug (int bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = bdebug ;
}
/* Accessor methods for yylval and yylloc */
YYSTYPE * yyget_lval (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yylval;
}
void yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yylval = yylval_param;
}
YYLTYPE *yyget_lloc (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yylloc;
}
void yyset_lloc (YYLTYPE * yylloc_param , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yylloc = yylloc_param;
}
/* User-visible API */
/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
return yy_init_globals ( *ptr_yy_globals );
}
/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
* The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
int yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
*ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
return 1;
}
/* By setting to 0xAA, we expose bugs in
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = 0;
yyg->yy_buffer_stack_top = 0;
yyg->yy_buffer_stack_max = 0;
yyg->yy_c_buf_p = (char *) 0;
yyg->yy_init = 0;
yyg->yy_start = 0;
yyg->yy_start_stack_ptr = 0;
yyg->yy_start_stack_depth = 0;
yyg->yy_start_stack = NULL;
/* Defined in main.c */
#ifdef YY_STDINIT
yyin = stdin;
yyout = stdout;
#else
yyin = (FILE *) 0;
yyout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* yylex_init()
*/
return 0;
}
/* yylex_destroy is for both reentrant and non-reentrant scanners. */
int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
yyfree(yyg->yy_buffer_stack ,yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
yyfree(yyg->yy_start_stack ,yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
return (void *) malloc( size );
}
void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void yyfree (void * ptr , yyscan_t yyscanner)
{
free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
yy_size_t string_input(char* buf, yy_size_t max_size, yyscan_t yyscanner) {
pp::Token token;
yyget_extra(yyscanner)->getPreprocessor().lex(&token);
yy_size_t len = token.type == pp::Token::LAST ? 0 : token.text.size();
if (len < max_size)
memcpy(buf, token.text.c_str(), len);
yyset_column(token.location.file,yyscanner);
yyset_lineno(token.location.line,yyscanner);
if (len >= max_size)
YY_FATAL_ERROR("Input buffer overflow");
else if (len > 0)
buf[len++] = ' ';
return len;
}
int check_type(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*) yyscanner;
int token = IDENTIFIER;
TSymbol* symbol = yyextra->symbolTable.find(yytext, yyextra->getShaderVersion());
if (symbol && symbol->isVariable()) {
TVariable* variable = static_cast<TVariable*>(symbol);
if (variable->isUserType()) {
token = TYPE_NAME;
}
}
yylval->lex.symbol = symbol;
return token;
}
int reserved_word(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*) yyscanner;
yyextra->error(*yylloc, "Illegal use of reserved word", yytext, "");
yyextra->recover();
return 0;
}
int ES2_reserved_ES3_keyword(TParseContext *context, int token)
{
yyscan_t yyscanner = (yyscan_t) context->getScanner();
if (context->getShaderVersion() < 300)
{
return reserved_word(yyscanner);
}
return token;
}
int ES2_keyword_ES3_reserved(TParseContext *context, int token)
{
yyscan_t yyscanner = (yyscan_t) context->getScanner();
if (context->getShaderVersion() >= 300)
{
return reserved_word(yyscanner);
}
return token;
}
int ES2_ident_ES3_keyword(TParseContext *context, int token)
{
struct yyguts_t* yyg = (struct yyguts_t*) context->getScanner();
yyscan_t yyscanner = (yyscan_t) context->getScanner();
// not a reserved word in GLSL ES 1.00, so could be used as an identifier/type name
if (context->getShaderVersion() < 300)
{
yylval->lex.string = NewPoolTString(yytext);
return check_type(yyscanner);
}
return token;
}
int uint_constant(TParseContext *context)
{
struct yyguts_t* yyg = (struct yyguts_t*) context->getScanner();
if (context->getShaderVersion() < 300)
{
context->error(*yylloc, "Unsigned integers are unsupported prior to GLSL ES 3.00", yytext, "");
context->recover();
return 0;
}
if (!atoi_clamp(yytext, &(yylval->lex.u)))
yyextra->error(*yylloc, "Integer overflow", yytext, "");
return UINTCONSTANT;
}
int floatsuffix_check(TParseContext* context)
{
struct yyguts_t* yyg = (struct yyguts_t*) context->getScanner();
if (context->getShaderVersion() < 300)
{
context->error(*yylloc, "Floating-point suffix unsupported prior to GLSL ES 3.00", yytext);
context->recover();
return 0;
}
std::string text = yytext;
text.resize(text.size() - 1);
if (!strtof_clamp(text, &(yylval->lex.f)))
yyextra->warning(*yylloc, "Float overflow", yytext, "");
return(FLOATCONSTANT);
}
void yyerror(YYLTYPE* lloc, TParseContext* context, void *scanner, const char* reason) {
context->error(*lloc, reason, yyget_text(scanner));
context->recover();
}
int int_constant(TParseContext *context) {
struct yyguts_t* yyg = (struct yyguts_t*) context->getScanner();
unsigned int u;
if (!atoi_clamp(yytext, &u))
{
if (context->getShaderVersion() >= 300)
yyextra->error(*yylloc, "Integer overflow", yytext, "");
else
yyextra->warning(*yylloc, "Integer overflow", yytext, "");
}
yylval->lex.i = static_cast<int>(u);
return INTCONSTANT;
}
int float_constant(yyscan_t yyscanner) {
struct yyguts_t* yyg = (struct yyguts_t*) yyscanner;
if (!strtof_clamp(yytext, &(yylval->lex.f)))
yyextra->warning(*yylloc, "Float overflow", yytext, "");
return FLOATCONSTANT;
}
int glslang_initialize(TParseContext* context) {
yyscan_t scanner = NULL;
if (yylex_init_extra(context,&scanner))
return 1;
context->setScanner(scanner);
return 0;
}
int glslang_finalize(TParseContext* context) {
yyscan_t scanner = context->getScanner();
if (scanner == NULL) return 0;
context->setScanner(NULL);
yylex_destroy(scanner);
return 0;
}
int glslang_scan(size_t count, const char* const string[], const int length[],
TParseContext* context) {
yyrestart(NULL,context->getScanner());
yyset_column(0,context->getScanner());
yyset_lineno(1,context->getScanner());
// Initialize preprocessor.
pp::Preprocessor *preprocessor = &context->getPreprocessor();
if (!preprocessor->init(count, string, length))
return 1;
// Define extension macros.
const TExtensionBehavior& extBehavior = context->extensionBehavior();
for (TExtensionBehavior::const_iterator iter = extBehavior.begin();
iter != extBehavior.end(); ++iter) {
preprocessor->predefineMacro(iter->first.c_str(), 1);
}
if (context->getFragmentPrecisionHigh())
preprocessor->predefineMacro("GL_FRAGMENT_PRECISION_HIGH", 1);
preprocessor->setMaxTokenSize(GetGlobalMaxTokenSize(context->getShaderSpec()));
return 0;
}
|
//===----------- Triple.cpp - Triple unit tests ---------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Triple.h"
#include "llvm/Support/VersionTuple.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
TEST(TripleTest, BasicParsing) {
Triple T;
T = Triple("");
EXPECT_EQ("", T.getArchName().str());
EXPECT_EQ("", T.getVendorName().str());
EXPECT_EQ("", T.getOSName().str());
EXPECT_EQ("", T.getEnvironmentName().str());
T = Triple("-");
EXPECT_EQ("", T.getArchName().str());
EXPECT_EQ("", T.getVendorName().str());
EXPECT_EQ("", T.getOSName().str());
EXPECT_EQ("", T.getEnvironmentName().str());
T = Triple("--");
EXPECT_EQ("", T.getArchName().str());
EXPECT_EQ("", T.getVendorName().str());
EXPECT_EQ("", T.getOSName().str());
EXPECT_EQ("", T.getEnvironmentName().str());
T = Triple("---");
EXPECT_EQ("", T.getArchName().str());
EXPECT_EQ("", T.getVendorName().str());
EXPECT_EQ("", T.getOSName().str());
EXPECT_EQ("", T.getEnvironmentName().str());
T = Triple("----");
EXPECT_EQ("", T.getArchName().str());
EXPECT_EQ("", T.getVendorName().str());
EXPECT_EQ("", T.getOSName().str());
EXPECT_EQ("-", T.getEnvironmentName().str());
T = Triple("a");
EXPECT_EQ("a", T.getArchName().str());
EXPECT_EQ("", T.getVendorName().str());
EXPECT_EQ("", T.getOSName().str());
EXPECT_EQ("", T.getEnvironmentName().str());
T = Triple("a-b");
EXPECT_EQ("a", T.getArchName().str());
EXPECT_EQ("b", T.getVendorName().str());
EXPECT_EQ("", T.getOSName().str());
EXPECT_EQ("", T.getEnvironmentName().str());
T = Triple("a-b-c");
EXPECT_EQ("a", T.getArchName().str());
EXPECT_EQ("b", T.getVendorName().str());
EXPECT_EQ("c", T.getOSName().str());
EXPECT_EQ("", T.getEnvironmentName().str());
T = Triple("a-b-c-d");
EXPECT_EQ("a", T.getArchName().str());
EXPECT_EQ("b", T.getVendorName().str());
EXPECT_EQ("c", T.getOSName().str());
EXPECT_EQ("d", T.getEnvironmentName().str());
}
TEST(TripleTest, ParsedIDs) {
Triple T;
T = Triple("i386-apple-darwin");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::Apple, T.getVendor());
EXPECT_EQ(Triple::Darwin, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("i386-pc-elfiamcu");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::ELFIAMCU, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("i386-pc-contiki-unknown");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Contiki, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("i386-pc-hurd-gnu");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Hurd, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
T = Triple("x86_64-pc-linux-gnu");
EXPECT_EQ(Triple::x86_64, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
T = Triple("x86_64-pc-linux-musl");
EXPECT_EQ(Triple::x86_64, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::Musl, T.getEnvironment());
T = Triple("powerpc-ibm-aix");
EXPECT_EQ(Triple::ppc, T.getArch());
EXPECT_EQ(Triple::IBM, T.getVendor());
EXPECT_EQ(Triple::AIX, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("powerpc64-ibm-aix");
EXPECT_EQ(Triple::ppc64, T.getArch());
EXPECT_EQ(Triple::IBM, T.getVendor());
EXPECT_EQ(Triple::AIX, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("powerpc-dunno-notsure");
EXPECT_EQ(Triple::ppc, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("powerpcspe-unknown-freebsd");
EXPECT_EQ(Triple::ppc, T.getArch());
EXPECT_EQ(Triple::PPCSubArch_spe, T.getSubArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::FreeBSD, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("s390x-ibm-zos");
EXPECT_EQ(Triple::systemz, T.getArch());
EXPECT_EQ(Triple::IBM, T.getVendor());
EXPECT_EQ(Triple::ZOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("systemz-ibm-zos");
EXPECT_EQ(Triple::systemz, T.getArch());
EXPECT_EQ(Triple::IBM, T.getVendor());
EXPECT_EQ(Triple::ZOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("arm-none-none-eabi");
EXPECT_EQ(Triple::arm, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::EABI, T.getEnvironment());
T = Triple("arm-none-linux-musleabi");
EXPECT_EQ(Triple::arm, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::MuslEABI, T.getEnvironment());
T = Triple("armv6hl-none-linux-gnueabi");
EXPECT_EQ(Triple::arm, T.getArch());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUEABI, T.getEnvironment());
T = Triple("armv7hl-none-linux-gnueabi");
EXPECT_EQ(Triple::arm, T.getArch());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUEABI, T.getEnvironment());
T = Triple("amdil-unknown-unknown");
EXPECT_EQ(Triple::amdil, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
T = Triple("amdil64-unknown-unknown");
EXPECT_EQ(Triple::amdil64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
T = Triple("hsail-unknown-unknown");
EXPECT_EQ(Triple::hsail, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
T = Triple("hsail64-unknown-unknown");
EXPECT_EQ(Triple::hsail64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
T = Triple("sparcel-unknown-unknown");
EXPECT_EQ(Triple::sparcel, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
T = Triple("spir-unknown-unknown");
EXPECT_EQ(Triple::spir, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
T = Triple("spir64-unknown-unknown");
EXPECT_EQ(Triple::spir64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
T = Triple("x86_64-unknown-ananas");
EXPECT_EQ(Triple::x86_64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Ananas, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("x86_64-unknown-cloudabi");
EXPECT_EQ(Triple::x86_64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::CloudABI, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("x86_64-unknown-fuchsia");
EXPECT_EQ(Triple::x86_64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Fuchsia, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("x86_64-unknown-hermit");
EXPECT_EQ(Triple::x86_64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::HermitCore, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("wasm32-unknown-unknown");
EXPECT_EQ(Triple::wasm32, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("wasm32-unknown-wasi");
EXPECT_EQ(Triple::wasm32, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::WASI, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("wasm64-unknown-unknown");
EXPECT_EQ(Triple::wasm64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("wasm64-unknown-wasi");
EXPECT_EQ(Triple::wasm64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::WASI, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("avr-unknown-unknown");
EXPECT_EQ(Triple::avr, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("avr");
EXPECT_EQ(Triple::avr, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("lanai-unknown-unknown");
EXPECT_EQ(Triple::lanai, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("lanai");
EXPECT_EQ(Triple::lanai, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("amdgcn-mesa-mesa3d");
EXPECT_EQ(Triple::amdgcn, T.getArch());
EXPECT_EQ(Triple::Mesa, T.getVendor());
EXPECT_EQ(Triple::Mesa3D, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("amdgcn-amd-amdhsa");
EXPECT_EQ(Triple::amdgcn, T.getArch());
EXPECT_EQ(Triple::AMD, T.getVendor());
EXPECT_EQ(Triple::AMDHSA, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("amdgcn-amd-amdpal");
EXPECT_EQ(Triple::amdgcn, T.getArch());
EXPECT_EQ(Triple::AMD, T.getVendor());
EXPECT_EQ(Triple::AMDPAL, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("ve-unknown-linux");
EXPECT_EQ(Triple::ve, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("csky-unknown-unknown");
EXPECT_EQ(Triple::csky, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("csky-unknown-linux");
EXPECT_EQ(Triple::csky, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("riscv32-unknown-unknown");
EXPECT_EQ(Triple::riscv32, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("riscv64-unknown-linux");
EXPECT_EQ(Triple::riscv64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("riscv64-unknown-freebsd");
EXPECT_EQ(Triple::riscv64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::FreeBSD, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("riscv64-suse-linux");
EXPECT_EQ(Triple::riscv64, T.getArch());
EXPECT_EQ(Triple::SUSE, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("armv7hl-suse-linux-gnueabi");
EXPECT_EQ(Triple::arm, T.getArch());
EXPECT_EQ(Triple::SUSE, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUEABI, T.getEnvironment());
T = Triple("i586-pc-haiku");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Haiku, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("x86_64-unknown-haiku");
EXPECT_EQ(Triple::x86_64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Haiku, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T = Triple("mips-mti-linux-gnu");
EXPECT_EQ(Triple::mips, T.getArch());
EXPECT_EQ(Triple::MipsTechnologies, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
T = Triple("mipsel-img-linux-gnu");
EXPECT_EQ(Triple::mipsel, T.getArch());
EXPECT_EQ(Triple::ImaginationTechnologies, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
T = Triple("mips64-mti-linux-gnu");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::MipsTechnologies, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
T = Triple("mips64el-img-linux-gnu");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::ImaginationTechnologies, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
T = Triple("mips64el-img-linux-gnuabin32");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::ImaginationTechnologies, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
T = Triple("mips64el-unknown-linux-gnuabi64");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mips64el");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mips64-unknown-linux-gnuabi64");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mips64");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mipsisa64r6el-unknown-linux-gnuabi64");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mips64r6el");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsisa64r6el");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsisa64r6-unknown-linux-gnuabi64");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mips64r6");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsisa64r6");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABI64, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mips64el-unknown-linux-gnuabin32");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mipsn32el");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mips64-unknown-linux-gnuabin32");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mipsn32");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mipsisa64r6el-unknown-linux-gnuabin32");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsn32r6el");
EXPECT_EQ(Triple::mips64el, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsisa64r6-unknown-linux-gnuabin32");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsn32r6");
EXPECT_EQ(Triple::mips64, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNUABIN32, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsel-unknown-linux-gnu");
EXPECT_EQ(Triple::mipsel, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mipsel");
EXPECT_EQ(Triple::mipsel, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mips-unknown-linux-gnu");
EXPECT_EQ(Triple::mips, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mips");
EXPECT_EQ(Triple::mips, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::NoSubArch, T.getSubArch());
T = Triple("mipsisa32r6el-unknown-linux-gnu");
EXPECT_EQ(Triple::mipsel, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsr6el");
EXPECT_EQ(Triple::mipsel, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsisa32r6el");
EXPECT_EQ(Triple::mipsel, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsisa32r6-unknown-linux-gnu");
EXPECT_EQ(Triple::mips, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsr6");
EXPECT_EQ(Triple::mips, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("mipsisa32r6");
EXPECT_EQ(Triple::mips, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::GNU, T.getEnvironment());
EXPECT_EQ(Triple::MipsSubArch_r6, T.getSubArch());
T = Triple("arm-oe-linux-gnueabi");
EXPECT_EQ(Triple::arm, T.getArch());
EXPECT_EQ(Triple::OpenEmbedded, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::GNUEABI, T.getEnvironment());
T = Triple("aarch64-oe-linux");
EXPECT_EQ(Triple::aarch64, T.getArch());
EXPECT_EQ(Triple::OpenEmbedded, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
EXPECT_TRUE(T.isArch64Bit());
T = Triple("arm64_32-apple-ios");
EXPECT_EQ(Triple::aarch64_32, T.getArch());
EXPECT_EQ(Triple::IOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
EXPECT_TRUE(T.isArch32Bit());
T = Triple("huh");
EXPECT_EQ(Triple::UnknownArch, T.getArch());
}
static std::string Join(StringRef A, StringRef B, StringRef C) {
std::string Str = std::string(A);
Str += '-';
Str += B;
Str += '-';
Str += C;
return Str;
}
static std::string Join(StringRef A, StringRef B, StringRef C, StringRef D) {
std::string Str = std::string(A);
Str += '-';
Str += B;
Str += '-';
Str += C;
Str += '-';
Str += D;
return Str;
}
TEST(TripleTest, Normalization) {
EXPECT_EQ("unknown", Triple::normalize(""));
EXPECT_EQ("unknown-unknown", Triple::normalize("-"));
EXPECT_EQ("unknown-unknown-unknown", Triple::normalize("--"));
EXPECT_EQ("unknown-unknown-unknown-unknown", Triple::normalize("---"));
EXPECT_EQ("unknown-unknown-unknown-unknown-unknown",
Triple::normalize("----"));
EXPECT_EQ("a", Triple::normalize("a"));
EXPECT_EQ("a-b", Triple::normalize("a-b"));
EXPECT_EQ("a-b-c", Triple::normalize("a-b-c"));
EXPECT_EQ("a-b-c-d", Triple::normalize("a-b-c-d"));
EXPECT_EQ("i386-b-c", Triple::normalize("i386-b-c"));
EXPECT_EQ("i386-a-c", Triple::normalize("a-i386-c"));
EXPECT_EQ("i386-a-b", Triple::normalize("a-b-i386"));
EXPECT_EQ("i386-a-b-c", Triple::normalize("a-b-c-i386"));
EXPECT_EQ("a-pc-c", Triple::normalize("a-pc-c"));
EXPECT_EQ("unknown-pc-b-c", Triple::normalize("pc-b-c"));
EXPECT_EQ("a-pc-b", Triple::normalize("a-b-pc"));
EXPECT_EQ("a-pc-b-c", Triple::normalize("a-b-c-pc"));
EXPECT_EQ("a-b-linux", Triple::normalize("a-b-linux"));
EXPECT_EQ("unknown-unknown-linux-b-c", Triple::normalize("linux-b-c"));
EXPECT_EQ("a-unknown-linux-c", Triple::normalize("a-linux-c"));
EXPECT_EQ("i386-pc-a", Triple::normalize("a-pc-i386"));
EXPECT_EQ("i386-pc-unknown", Triple::normalize("-pc-i386"));
EXPECT_EQ("unknown-pc-linux-c", Triple::normalize("linux-pc-c"));
EXPECT_EQ("unknown-pc-linux", Triple::normalize("linux-pc-"));
EXPECT_EQ("i386", Triple::normalize("i386"));
EXPECT_EQ("unknown-pc", Triple::normalize("pc"));
EXPECT_EQ("unknown-unknown-linux", Triple::normalize("linux"));
EXPECT_EQ("x86_64-unknown-linux-gnu", Triple::normalize("x86_64-gnu-linux"));
// Check that normalizing a permutated set of valid components returns a
// triple with the unpermuted components.
//
// We don't check every possible combination. For the set of architectures A,
// vendors V, operating systems O, and environments E, that would require |A|
// * |V| * |O| * |E| * 4! tests. Instead we check every option for any given
// slot and make sure it gets normalized to the correct position from every
// permutation. This should cover the core logic while being a tractable
// number of tests at (|A| + |V| + |O| + |E|) * 4!.
auto FirstArchType = Triple::ArchType(Triple::UnknownArch + 1);
auto FirstVendorType = Triple::VendorType(Triple::UnknownVendor + 1);
auto FirstOSType = Triple::OSType(Triple::UnknownOS + 1);
auto FirstEnvType = Triple::EnvironmentType(Triple::UnknownEnvironment + 1);
StringRef InitialC[] = {Triple::getArchTypeName(FirstArchType),
Triple::getVendorTypeName(FirstVendorType),
Triple::getOSTypeName(FirstOSType),
Triple::getEnvironmentTypeName(FirstEnvType)};
for (int Arch = FirstArchType; Arch <= Triple::LastArchType; ++Arch) {
StringRef C[] = {InitialC[0], InitialC[1], InitialC[2], InitialC[3]};
C[0] = Triple::getArchTypeName(Triple::ArchType(Arch));
std::string E = Join(C[0], C[1], C[2]);
int I[] = {0, 1, 2};
do {
EXPECT_EQ(E, Triple::normalize(Join(C[I[0]], C[I[1]], C[I[2]])));
} while (std::next_permutation(std::begin(I), std::end(I)));
std::string F = Join(C[0], C[1], C[2], C[3]);
int J[] = {0, 1, 2, 3};
do {
EXPECT_EQ(F, Triple::normalize(Join(C[J[0]], C[J[1]], C[J[2]], C[J[3]])));
} while (std::next_permutation(std::begin(J), std::end(J)));
}
for (int Vendor = FirstVendorType; Vendor <= Triple::LastVendorType;
++Vendor) {
StringRef C[] = {InitialC[0], InitialC[1], InitialC[2], InitialC[3]};
C[1] = Triple::getVendorTypeName(Triple::VendorType(Vendor));
std::string E = Join(C[0], C[1], C[2]);
int I[] = {0, 1, 2};
do {
EXPECT_EQ(E, Triple::normalize(Join(C[I[0]], C[I[1]], C[I[2]])));
} while (std::next_permutation(std::begin(I), std::end(I)));
std::string F = Join(C[0], C[1], C[2], C[3]);
int J[] = {0, 1, 2, 3};
do {
EXPECT_EQ(F, Triple::normalize(Join(C[J[0]], C[J[1]], C[J[2]], C[J[3]])));
} while (std::next_permutation(std::begin(J), std::end(J)));
}
for (int OS = FirstOSType; OS <= Triple::LastOSType; ++OS) {
if (OS == Triple::Win32)
continue;
StringRef C[] = {InitialC[0], InitialC[1], InitialC[2], InitialC[3]};
C[2] = Triple::getOSTypeName(Triple::OSType(OS));
std::string E = Join(C[0], C[1], C[2]);
int I[] = {0, 1, 2};
do {
EXPECT_EQ(E, Triple::normalize(Join(C[I[0]], C[I[1]], C[I[2]])));
} while (std::next_permutation(std::begin(I), std::end(I)));
std::string F = Join(C[0], C[1], C[2], C[3]);
int J[] = {0, 1, 2, 3};
do {
EXPECT_EQ(F, Triple::normalize(Join(C[J[0]], C[J[1]], C[J[2]], C[J[3]])));
} while (std::next_permutation(std::begin(J), std::end(J)));
}
for (int Env = FirstEnvType; Env <= Triple::LastEnvironmentType; ++Env) {
StringRef C[] = {InitialC[0], InitialC[1], InitialC[2], InitialC[3]};
C[3] = Triple::getEnvironmentTypeName(Triple::EnvironmentType(Env));
std::string F = Join(C[0], C[1], C[2], C[3]);
int J[] = {0, 1, 2, 3};
do {
EXPECT_EQ(F, Triple::normalize(Join(C[J[0]], C[J[1]], C[J[2]], C[J[3]])));
} while (std::next_permutation(std::begin(J), std::end(J)));
}
// Various real-world funky triples. The value returned by GCC's config.sub
// is given in the comment.
EXPECT_EQ("i386-unknown-windows-gnu",
Triple::normalize("i386-mingw32")); // i386-pc-mingw32
EXPECT_EQ("x86_64-unknown-linux-gnu",
Triple::normalize("x86_64-linux-gnu")); // x86_64-pc-linux-gnu
EXPECT_EQ("i486-unknown-linux-gnu",
Triple::normalize("i486-linux-gnu")); // i486-pc-linux-gnu
EXPECT_EQ("i386-redhat-linux",
Triple::normalize("i386-redhat-linux")); // i386-redhat-linux-gnu
EXPECT_EQ("i686-unknown-linux",
Triple::normalize("i686-linux")); // i686-pc-linux-gnu
EXPECT_EQ("arm-none-unknown-eabi",
Triple::normalize("arm-none-eabi")); // arm-none-eabi
EXPECT_EQ("ve-unknown-linux",
Triple::normalize("ve-linux")); // ve-linux
EXPECT_EQ("wasm32-unknown-wasi",
Triple::normalize("wasm32-wasi")); // wasm32-unknown-wasi
EXPECT_EQ("wasm64-unknown-wasi",
Triple::normalize("wasm64-wasi")); // wasm64-unknown-wasi
}
TEST(TripleTest, MutateName) {
Triple T;
EXPECT_EQ(Triple::UnknownArch, T.getArch());
EXPECT_EQ(Triple::UnknownVendor, T.getVendor());
EXPECT_EQ(Triple::UnknownOS, T.getOS());
EXPECT_EQ(Triple::UnknownEnvironment, T.getEnvironment());
T.setArchName("i386");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ("i386--", T.getTriple());
T.setVendorName("pc");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ("i386-pc-", T.getTriple());
T.setOSName("linux");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ("i386-pc-linux", T.getTriple());
T.setEnvironmentName("gnu");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Linux, T.getOS());
EXPECT_EQ("i386-pc-linux-gnu", T.getTriple());
T.setOSName("freebsd");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::FreeBSD, T.getOS());
EXPECT_EQ("i386-pc-freebsd-gnu", T.getTriple());
T.setOSAndEnvironmentName("darwin");
EXPECT_EQ(Triple::x86, T.getArch());
EXPECT_EQ(Triple::PC, T.getVendor());
EXPECT_EQ(Triple::Darwin, T.getOS());
EXPECT_EQ("i386-pc-darwin", T.getTriple());
}
TEST(TripleTest, BitWidthPredicates) {
Triple T;
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::arm);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::hexagon);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::mips);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::mips64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::msp430);
EXPECT_TRUE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::ppc);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::ppc64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::x86);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::x86_64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::amdil);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::amdil64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::hsail);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::hsail64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::spir);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::spir64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::sparc);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::sparcel);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::sparcv9);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::wasm32);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::wasm64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.setArch(Triple::avr);
EXPECT_TRUE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::lanai);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.setArch(Triple::riscv32);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
EXPECT_TRUE(T.isRISCV());
T.setArch(Triple::riscv64);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
EXPECT_TRUE(T.isRISCV());
T.setArch(Triple::csky);
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
EXPECT_TRUE(T.isCSKY());
}
TEST(TripleTest, BitWidthArchVariants) {
Triple T;
EXPECT_EQ(Triple::UnknownArch, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.get64BitArchVariant().getArch());
T.setArch(Triple::UnknownArch);
EXPECT_EQ(Triple::UnknownArch, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.get64BitArchVariant().getArch());
T.setArch(Triple::mips);
EXPECT_EQ(Triple::mips, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::mips64, T.get64BitArchVariant().getArch());
T.setArch(Triple::mipsel);
EXPECT_EQ(Triple::mipsel, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::mips64el, T.get64BitArchVariant().getArch());
T.setArch(Triple::ppc);
EXPECT_EQ(Triple::ppc, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::ppc64, T.get64BitArchVariant().getArch());
T.setArch(Triple::nvptx);
EXPECT_EQ(Triple::nvptx, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::nvptx64, T.get64BitArchVariant().getArch());
T.setArch(Triple::sparc);
EXPECT_EQ(Triple::sparc, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::sparcv9, T.get64BitArchVariant().getArch());
T.setArch(Triple::x86);
EXPECT_EQ(Triple::x86, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::x86_64, T.get64BitArchVariant().getArch());
T.setArch(Triple::mips64);
EXPECT_EQ(Triple::mips, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::mips64, T.get64BitArchVariant().getArch());
T.setArch(Triple::mips64el);
EXPECT_EQ(Triple::mipsel, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::mips64el, T.get64BitArchVariant().getArch());
T.setArch(Triple::ppc64);
EXPECT_EQ(Triple::ppc, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::ppc64, T.get64BitArchVariant().getArch());
T.setArch(Triple::nvptx64);
EXPECT_EQ(Triple::nvptx, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::nvptx64, T.get64BitArchVariant().getArch());
T.setArch(Triple::sparcv9);
EXPECT_EQ(Triple::sparc, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::sparcv9, T.get64BitArchVariant().getArch());
T.setArch(Triple::x86_64);
EXPECT_EQ(Triple::x86, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::x86_64, T.get64BitArchVariant().getArch());
T.setArch(Triple::amdil);
EXPECT_EQ(Triple::amdil, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::amdil64, T.get64BitArchVariant().getArch());
T.setArch(Triple::amdil64);
EXPECT_EQ(Triple::amdil, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::amdil64, T.get64BitArchVariant().getArch());
T.setArch(Triple::hsail);
EXPECT_EQ(Triple::hsail, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::hsail64, T.get64BitArchVariant().getArch());
T.setArch(Triple::hsail64);
EXPECT_EQ(Triple::hsail, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::hsail64, T.get64BitArchVariant().getArch());
T.setArch(Triple::spir);
EXPECT_EQ(Triple::spir, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::spir64, T.get64BitArchVariant().getArch());
T.setArch(Triple::spir64);
EXPECT_EQ(Triple::spir, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::spir64, T.get64BitArchVariant().getArch());
T.setArch(Triple::wasm32);
EXPECT_EQ(Triple::wasm32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::wasm64, T.get64BitArchVariant().getArch());
T.setArch(Triple::wasm64);
EXPECT_EQ(Triple::wasm32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::wasm64, T.get64BitArchVariant().getArch());
T.setArch(Triple::riscv32);
EXPECT_EQ(Triple::riscv32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::riscv64, T.get64BitArchVariant().getArch());
T.setArch(Triple::riscv64);
EXPECT_EQ(Triple::riscv32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::riscv64, T.get64BitArchVariant().getArch());
T.setArch(Triple::csky);
EXPECT_EQ(Triple::csky, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.get64BitArchVariant().getArch());
T.setArch(Triple::thumbeb);
EXPECT_EQ(Triple::thumbeb, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::aarch64_be, T.get64BitArchVariant().getArch());
T.setArch(Triple::thumb);
EXPECT_EQ(Triple::thumb, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::aarch64, T.get64BitArchVariant().getArch());
T.setArch(Triple::aarch64);
EXPECT_EQ(Triple::arm, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::aarch64, T.get64BitArchVariant().getArch());
T.setArch(Triple::aarch64_be);
EXPECT_EQ(Triple::armeb, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::aarch64_be, T.get64BitArchVariant().getArch());
T.setArch(Triple::renderscript32);
EXPECT_EQ(Triple::renderscript32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::renderscript64, T.get64BitArchVariant().getArch());
T.setArch(Triple::renderscript64);
EXPECT_EQ(Triple::renderscript32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::renderscript64, T.get64BitArchVariant().getArch());
T.setArch(Triple::le32);
EXPECT_EQ(Triple::le32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::le64, T.get64BitArchVariant().getArch());
T.setArch(Triple::le64);
EXPECT_EQ(Triple::le32, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::le64, T.get64BitArchVariant().getArch());
T.setArch(Triple::armeb);
EXPECT_EQ(Triple::armeb, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::aarch64_be, T.get64BitArchVariant().getArch());
T.setArch(Triple::arm);
EXPECT_EQ(Triple::arm, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::aarch64, T.get64BitArchVariant().getArch());
T.setArch(Triple::systemz);
EXPECT_EQ(Triple::UnknownArch, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::systemz, T.get64BitArchVariant().getArch());
T.setArch(Triple::xcore);
EXPECT_EQ(Triple::xcore, T.get32BitArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.get64BitArchVariant().getArch());
}
TEST(TripleTest, EndianArchVariants) {
Triple T;
EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::UnknownArch);
EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::aarch64_be);
EXPECT_EQ(Triple::aarch64_be, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::aarch64, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::aarch64);
EXPECT_EQ(Triple::aarch64_be, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::aarch64, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::armeb);
EXPECT_EQ(Triple::armeb, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::arm);
EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::arm, T.getLittleEndianArchVariant().getArch());
T = Triple("arm");
EXPECT_TRUE(T.isLittleEndian());
T = Triple("thumb");
EXPECT_TRUE(T.isLittleEndian());
T = Triple("armeb");
EXPECT_FALSE(T.isLittleEndian());
T = Triple("thumbeb");
EXPECT_FALSE(T.isLittleEndian());
T.setArch(Triple::bpfeb);
EXPECT_EQ(Triple::bpfeb, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::bpfel, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::bpfel);
EXPECT_EQ(Triple::bpfeb, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::bpfel, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::mips64);
EXPECT_EQ(Triple::mips64, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::mips64el, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::mips64el);
EXPECT_EQ(Triple::mips64, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::mips64el, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::mips);
EXPECT_EQ(Triple::mips, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::mipsel, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::mipsel);
EXPECT_EQ(Triple::mips, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::mipsel, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::ppc);
EXPECT_EQ(Triple::ppc, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::ppcle, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::ppc64);
EXPECT_EQ(Triple::ppc64, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::ppc64le, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::ppc64le);
EXPECT_EQ(Triple::ppc64, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::ppc64le, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::sparc);
EXPECT_EQ(Triple::sparc, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::sparcel, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::sparcel);
EXPECT_EQ(Triple::sparc, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::sparcel, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::thumb);
EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::thumb, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::thumbeb);
EXPECT_EQ(Triple::thumbeb, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::lanai);
EXPECT_EQ(Triple::lanai, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::UnknownArch, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::tcele);
EXPECT_EQ(Triple::tce, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::tcele, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::tce);
EXPECT_EQ(Triple::tce, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::tcele, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::le32);
EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::le32, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::le64);
EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::le64, T.getLittleEndianArchVariant().getArch());
T.setArch(Triple::csky);
EXPECT_EQ(Triple::UnknownArch, T.getBigEndianArchVariant().getArch());
EXPECT_EQ(Triple::csky, T.getLittleEndianArchVariant().getArch());
}
TEST(TripleTest, getOSVersion) {
Triple T;
unsigned Major, Minor, Micro;
T = Triple("i386-apple-darwin9");
EXPECT_TRUE(T.isMacOSX());
EXPECT_FALSE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)5, Minor);
EXPECT_EQ((unsigned)0, Micro);
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)5, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("x86_64-apple-darwin9");
EXPECT_TRUE(T.isMacOSX());
EXPECT_FALSE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)5, Minor);
EXPECT_EQ((unsigned)0, Micro);
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)5, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("x86_64-apple-macosx");
EXPECT_TRUE(T.isMacOSX());
EXPECT_FALSE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)4, Minor);
EXPECT_EQ((unsigned)0, Micro);
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)5, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("x86_64-apple-macosx10.7");
EXPECT_TRUE(T.isMacOSX());
EXPECT_FALSE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)7, Minor);
EXPECT_EQ((unsigned)0, Micro);
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)5, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("x86_64-apple-macos11.0");
EXPECT_TRUE(T.isMacOSX());
EXPECT_FALSE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)11, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("arm64-apple-macosx11.5.8");
EXPECT_TRUE(T.isMacOSX());
EXPECT_FALSE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_FALSE(T.isArch32Bit());
EXPECT_TRUE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)11, Major);
EXPECT_EQ((unsigned)5, Minor);
EXPECT_EQ((unsigned)8, Micro);
// 10.16 forms a valid triple, even though it's not
// a version of a macOS.
T = Triple("x86_64-apple-macos10.16");
EXPECT_TRUE(T.isMacOSX());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)16, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("x86_64-apple-darwin20");
EXPECT_TRUE(T.isMacOSX());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)11, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
// For darwin triples on macOS 11, only compare the major version.
T = Triple("x86_64-apple-darwin20.2");
EXPECT_TRUE(T.isMacOSX());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)11, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("armv7-apple-ios");
EXPECT_FALSE(T.isMacOSX());
EXPECT_TRUE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)4, Minor);
EXPECT_EQ((unsigned)0, Micro);
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)5, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
T = Triple("armv7-apple-ios7.0");
EXPECT_FALSE(T.isMacOSX());
EXPECT_TRUE(T.isiOS());
EXPECT_FALSE(T.isArch16Bit());
EXPECT_TRUE(T.isArch32Bit());
EXPECT_FALSE(T.isArch64Bit());
T.getMacOSXVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)4, Minor);
EXPECT_EQ((unsigned)0, Micro);
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)7, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
EXPECT_FALSE(T.isSimulatorEnvironment());
T = Triple("x86_64-apple-ios10.3-simulator");
EXPECT_TRUE(T.isiOS());
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)10, Major);
EXPECT_EQ((unsigned)3, Minor);
EXPECT_EQ((unsigned)0, Micro);
EXPECT_TRUE(T.isSimulatorEnvironment());
EXPECT_FALSE(T.isMacCatalystEnvironment());
T = Triple("x86_64-apple-ios13.0-macabi");
EXPECT_TRUE(T.isiOS());
T.getiOSVersion(Major, Minor, Micro);
EXPECT_EQ((unsigned)13, Major);
EXPECT_EQ((unsigned)0, Minor);
EXPECT_EQ((unsigned)0, Micro);
EXPECT_TRUE(T.getEnvironment() == Triple::MacABI);
EXPECT_TRUE(T.isMacCatalystEnvironment());
EXPECT_FALSE(T.isSimulatorEnvironment());
}
TEST(TripleTest, isMacOSVersionLT) {
Triple T = Triple("x86_64-apple-macos11");
EXPECT_TRUE(T.isMacOSXVersionLT(11, 1, 0));
EXPECT_FALSE(T.isMacOSXVersionLT(10, 15, 0));
T = Triple("x86_64-apple-darwin20");
EXPECT_TRUE(T.isMacOSXVersionLT(11, 1, 0));
EXPECT_FALSE(T.isMacOSXVersionLT(11, 0, 0));
EXPECT_FALSE(T.isMacOSXVersionLT(10, 15, 0));
}
TEST(TripleTest, CanonicalizeOSVersion) {
EXPECT_EQ(VersionTuple(10, 15, 4),
Triple::getCanonicalVersionForOS(Triple::MacOSX,
VersionTuple(10, 15, 4)));
EXPECT_EQ(VersionTuple(11, 0), Triple::getCanonicalVersionForOS(
Triple::MacOSX, VersionTuple(10, 16)));
EXPECT_EQ(VersionTuple(20),
Triple::getCanonicalVersionForOS(Triple::Darwin, VersionTuple(20)));
}
TEST(TripleTest, FileFormat) {
EXPECT_EQ(Triple::ELF, Triple("i686-unknown-linux-gnu").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("i686-unknown-freebsd").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("i686-unknown-netbsd").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("i686--win32-elf").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("i686---elf").getObjectFormat());
EXPECT_EQ(Triple::MachO, Triple("i686-apple-macosx").getObjectFormat());
EXPECT_EQ(Triple::MachO, Triple("i686-apple-ios").getObjectFormat());
EXPECT_EQ(Triple::MachO, Triple("i686---macho").getObjectFormat());
EXPECT_EQ(Triple::COFF, Triple("i686--win32").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("i686-pc-windows-msvc-elf").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("i686-pc-cygwin-elf").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("systemz-ibm-linux").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("systemz-ibm-unknown").getObjectFormat());
EXPECT_EQ(Triple::GOFF, Triple("s390x-ibm-zos").getObjectFormat());
EXPECT_EQ(Triple::GOFF, Triple("systemz-ibm-zos").getObjectFormat());
EXPECT_EQ(Triple::GOFF, Triple("s390x-ibm-zos-goff").getObjectFormat());
EXPECT_EQ(Triple::GOFF, Triple("s390x-unknown-zos-goff").getObjectFormat());
EXPECT_EQ(Triple::GOFF, Triple("s390x---goff").getObjectFormat());
EXPECT_EQ(Triple::Wasm, Triple("wasm32-unknown-unknown").getObjectFormat());
EXPECT_EQ(Triple::Wasm, Triple("wasm64-unknown-unknown").getObjectFormat());
EXPECT_EQ(Triple::Wasm, Triple("wasm32-wasi").getObjectFormat());
EXPECT_EQ(Triple::Wasm, Triple("wasm64-wasi").getObjectFormat());
EXPECT_EQ(Triple::Wasm, Triple("wasm32-unknown-wasi").getObjectFormat());
EXPECT_EQ(Triple::Wasm, Triple("wasm64-unknown-wasi").getObjectFormat());
EXPECT_EQ(Triple::Wasm,
Triple("wasm32-unknown-unknown-wasm").getObjectFormat());
EXPECT_EQ(Triple::Wasm,
Triple("wasm64-unknown-unknown-wasm").getObjectFormat());
EXPECT_EQ(Triple::Wasm,
Triple("wasm32-wasi-wasm").getObjectFormat());
EXPECT_EQ(Triple::Wasm,
Triple("wasm64-wasi-wasm").getObjectFormat());
EXPECT_EQ(Triple::Wasm,
Triple("wasm32-unknown-wasi-wasm").getObjectFormat());
EXPECT_EQ(Triple::Wasm,
Triple("wasm64-unknown-wasi-wasm").getObjectFormat());
EXPECT_EQ(Triple::XCOFF, Triple("powerpc-ibm-aix").getObjectFormat());
EXPECT_EQ(Triple::XCOFF, Triple("powerpc64-ibm-aix").getObjectFormat());
EXPECT_EQ(Triple::XCOFF, Triple("powerpc---xcoff").getObjectFormat());
EXPECT_EQ(Triple::XCOFF, Triple("powerpc64---xcoff").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("csky-unknown-unknown").getObjectFormat());
EXPECT_EQ(Triple::ELF, Triple("csky-unknown-linux").getObjectFormat());
Triple MSVCNormalized(Triple::normalize("i686-pc-windows-msvc-elf"));
EXPECT_EQ(Triple::ELF, MSVCNormalized.getObjectFormat());
Triple GNUWindowsNormalized(Triple::normalize("i686-pc-windows-gnu-elf"));
EXPECT_EQ(Triple::ELF, GNUWindowsNormalized.getObjectFormat());
Triple CygnusNormalised(Triple::normalize("i686-pc-windows-cygnus-elf"));
EXPECT_EQ(Triple::ELF, CygnusNormalised.getObjectFormat());
Triple CygwinNormalized(Triple::normalize("i686-pc-cygwin-elf"));
EXPECT_EQ(Triple::ELF, CygwinNormalized.getObjectFormat());
Triple T = Triple("");
T.setObjectFormat(Triple::ELF);
EXPECT_EQ(Triple::ELF, T.getObjectFormat());
T.setObjectFormat(Triple::MachO);
EXPECT_EQ(Triple::MachO, T.getObjectFormat());
T.setObjectFormat(Triple::XCOFF);
EXPECT_EQ(Triple::XCOFF, T.getObjectFormat());
T.setObjectFormat(Triple::GOFF);
EXPECT_EQ(Triple::GOFF, T.getObjectFormat());
}
TEST(TripleTest, NormalizeWindows) {
EXPECT_EQ("i686-pc-windows-msvc", Triple::normalize("i686-pc-win32"));
EXPECT_EQ("i686-unknown-windows-msvc", Triple::normalize("i686-win32"));
EXPECT_EQ("i686-pc-windows-gnu", Triple::normalize("i686-pc-mingw32"));
EXPECT_EQ("i686-unknown-windows-gnu", Triple::normalize("i686-mingw32"));
EXPECT_EQ("i686-pc-windows-gnu", Triple::normalize("i686-pc-mingw32-w64"));
EXPECT_EQ("i686-unknown-windows-gnu", Triple::normalize("i686-mingw32-w64"));
EXPECT_EQ("i686-pc-windows-cygnus", Triple::normalize("i686-pc-cygwin"));
EXPECT_EQ("i686-unknown-windows-cygnus", Triple::normalize("i686-cygwin"));
EXPECT_EQ("x86_64-pc-windows-msvc", Triple::normalize("x86_64-pc-win32"));
EXPECT_EQ("x86_64-unknown-windows-msvc", Triple::normalize("x86_64-win32"));
EXPECT_EQ("x86_64-pc-windows-gnu", Triple::normalize("x86_64-pc-mingw32"));
EXPECT_EQ("x86_64-unknown-windows-gnu", Triple::normalize("x86_64-mingw32"));
EXPECT_EQ("x86_64-pc-windows-gnu",
Triple::normalize("x86_64-pc-mingw32-w64"));
EXPECT_EQ("x86_64-unknown-windows-gnu",
Triple::normalize("x86_64-mingw32-w64"));
EXPECT_EQ("i686-pc-windows-elf", Triple::normalize("i686-pc-win32-elf"));
EXPECT_EQ("i686-unknown-windows-elf", Triple::normalize("i686-win32-elf"));
EXPECT_EQ("i686-pc-windows-macho", Triple::normalize("i686-pc-win32-macho"));
EXPECT_EQ("i686-unknown-windows-macho",
Triple::normalize("i686-win32-macho"));
EXPECT_EQ("x86_64-pc-windows-elf", Triple::normalize("x86_64-pc-win32-elf"));
EXPECT_EQ("x86_64-unknown-windows-elf",
Triple::normalize("x86_64-win32-elf"));
EXPECT_EQ("x86_64-pc-windows-macho",
Triple::normalize("x86_64-pc-win32-macho"));
EXPECT_EQ("x86_64-unknown-windows-macho",
Triple::normalize("x86_64-win32-macho"));
EXPECT_EQ("i686-pc-windows-cygnus",
Triple::normalize("i686-pc-windows-cygnus"));
EXPECT_EQ("i686-pc-windows-gnu", Triple::normalize("i686-pc-windows-gnu"));
EXPECT_EQ("i686-pc-windows-itanium",
Triple::normalize("i686-pc-windows-itanium"));
EXPECT_EQ("i686-pc-windows-msvc", Triple::normalize("i686-pc-windows-msvc"));
EXPECT_EQ("i686-pc-windows-elf",
Triple::normalize("i686-pc-windows-elf-elf"));
EXPECT_TRUE(Triple("x86_64-pc-win32").isWindowsMSVCEnvironment());
}
TEST(TripleTest, getARMCPUForArch) {
// Platform specific defaults.
{
llvm::Triple Triple("arm--nacl");
EXPECT_EQ("cortex-a8", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("arm--openbsd");
EXPECT_EQ("cortex-a8", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("armv6-unknown-freebsd");
EXPECT_EQ("arm1176jzf-s", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("thumbv6-unknown-freebsd");
EXPECT_EQ("arm1176jzf-s", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("armebv6-unknown-freebsd");
EXPECT_EQ("arm1176jzf-s", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("arm--win32");
EXPECT_EQ("cortex-a9", Triple.getARMCPUForArch());
}
// Some alternative architectures
{
llvm::Triple Triple("armv7k-apple-ios9");
EXPECT_EQ("cortex-a7", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("armv7k-apple-watchos3");
EXPECT_EQ("cortex-a7", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("armv7k-apple-tvos9");
EXPECT_EQ("cortex-a7", Triple.getARMCPUForArch());
}
// armeb is permitted, but armebeb is not
{
llvm::Triple Triple("armeb-none-eabi");
EXPECT_EQ("arm7tdmi", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("armebeb-none-eabi");
EXPECT_EQ("", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("armebv6eb-none-eabi");
EXPECT_EQ("", Triple.getARMCPUForArch());
}
// xscaleeb is permitted, but armebxscale is not
{
llvm::Triple Triple("xscaleeb-none-eabi");
EXPECT_EQ("xscale", Triple.getARMCPUForArch());
}
{
llvm::Triple Triple("armebxscale-none-eabi");
EXPECT_EQ("", Triple.getARMCPUForArch());
}
}
TEST(TripleTest, NormalizeARM) {
EXPECT_EQ("armv6-unknown-netbsd-eabi",
Triple::normalize("armv6-netbsd-eabi"));
EXPECT_EQ("armv7-unknown-netbsd-eabi",
Triple::normalize("armv7-netbsd-eabi"));
EXPECT_EQ("armv6eb-unknown-netbsd-eabi",
Triple::normalize("armv6eb-netbsd-eabi"));
EXPECT_EQ("armv7eb-unknown-netbsd-eabi",
Triple::normalize("armv7eb-netbsd-eabi"));
EXPECT_EQ("armv6-unknown-netbsd-eabihf",
Triple::normalize("armv6-netbsd-eabihf"));
EXPECT_EQ("armv7-unknown-netbsd-eabihf",
Triple::normalize("armv7-netbsd-eabihf"));
EXPECT_EQ("armv6eb-unknown-netbsd-eabihf",
Triple::normalize("armv6eb-netbsd-eabihf"));
EXPECT_EQ("armv7eb-unknown-netbsd-eabihf",
Triple::normalize("armv7eb-netbsd-eabihf"));
EXPECT_EQ("armv7-suse-linux-gnueabihf",
Triple::normalize("armv7-suse-linux-gnueabi"));
Triple T;
T = Triple("armv6--netbsd-eabi");
EXPECT_EQ(Triple::arm, T.getArch());
T = Triple("armv6eb--netbsd-eabi");
EXPECT_EQ(Triple::armeb, T.getArch());
T = Triple("armv7-suse-linux-gnueabihf");
EXPECT_EQ(Triple::GNUEABIHF, T.getEnvironment());
}
TEST(TripleTest, ParseARMArch) {
// ARM
{
Triple T = Triple("arm");
EXPECT_EQ(Triple::arm, T.getArch());
}
{
Triple T = Triple("armeb");
EXPECT_EQ(Triple::armeb, T.getArch());
}
// THUMB
{
Triple T = Triple("thumb");
EXPECT_EQ(Triple::thumb, T.getArch());
}
{
Triple T = Triple("thumbeb");
EXPECT_EQ(Triple::thumbeb, T.getArch());
}
// AARCH64
{
Triple T = Triple("arm64");
EXPECT_EQ(Triple::aarch64, T.getArch());
}
{
Triple T = Triple("arm64_32");
EXPECT_EQ(Triple::aarch64_32, T.getArch());
}
{
Triple T = Triple("aarch64");
EXPECT_EQ(Triple::aarch64, T.getArch());
}
{
Triple T = Triple("aarch64_be");
EXPECT_EQ(Triple::aarch64_be, T.getArch());
}
{
Triple T = Triple("arm64e");
EXPECT_EQ(Triple::aarch64, T.getArch());
EXPECT_EQ(Triple::AArch64SubArch_arm64e, T.getSubArch());
}
}
} // end anonymous namespace
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "ApiDetector.hpp"
#include <VersionHelpers.h>
#pragma hdrstop
using namespace Microsoft::Console::Interactivity;
// API Sets
#define EXT_API_SET_NTUSER_WINDOW L"ext-ms-win-ntuser-window-l1-1-0"
// This may not be defined depending on the SDK version being targetted.
#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER
#define LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER 0x00004000
#endif
#pragma region Public Methods
// Routine Description
// - This routine detects whether the system hosts the extension API set that
// includes, among others, CreateWindowExW.
// Arguments:
// - level - pointer to an APILevel enum stating the level of support the
// system offers for the given functionality.
[[nodiscard]]
NTSTATUS ApiDetector::DetectNtUserWindow(_Out_ ApiLevel* level)
{
// N.B.: Testing for the API set implies the function is present.
return DetectApiSupport(EXT_API_SET_NTUSER_WINDOW, nullptr, level);
}
#pragma endregion
#pragma region Private Methods
[[nodiscard]]
NTSTATUS ApiDetector::DetectApiSupport(_In_ LPCWSTR lpApiHost, _In_ LPCSTR lpProcedure, _Out_ ApiLevel* level)
{
if (!level)
{
return STATUS_INVALID_PARAMETER;
}
NTSTATUS status = STATUS_SUCCESS;
HMODULE hModule = nullptr;
status = TryLoadWellKnownLibrary(lpApiHost, &hModule);
if (NT_SUCCESS(status) && lpProcedure)
{
status = TryLocateProcedure(hModule, lpProcedure);
}
SetLevelAndFreeIfNecessary(status, hModule, level);
return STATUS_SUCCESS;
}
[[nodiscard]]
NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, _Outptr_result_nullonfailure_ HMODULE *phModule)
{
NTSTATUS status = STATUS_SUCCESS;
// N.B.: Suppose we attempt to load user32.dll and locate CreateWindowExW
// on a Nano Server system with reverse forwarders enabled. Since the
// reverse forwarder modules have the same name as their regular
// counterparts, the loader will claim to have found the module. In
// addition, since reverse forwarders contain all the functions of
// their regular counterparts, just stubbed to return or set the last
// error to STATUS_NOT_IMPLEMENTED, GetProcAddress will indeed
// indicate that the procedure exists. Hence, we need to search for
// modules skipping over the reverse forwarders.
//
// This however has the side-effect of not working on downlevel.
// LoadLibraryEx asserts that the flags passed in are valid. If any
// invalid flags are passed, it sets the last error to
// ERROR_INVALID_PARAMETER and returns. Since
// LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER does not exist on
// downlevel Windows, the call will fail there.
//
// To counteract that, we try to load the library skipping forwarders
// first under the assumption that we are running on a sufficiently
// new system. If the call fails with ERROR_INVALID_PARAMETER, we
// know there is a problem with the flags, so we try again without
// the NO_FORWARDER part. Because reverse forwarders do not exist on
// downlevel (i.e. < Windows 10), we do not run the risk of failing
// to accurately detect system functionality there.
//
// N.B.: We cannot use IsWindowsVersionOrGreater or associated helper API's
// because those are subject to manifesting and may tell us we are
// running on Windows 8 even if we are running on Windows 10.
//
// TODO: MSFT 10916452 Determine what manifest magic is required to make
// versioning API's behave sanely.
status = TryLoadWellKnownLibrary(lpLibrary, LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER, phModule);
if (!NT_SUCCESS(status) && GetLastError() == ERROR_INVALID_PARAMETER)
{
status = TryLoadWellKnownLibrary(lpLibrary, LOAD_LIBRARY_SEARCH_SYSTEM32, phModule);
}
return status;
}
[[nodiscard]]
NTSTATUS ApiDetector::TryLoadWellKnownLibrary(_In_ LPCWSTR lpLibrary, _In_ DWORD dwLoaderFlags, _Outptr_result_nullonfailure_ HMODULE *phModule)
{
HMODULE hModule = nullptr;
hModule = LoadLibraryExW(lpLibrary,
nullptr,
dwLoaderFlags);
if (hModule)
{
*phModule = hModule;
return STATUS_SUCCESS;
}
else
{
return STATUS_UNSUCCESSFUL;
}
}
[[nodiscard]]
NTSTATUS ApiDetector::TryLocateProcedure(_In_ HMODULE hModule, _In_ LPCSTR lpProcedure)
{
FARPROC proc = GetProcAddress(hModule, lpProcedure);
if (proc)
{
return STATUS_SUCCESS;
}
else
{
return STATUS_UNSUCCESSFUL;
}
}
void ApiDetector::SetLevelAndFreeIfNecessary(_In_ NTSTATUS status, _In_ HMODULE hModule, _Out_ ApiLevel* level)
{
if (NT_SUCCESS(status))
{
*level = ApiLevel::Win32;
}
else
{
FreeLibrary(hModule);
*level = ApiLevel::OneCore;
}
}
#pragma endregion
|
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_TYPE_TRAITS_FLOAT_PROMOTE_HPP
#define SPROUT_TYPE_TRAITS_FLOAT_PROMOTE_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/type_traits/identity.hpp>
namespace sprout {
namespace detail {
template<typename T>
struct float_promote1
: public std::conditional<
std::is_floating_point<T>::value,
T,
double
>
{
static_assert(
std::is_arithmetic<T>::value,
"float_promote requires arithmetic type."
);
};
template<typename T, typename U>
struct float_promote2
: public std::conditional<
(std::is_same<T, long double>::value || std::is_same<U, long double>::value),
long double,
typename std::conditional<
(std::is_same<T, float>::value && std::is_same<U, float>::value),
float,
double
>::type
>
{
static_assert(
std::is_arithmetic<T>::value && std::is_arithmetic<U>::value,
"float_promote requires arithmetic type."
);
};
template<typename... Types>
struct float_promote_impl;
template<typename T, typename U, typename... Tail>
struct float_promote_impl<T, U, Tail...>
: public sprout::detail::float_promote_impl<
typename sprout::detail::float_promote2<T, U>::type,
Tail...
>
{};
template<typename T>
struct float_promote_impl<T>
: public sprout::detail::float_promote1<T>
{};
} // namespace detail
//
// float_promote
//
template<typename... Types>
struct float_promote
: public sprout::detail::float_promote_impl<
typename std::remove_cv<Types>::type...
>
{};
#if SPROUT_USE_TEMPLATE_ALIASES
template<typename... Types>
using float_promote_t = typename sprout::float_promote<Types...>::type;
#endif // #if SPROUT_USE_TEMPLATE_ALIASES
} // namespace sprout
#endif // #ifndef SPROUT_TYPE_TRAITS_FLOAT_PROMOTE_HPP
|
/**
@file
@author Alexander Sherikov
@copyright 2017-2018 Alexander Sherikov, Licensed under the Apache License, Version 2.0.
(see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
@brief
*/
#define ARILES_API_VERSION 2
#include "utility.h"
#include "ariles/adapters_all.h"
#include "ariles/ariles2.h"
// ===============================================================
// TYPES
// ===============================================================
#include "types/inheritance.h"
// ===============================================================
// FIXTURES
// ===============================================================
#include "fixtures/006_dummy.h"
// ===============================================================
// TESTS
// ===============================================================
BOOST_FIXTURE_TEST_CASE(CompareInheritance, ariles_tests::DummyFixture)
{
ariles_tests::ConfigurableDerived configurable1, configurable2;
ariles::Compare visitor;
ariles::Compare::Parameters param;
param.double_tolerance_ = g_tolerance;
param.compare_number_of_entries_ = true;
param.throw_on_error_ = false;
configurable1.randomize();
configurable2 = configurable1;
BOOST_CHECK(visitor.compare(configurable1, configurable2, param));
configurable1.randomize();
BOOST_CHECK(false == visitor.compare(configurable1, configurable2, param));
}
|
//
// Created by Justin Provazza on 12/8/18.
//
#include <iostream>
#include <complex>
#include <cmath>
#include "MQDS/twa.h"
#include "MQDS/system.h"
#include "MQDS/bath.h"
#include "MQDS/calculation.h"
#include "MQDS/io.h"
#include "MQDS/universe.h"
#include "MQDS/units.h"
#include "MQDS/constants.h"
void MQDS::TWA::initialize_method(std::unique_ptr<System> & system,
std::unique_ptr<Bath> & bath,
MQDS::IO & io)
{
const int bath_copies = 1;
const int system_copies = 1;
bath->initialize_phase_space(bath_copies,io.nbath(),io.nosc());
system->initialize_mapping_variables(system_copies,io.nstate());
return;
}
std::vector<Eigen::MatrixXcd>
MQDS::TWA::calculate_reduced_density_matrix(std::unique_ptr<MQDS::System> & system,
std::unique_ptr<MQDS::Bath> & bath,
MQDS::IO & io,
MQDS::Universe & pe)
{
// ALLOCATE REDUCED DENSITY MATRIX TO CALCULATE WITH PLDM
allocate_redmat(io);
// CALCULATE BETA = (1/K_B*T), AND DT FOR A TIME-STEP
const double beta = 1.0 / (io.temperature() * Units::conversion(Units::kelvin,Units::atomic_energy));
const double dt = io.runtime() * Units::conversion(Units::femtoseconds,Units::atomic_time)/io.nstep();
std::complex<double> traj_per_proc(io.ntraj()/pe.num_procs(),0.0);
// LOOP OVER ENSEMBLE OF TRAJECTORIES
for (int itraj=0; itraj<io.ntraj()/pe.num_procs(); ++itraj)
{
// GATHER ALL INITIAL CONDITIONS FOR THE TRAJECTORY
system->gaussian_mapping_initial_conditions(0.0,std::sqrt(0.5));
system->assign_initial_trajectory_weight
(initial_trajectory_weight(system,io.initstate(),io.initstatet()));
// ASSUMES BOLTZMANN INITIAL CONDITIONS
bath->bare_boltzmann_wigner_initial_conditions(beta);
// INITIALIZE TIME DIMENSION COUNTER
int itime=0;
redmat_[itime] = redmat_[itime] + redmat_function(system);
for (int istep=1; istep<io.nstep()+1; ++istep)
{
// ADVANCE ALL DOF BY A TIME-STEP
propagate(system,bath,dt,io.nlit());
// IF INTEGER MULTIPLE OF IO.DUMP(), CALCULATE REDUCED DENSITY MATRIX
if (istep % io.dump() == 0)
{
itime+=1;
redmat_[itime] = redmat_[itime] + redmat_function(system);
}
}
}
// AVERAGE RESULT OVER NUMBER OF TRAJECTORIES ON THIS PROCESSOR
for (int itime=0; itime<redmat_.size(); ++itime)
{
for (int istate=0; istate<io.nstate(); ++istate)
{
for (int jstate=0; jstate<io.nstate(); ++jstate)
{
redmat_[itime](istate,jstate)=redmat_[itime](istate,jstate)
/(traj_per_proc);
}
}
}
return redmat_;
}
// PROPAGATION USING THE TWA EQUATIONS OF MOTION
void MQDS::TWA::propagate(std::unique_ptr<System> & system,
std::unique_ptr<Bath> & bath,
const double & dt,
const int & nlit)
{
//position half-step
bath->advance_position(0.5*dt);
//mapping full-step, forward mapping and backward mapping
system->advance_mapping_variables(0,what_system_feels(0,system,bath),dt,nlit);
//momentum full-step
bath->advance_momentum(what_bath_feels(system,bath),dt);
//position half-step
bath->advance_position(0.5*dt);
return;
}
// WHAT THE BATH DYNAMICS IS GOVERENED BY IN PLDM
std::vector<Eigen::MatrixXd> MQDS::TWA::what_bath_feels(std::unique_ptr<System> & system,
std::unique_ptr<Bath> & bath)
{
const int bath_copies=1;
std::vector<Eigen::MatrixXd> pldm_what_bath_feels;
pldm_what_bath_feels.resize(bath_copies);
pldm_what_bath_feels[0].resize(system->position_map()[0].size(), system->position_map()[0].size());
// vector is of length bath_copies, matrix is nstate x nstate
for (int istate=0; istate<system->position_map()[0].size(); ++istate)
{
for (int jstate = 0; jstate < system->position_map()[0].size(); ++jstate)
{
if (istate==jstate) {
pldm_what_bath_feels[0](istate, jstate) = 0.5 * (system->position_map()[0](istate)
* system->position_map()[0](jstate)
+ system->momentum_map()[0](istate)
* system->momentum_map()[0](jstate) - 1);
}
else
{
pldm_what_bath_feels[0](istate,jstate) = 0.5 * (system->position_map()[0](istate)
* system->position_map()[0](jstate)
+ system->momentum_map()[0](istate)
* system->momentum_map()[0](jstate));
}
}
}
return pldm_what_bath_feels;
}
// WHAT THE SYSTEM (MAPPING VARIABLE) DYNAMICS IS CONTROLLED BY IN PLDM
Eigen::MatrixXd MQDS::TWA::what_system_feels(const int &icopy,
std::unique_ptr<System> & system,
std::unique_ptr<Bath> & bath)
{
// ONLY ONE COPY OF BATH FOR PLDM
Eigen::MatrixXd pldm_what_system_feels;
pldm_what_system_feels.resize(system->position_map()[0].size(), system->position_map()[0].size());
for (int istate = 0; istate < system->position_map()[0].size(); ++istate) {
for (int jstate = 0; jstate < system->position_map()[0].size(); ++jstate) {
pldm_what_system_feels(istate, jstate) = system->hamiltonian()(istate, jstate)
+ bath->sb_portion_of_hamiltonian(icopy, istate, jstate);
}
}
return pldm_what_system_feels;
}
// CALCULATE THE REDUCED DENSITY MATRIX WITH TWA
Eigen::MatrixXcd
MQDS::TWA::redmat_function(std::unique_ptr<System> & system)
{
Eigen::MatrixXcd temp(system->position_map()[0].size(), system->position_map()[0].size());
double gauss_factor=1.0;
for (int istate = 0; istate < system->position_map()[0].size(); ++istate)
{
gauss_factor *= std::exp(- std::pow(system->position_map()[0](istate),2)
- std::pow(system->momentum_map()[0](istate),2));
}
for (int istate = 0; istate < system->position_map()[0].size(); ++istate) {
for (int jstate = 0; jstate < system->position_map()[0].size(); ++jstate) {
if (istate == jstate)
{
temp(istate, jstate) = system->initial_trajectory_weight() * gauss_factor
* (std::pow(system->position_map()[0](istate),2)
+ std::pow(system->momentum_map()[0](istate),2)-0.5);
}
else
{
temp(istate, jstate) = system->initial_trajectory_weight() * gauss_factor
* (system->position_map()[0](istate)
+ MQDS::Constants::eye * system->momentum_map()[0](istate))
* (system->position_map()[0](jstate)
- MQDS::Constants::eye * system->momentum_map()[0](jstate));
}
}
}
return temp;
}
// GET THE INITIAL TRAJECTORY WEIGHT
std::complex<double> MQDS::TWA::initial_trajectory_weight(std::unique_ptr<System> & system,
const int &initstate,
const int &initstatet)
{
if (initstate==initstatet)
{
return std::pow(2.0,2*system->position_map()[0].size())
* (std::pow(system->position_map()[0](initstate),2)
+ std::pow(system->momentum_map()[0](initstate),2) - 0.5);
}
else
{
return std::pow(2.0,2*system->position_map()[0].size())
* (system->position_map()[0](initstate) - Constants::eye * system->momentum_map()[0](initstate))
* (system->position_map()[0](initstatet) + Constants::eye * system->momentum_map()[0](initstatet));
}
}
|
#include "EvadeSneak.h"
#include "../../character/Character.h"
#include "WanderSneak.h"
#include "StandSneak.h"
void EvadeSneak::enter(Character* stateMachine) {
if (globals::debug) std::cout << *stateMachine << "enter evade sneak" << std::endl;
stateMachine->setTarget(m_target);
stateMachine->turnOnBehavior(SteeringBehaviors::fEvade);
}
void EvadeSneak::exit(Character* stateMachine) {
if (globals::debug) std::cout << *stateMachine << "exit evade sneak" << std::endl;
stateMachine->setTarget(nullptr);
stateMachine->turnOffBehavior(SteeringBehaviors::fEvade);
State::exit(stateMachine);
}
void EvadeSneak::execute(Character* stateMachine) {
static int escaped = 0;
if (!m_target->canDetect(stateMachine)) {
escaped++;
if (escaped > 1000) {
escaped = 0;
stateMachine->changeState(new WanderSneak());
}
} else {
escaped = 0;
}
State::execute(stateMachine);
}
|
#include "AST/read.hpp"
// TODO
ReadNode::ReadNode(const uint32_t line, const uint32_t col)
: AstNode{line, col} {}
// TODO: You may use code snippets in AstDumper.cpp
void ReadNode::print() {}
// void ReadNode::visitChildNodes(AstNodeVisitor &p_visitor) {
// // TODO
// }
|
/*
MIT License
Copyright (c) 2017 FMI Open Development / Markus Peura, first.last@fmi.fi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
Part of Rack development has been done in the BALTRAD projects part-financed
by the European Union (European Regional Development Fund and European
Neighbourhood Partnership Instrument, Baltic Sea Region Programme 2007-2013)
*/
#include "drain/util/Rectangle.h"
#include "AccumulatorGeo.h"
namespace drain
{
namespace image
{
std::ostream &operator<<(std::ostream &ostr, const drain::image::AccumulatorGeo & acc){
ostr << "AccumulatorGeo/ ";
ostr << (const GeoFrame &)acc;
ostr << (const drain::image::AccumulationArray &)acc << '\n';
ostr << " allocated (" << acc.getWidth() << 'x' << acc.getHeight() << ") \n";
return ostr;
}
/*
std::ostream &operator<<(std::ostream &ostr, const drain::image::AccumulatorGeo & acc){
ostr << "AccumulatorGeo (frame " << acc.getFrameWidth() << 'x' << acc.getFrameHeight() << ") \n";
ostr << (const drain::image::AccumulationArray &)acc << '\n';
ostr << " allocated (" << acc.getWidth() << 'x' << acc.getHeight() << ") \n";
//ostr << " resolution, metres: " << acc.getScaleX() << 'x' << acc.getScaleY() << "\n";
ostr << " coord system: " << acc.getCoordinateSystem() << '\n';
ostr << " proj: " << acc.getProjection() << '\n';
ostr << " scope, metres: [" << acc.getBoundingBoxM() << "]\n";
ostr << " scope, radians: [" << acc.getBoundingBoxR() << "]\n";
ostr << " scope, degrees: [" << acc.getBoundingBoxD() << "]\n";
return ostr;
}
*/
} // namespace image
} // namespace drain
// Drain
|
//
// GeometryReverseSequence.cpp
// MNN
//
// Created by MNN on 2020/05/29.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "geometry/GeometryComputer.hpp"
namespace MNN {
class GeometryReverseSequence : public GeometryComputer {
public:
virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs,
Context& context, CommandBuffer& res) const override {
MNN_ASSERT(1 == outputs.size());
MNN_ASSERT(2 == inputs.size());
auto output = outputs[0];
auto input = inputs[0];
auto reverse = inputs[1];
// below will using stride, set it first
TensorUtils::setLinearLayout(output);
TensorUtils::setLinearLayout(input);
TensorUtils::setLinearLayout(reverse);
if (nullptr == op->main_as_ReverseSequenceParam()) {
MNN_ERROR("Dont's has Parameters for OpType_ReverseSequence\n");
return false;
}
auto seqDim = op->main_as_ReverseSequenceParam()->seqDim();
if (seqDim < 0) {
seqDim += inputs[0]->dimensions();
}
auto batchDim = op->main_as_ReverseSequenceParam()->batchDim();
if (batchDim < 0) {
batchDim += inputs[0]->dimensions();
}
if (seqDim == batchDim) {
MNN_ERROR("seq and batch dim can't be the same\n");
return false;
}
if (inputs[0]->getType().bits != 32) {
MNN_ERROR("Don't support %d bit's ReverseSequence\n", inputs[0]->getType().bits);
return false;
}
if (inputs[1]->length(0) != inputs[0]->length(batchDim)) {
MNN_ERROR("ReverseSequence info error\n");
return false;
}
int mid0 = seqDim;
int mid1 = batchDim;
if (mid0 > mid1) {
auto temp = mid1;
mid1 = mid0;
mid0 = temp;
}
int mInsideStride = inputs[0]->stride(mid1);
int mOutsideSize = 1;
int mOutSideStride = 1;
for (int i = 0; i < mid0; ++i) {
mOutsideSize *= inputs[0]->length(i);
}
if (mid0 > 0) {
mOutSideStride = inputs[0]->stride(mid0 - 1);
}
int mMidSize = 1;
int mMidStride = 1;
for (int i = mid0 + 1; i < mid1; ++i) {
mMidSize *= inputs[0]->length(i);
}
if (mid1 > 0) {
mMidStride = inputs[0]->stride(mid1 - 1);
}
auto outputDes = TensorUtils::getDescribe(output);
outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL;
auto batchSize = input->length(batchDim);
outputDes->regions.clear();
for (int batch = 0; batch < batchSize; ++batch) {
auto q = reverse->host<int32_t>()[batch];
if (q > input->length(seqDim) || q < 1) {
MNN_ERROR("ReverseSequence info error\n");
return false;
}
for (int o = 0; o < mOutsideSize; ++o) {
Tensor::InsideDescribe::Region dstSlice;
dstSlice.origin = input;
dstSlice.size[0] = q;
dstSlice.size[1] = mMidSize;
dstSlice.size[2] = mInsideStride;
dstSlice.src.stride[0] = -(input->stride(seqDim));
dstSlice.src.stride[1] = mMidStride;
dstSlice.src.stride[2] = 1;
dstSlice.src.offset =
(q - 1) * input->stride(seqDim) + batch * input->stride(batchDim) + o * mOutSideStride;
dstSlice.dst.offset = batch * output->stride(batchDim) + o * mOutSideStride;
dstSlice.dst.stride[0] = output->stride(seqDim);
dstSlice.dst.stride[1] = mMidStride;
dstSlice.dst.stride[2] = 1;
outputDes->regions.emplace_back(std::move(dstSlice));
}
if(q < input->length(seqDim)) {
const int leftSeq = input->length(seqDim) - q;
for (int o = 0; o < mOutsideSize; ++o) {
Tensor::InsideDescribe::Region dstSlice;
dstSlice.origin = input;
dstSlice.size[0] = leftSeq;
dstSlice.size[1] = mMidSize;
dstSlice.size[2] = mInsideStride;
dstSlice.src.stride[0] = input->stride(seqDim);
dstSlice.src.stride[1] = mMidStride;
dstSlice.src.stride[2] = 1;
dstSlice.src.offset =
q * input->stride(seqDim) + batch * input->stride(batchDim) + o * mOutSideStride;
dstSlice.dst.offset = q * output->stride(seqDim) + batch * output->stride(batchDim) + o * mOutSideStride;
dstSlice.dst.stride[0] = output->stride(seqDim);
dstSlice.dst.stride[1] = mMidStride;
dstSlice.dst.stride[2] = 1;
outputDes->regions.emplace_back(std::move(dstSlice));
}
}
}
return true;
}
};
static void _create() {
std::shared_ptr<GeometryComputer> comp(new GeometryReverseSequence);
GeometryComputer::registerGeometryComputer(comp, {OpType_ReverseSequence});
}
REGISTER_GEOMETRY(GeometryReverseSequence, _create);
} // namespace MNN
|
//==============================================================================
//
// Copyright (c) 2018-2019 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#include <iostream>
#include <algorithm>
#include <sstream>
#include <unordered_map>
#include "SaveOutputTensor.hpp"
#include "Util.hpp"
#include "SNPE/SNPE.hpp"
#include "DlSystem/ITensor.hpp"
#include "DlSystem/StringList.hpp"
#include "DlSystem/TensorMap.hpp"
#include "DlSystem/TensorShape.hpp"
#ifdef __ANDROID_API__
#include <android/log.h>
#define TAG "LoadInputTensor JNI"
#define _UNKNOWN 0
#define _DEFAULT 1
#define _VERBOSE 2
#define _DEBUG 3
#define _INFO 4
#define _WARN 5
#define _ERROR 6
#define _FATAL 7
#define _SILENT 8
#define LOGUNK(...) __android_log_print(_UNKNOWN,TAG,__VA_ARGS__)
#define LOGDEF(...) __android_log_print(_DEFAULT,TAG,__VA_ARGS__)
#define LOGV(...) __android_log_print(_VERBOSE,TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(_DEBUG,TAG,__VA_ARGS__)
#define LOGI(...) __android_log_print(_INFO,TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(_WARN,TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(_ERROR,TAG,__VA_ARGS__)
#define LOGF(...) __android_log_print(_FATAL,TAG,__VA_ARGS__)
#define LOGS(...) __android_log_print(_SILENT,TAG,__VA_ARGS__)
#endif
/*** NEMO ***/
void saveOutputToBuffer(zdl::DlSystem::TensorMap outputTensorMap, float * buffer){
// Get all output tensor names from the network
zdl::DlSystem::StringList tensorNames = outputTensorMap.getTensorNames();
// Iterate through the output Tensor map, and print each output layer name to a raw file
std::for_each( tensorNames.begin(), tensorNames.end(), [&](const char* name)
{
auto tensorPtr = outputTensorMap.getTensor(name);
size_t batchChunk = tensorPtr->getSize();
auto it = tensorPtr->cbegin();
memcpy(buffer, it.dataPointer(), batchChunk * sizeof(float)); // here causes free()
});
}
/*** NEMO ***/
// Print the results to raw files
// ITensor
bool saveOutput (zdl::DlSystem::TensorMap outputTensorMap,
const std::string& outputDir,
int num,
size_t batchSize)
{
// Get all output tensor names from the network
zdl::DlSystem::StringList tensorNames = outputTensorMap.getTensorNames();
// Iterate through the output Tensor map, and print each output layer name to a raw file
for( auto& name : tensorNames)
{
// Split the batched output tensor and save the results
for(size_t i=0; i<batchSize; i++) {
std::ostringstream path;
path << outputDir << "/"
<< "Result_" << num + i << "/"
<< name << ".raw";
auto tensorPtr = outputTensorMap.getTensor(name);
size_t batchChunk = tensorPtr->getSize() / batchSize;
if(!SaveITensorBatched(path.str(), tensorPtr, i, batchChunk))
{
return false;
}
}
}
return true;
}
// Execute the network on an input user buffer map and print results to raw files
bool saveOutput (zdl::DlSystem::UserBufferMap& outputMap,
std::unordered_map<std::string,std::vector<uint8_t>>& applicationOutputBuffers,
const std::string& outputDir,
int num,
size_t batchSize,
bool isTf8Buffer)
{
// Get all output buffer names from the network
const zdl::DlSystem::StringList& outputBufferNames = outputMap.getUserBufferNames();
// Iterate through output buffers and print each output to a raw file
for(auto& name : outputBufferNames)
{
for(size_t i=0; i<batchSize; i++) {
std::ostringstream path;
path << outputDir << "/"
<< "Result_" << num + i << "/"
<< name << ".raw";
auto bufferPtr = outputMap.getUserBuffer(name);
size_t batchChunk = bufferPtr->getSize() / batchSize;
size_t dataChunk = bufferPtr->getOutputSize() / batchSize;
if(batchChunk != dataChunk) {
std::cout << "\tUserBuffer size is " << bufferPtr->getSize() << " bytes, but "
<< bufferPtr->getOutputSize() << " bytes of data was found." << std::endl;
if( dataChunk > batchChunk )
std::cout << "\tAssign a larger buffer using a bigger -z argument" << std::endl;
batchChunk = std::min(batchChunk,dataChunk);
}
if (isTf8Buffer)
{
std::vector<uint8_t> output;
zdl::DlSystem::UserBufferEncodingTf8 ubetf8 = dynamic_cast<zdl::DlSystem::UserBufferEncodingTf8 &>(outputMap.getUserBuffer(name)->getEncoding());
output.resize(applicationOutputBuffers.at(name).size() * sizeof(float));
Tf8ToFloat(reinterpret_cast<float *>(&output[0]),applicationOutputBuffers.at(name).data(),ubetf8.getStepExactly0(),ubetf8.getQuantizedStepSize(),applicationOutputBuffers.at(name).size());
if(!SaveUserBufferBatched(path.str(), output, i, batchChunk * sizeof(float)))
{
return false;
}
}
else
{
if(!SaveUserBufferBatched(path.str(), applicationOutputBuffers.at(name), i, batchChunk))
{
return false;
}
}
}
}
return true;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The taco developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "util.h"
#include "ui_interface.h"
#include <set>
#include <stdint.h>
using namespace std;
using namespace json_spirit;
class CRPCConvertParam
{
public:
std::string methodName; //! method whose params want conversion
int paramIdx; //! 0-based idx of param to convert
};
// ***TODO***
static const CRPCConvertParam vRPCConvertParams[] =
{
{ "stop", 0 },
{ "setmocktime", 0 },
{ "getaddednodeinfo", 0 },
{ "setgenerate", 0 },
{ "setgenerate", 1 },
{ "getnetworkhashps", 0 },
{ "getnetworkhashps", 1 },
{ "sendtoaddress", 1 },
{ "sendtoaddressix", 1 },
{ "settxfee", 0 },
{ "getreceivedbyaddress", 1 },
{ "getreceivedbyaccount", 1 },
{ "listreceivedbyaddress", 0 },
{ "listreceivedbyaddress", 1 },
{ "listreceivedbyaddress", 2 },
{ "listreceivedbyaccount", 0 },
{ "listreceivedbyaccount", 1 },
{ "listreceivedbyaccount", 2 },
{ "getbalance", 1 },
{ "getbalance", 2 },
{ "getblockhash", 0 },
{ "move", 2 },
{ "move", 3 },
{ "sendfrom", 2 },
{ "sendfrom", 3 },
{ "listtransactions", 1 },
{ "listtransactions", 2 },
{ "listtransactions", 3 },
{ "listaccounts", 0 },
{ "listaccounts", 1 },
{ "walletpassphrase", 1 },
{ "walletpassphrase", 2 },
{ "getblocktemplate", 0 },
{ "listsinceblock", 1 },
{ "listsinceblock", 2 },
{ "sendmany", 1 },
{ "sendmany", 2 },
{ "addmultisigaddress", 0 },
{ "addmultisigaddress", 1 },
{ "createmultisig", 0 },
{ "createmultisig", 1 },
{ "listunspent", 0 },
{ "listunspent", 1 },
{ "listunspent", 2 },
{ "getblock", 1 },
{ "getblockheader", 1 },
{ "gettransaction", 1 },
{ "getrawtransaction", 1 },
{ "createrawtransaction", 0 },
{ "createrawtransaction", 1 },
{ "signrawtransaction", 1 },
{ "signrawtransaction", 2 },
{ "sendrawtransaction", 1 },
{ "gettxout", 1 },
{ "gettxout", 2 },
{ "lockunspent", 0 },
{ "lockunspent", 1 },
{ "importprivkey", 2 },
{ "importaddress", 2 },
{ "verifychain", 0 },
{ "verifychain", 1 },
{ "keypoolrefill", 0 },
{ "getrawmempool", 0 },
{ "estimatefee", 0 },
{ "estimatepriority", 0 },
{ "prioritisetransaction", 1 },
{ "prioritisetransaction", 2 },
{ "spork", 1 },
{ "mnbudget", 3 },
{ "mnbudget", 4 },
{ "mnbudget", 6 },
{ "mnbudget", 8 },
{ "mnbudgetvoteraw", 1 },
{ "mnbudgetvoteraw", 4 },
};
class CRPCConvertTable
{
private:
std::set<std::pair<std::string, int> > members;
public:
CRPCConvertTable();
bool convert(const std::string& method, int idx) {
return (members.count(std::make_pair(method, idx)) > 0);
}
};
CRPCConvertTable::CRPCConvertTable()
{
const unsigned int n_elem =
(sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0]));
for (unsigned int i = 0; i < n_elem; i++) {
members.insert(std::make_pair(vRPCConvertParams[i].methodName,
vRPCConvertParams[i].paramIdx));
}
}
static CRPCConvertTable rpcCvtTable;
/** Convert strings to command-specific RPC representation */
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
for (unsigned int idx = 0; idx < strParams.size(); idx++) {
const std::string& strVal = strParams[idx];
// insert string value directly
if (!rpcCvtTable.convert(strMethod, idx)) {
params.push_back(strVal);
}
// parse string as JSON, insert bool/number/object/etc. value
else {
Value jVal;
if (!read_string(strVal, jVal))
throw runtime_error(string("Error parsing JSON:")+strVal);
params.push_back(jVal);
}
}
return params;
}
|
#include "json/document.h"
#include "json/filestream.h"
#include "json/stringbuffer.h"
#include "json/writer.h"
#include "ConfigParser.h"
// ConfigParser
ConfigParser *ConfigParser::s_sharedInstance = NULL;
ConfigParser *ConfigParser::getInstance(void)
{
if (!s_sharedInstance)
{
s_sharedInstance = new ConfigParser();
}
return s_sharedInstance;
}
bool ConfigParser::isInit()
{
return _isInit;
}
void ConfigParser::readConfig()
{
_isInit = true;
string filecfg = "config.json";
string fileContent;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID && !defined(NDEBUG)) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS && defined(COCOS2D_DEBUG))
string fullPathFile = FileUtils::getInstance()->getWritablePath();
fullPathFile.append("debugruntime/");
fullPathFile.append(filecfg.c_str());
fileContent=FileUtils::getInstance()->getStringFromFile(fullPathFile.c_str());
#endif
if (fileContent.empty()) {
filecfg=FileUtils::getInstance()->fullPathForFilename(filecfg.c_str());
fileContent=FileUtils::getInstance()->getStringFromFile(filecfg.c_str());
}
if(!fileContent.empty())
{
_docRootjson.Parse<0>(fileContent.c_str());
if (_docRootjson.HasMember("init_cfg"))
{
if(_docRootjson["init_cfg"].IsObject())
{
const rapidjson::Value& objectInitView = _docRootjson["init_cfg"];
if (objectInitView.HasMember("width") && objectInitView.HasMember("height"))
{
_initViewSize.width = objectInitView["width"].GetUint();
_initViewSize.height = objectInitView["height"].GetUint();
if (_initViewSize.height>_initViewSize.width)
{
float tmpvalue =_initViewSize.height;
_initViewSize.height = _initViewSize.width;
_initViewSize.width = tmpvalue;
}
}
if (objectInitView.HasMember("name") && objectInitView["name"].IsString())
{
_viewName = objectInitView["name"].GetString();
}
if (objectInitView.HasMember("isLandscape") && objectInitView["isLandscape"].IsBool()) {
_isLandscape = objectInitView["isLandscape"].GetBool();
}
if (objectInitView.HasMember("entry") && objectInitView["entry"].IsString()) {
_entryfile = objectInitView["entry"].GetString();
}
}
}
if (_docRootjson.HasMember("simulator_screen_size"))
{
const rapidjson::Value& ArrayScreenSize = _docRootjson["simulator_screen_size"];
if (ArrayScreenSize.IsArray())
{
for (int i=0; i<ArrayScreenSize.Size(); i++)
{
const rapidjson::Value& objectScreenSize = ArrayScreenSize[i];
if (objectScreenSize.HasMember("title") && objectScreenSize.HasMember("width") && objectScreenSize.HasMember("height"))
{
_screenSizeArray.push_back(SimulatorScreenSize(objectScreenSize["title"].GetString(), objectScreenSize["width"].GetUint(), objectScreenSize["height"].GetUint()));
}
}
}
}
}
}
ConfigParser::ConfigParser(void):_isInit(false),_isLandscape(true)
{
_initViewSize.setSize(960,640);
_viewName = "SnakeGameLua";
_entryfile = "src/main.lua";
}
rapidjson::Document& ConfigParser::getConfigJsonRoot()
{
return _docRootjson;
}
string ConfigParser::getInitViewName()
{
return _viewName;
}
string ConfigParser::getEntryFile()
{
return _entryfile;
}
Size ConfigParser::getInitViewSize()
{
return _initViewSize;
}
bool ConfigParser::isLanscape()
{
return _isLandscape;
}
int ConfigParser::getScreenSizeCount(void)
{
return (int)_screenSizeArray.size();
}
const SimulatorScreenSize ConfigParser::getScreenSize(int index)
{
return _screenSizeArray.at(index);
}
|
#include "DrawableObjectCommon.h"
#include "mylog.h"
#include <assert.h>
#include "HelpFunction.h"
#include "MatrixState3D.h"
#include <string.h>
DrawableObjectCommon::DrawableObjectCommon(float* vdataIn,int dataByteCount,int vCountIn,VkDevice& device,VkPhysicalDeviceMemoryProperties& memoryroperties)
{
this->devicePointer=&device;
this->vdata=vdataIn;
this->vCount=vCountIn;
VkBufferCreateInfo buf_info = {};
buf_info.sType =VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.pNext = NULL;
buf_info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
buf_info.size = dataByteCount;
buf_info.queueFamilyIndexCount = 0;
buf_info.pQueueFamilyIndices = NULL;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
buf_info.flags = 0;
VkResult result = vk::vkCreateBuffer(device,&buf_info, NULL, &vertexDatabuf);
assert(result == VK_SUCCESS);
VkMemoryRequirements mem_reqs;
vk::vkGetBufferMemoryRequirements(device, vertexDatabuf, &mem_reqs);
assert(dataByteCount<=mem_reqs.size);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.pNext = NULL;
alloc_info.memoryTypeIndex = 0;
alloc_info.allocationSize = mem_reqs.size;
VkFlags requirements_mask=VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT| VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
bool flag=memoryTypeFromProperties(memoryroperties,mem_reqs.memoryTypeBits,requirements_mask,&alloc_info.memoryTypeIndex);
if(flag){
LOGE("确定内存类型成功 类型索引为%d",alloc_info.memoryTypeIndex);
}else{
LOGE("确定内存类型失败!");
}
result = vk::vkAllocateMemory(device,&alloc_info, NULL, &vertexDataMem);
assert(result == VK_SUCCESS);
uint8_t *pData;
result = vk::vkMapMemory(device, vertexDataMem, 0, mem_reqs.size, 0, (void **)&pData);
assert(result == VK_SUCCESS);
memcpy(pData, vdata, dataByteCount);
vk::vkUnmapMemory(device, vertexDataMem);
result = vk::vkBindBufferMemory(device,vertexDatabuf, vertexDataMem, 0);
assert(result == VK_SUCCESS);
vertexDataBufferInfo.buffer = vertexDatabuf;
vertexDataBufferInfo.offset = 0;
vertexDataBufferInfo.range = mem_reqs.size;
}
DrawableObjectCommon::~DrawableObjectCommon()
{
delete vdata;
vk::vkDestroyBuffer(*devicePointer, vertexDatabuf, NULL);
vk::vkFreeMemory(*devicePointer, vertexDataMem, NULL);
}
void DrawableObjectCommon::drawSelf(VkCommandBuffer& cmd,VkPipelineLayout& pipelineLayout,VkPipeline& pipeline,VkDescriptorSet* desSetPointer)
{
vk::vkCmdBindPipeline(cmd,VK_PIPELINE_BIND_POINT_GRAPHICS,pipeline);
vk::vkCmdBindDescriptorSets(cmd,VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1,desSetPointer, 0, NULL);
const VkDeviceSize offsetsVertex[1] = {0};
vk::vkCmdBindVertexBuffers(
cmd,
0,
1,
&(vertexDatabuf),
offsetsVertex
);
vk::vkCmdDraw(cmd, vCount, 1, 0, 0);
}
|
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 "frontend/parallel/ops_info/gatherd_info.h"
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "frontend/parallel/device_matrix.h"
#include "frontend/parallel/strategy.h"
#include "frontend/parallel/tensor_layout/tensor_redistribution.h"
#include "pipeline/jit/resource.h"
namespace mindspore {
namespace parallel {
Status GatherDInfo::GetAttrs() {
if (input_value_.size() != 3) {
MS_LOG(ERROR) << name_ << ": Invalid input_value's size " << input_value_.size();
return FAILED;
}
if (!input_value_[1]->isa<Int64Imm>()) {
MS_LOG(ERROR) << name_ << ": The value of dim is not int";
return FAILED;
}
int64_t dim = GetValue<int64_t>(input_value_[1]);
int64_t input_dim = SizeToLong(inputs_shape_[0].size());
if ((dim > (input_dim - 1)) || (dim < -input_dim)) {
MS_LOG(ERROR) << name_ << ": The dim(" << dim << ") is out of range[" << (-input_dim) << ", " << (input_dim - 1)
<< "]";
return FAILED;
}
if (dim < 0) {
dim += input_dim;
}
dim_ = LongToSize(dim);
MS_LOG(INFO) << name_ << ": The dim is " << dim_;
return SUCCESS;
}
Status GatherDInfo::CheckStrategy(const StrategyPtr &strategy) {
MS_EXCEPTION_IF_NULL(strategy);
if (CheckStrategyValue(strategy, inputs_shape_) != SUCCESS) {
MS_LOG(ERROR) << name_ << ": Invalid strategy";
return FAILED;
}
std::vector<Dimensions> stra = strategy->GetInputDim();
if (stra.size() != 2) {
MS_LOG(ERROR) << name_ << ": The size of strategy must be 2, but got " << stra.size();
return FAILED;
}
Dimensions input_strategy = stra[0];
Dimensions index_strategy = stra[1];
if (input_strategy[dim_] != 1 || index_strategy[dim_] != 1) {
MS_LOG(ERROR) << name_ << ": The dimension of dim can not be split";
return FAILED;
}
if (input_strategy != index_strategy) {
MS_LOG(ERROR) << name_ << ": The dimension of dim can not be split";
return FAILED;
}
return SUCCESS;
}
Status GatherDInfo::InferDevMatrixShape() {
MS_EXCEPTION_IF_NULL(strategy_);
std::vector<Dimensions> stra = strategy_->GetInputDim();
if (stra.empty()) {
MS_LOG(ERROR) << name_ << ": The strategy is empty";
return FAILED;
}
dev_matrix_shape_ = stra[0];
return SUCCESS;
}
Status GatherDInfo::InferTensorMap() {
Shape input_tensor_map;
size_t size = inputs_shape_[0].size();
for (size_t i = 0; i < size; ++i) {
input_tensor_map.push_back(SizeToLong(size - i - 1));
}
inputs_tensor_map_.push_back(input_tensor_map); // input
inputs_tensor_map_.push_back(input_tensor_map); // index
outputs_tensor_map_.push_back(input_tensor_map); // output
return SUCCESS;
}
Status GatherDInfo::InferTensorInfo() {
if (inputs_shape_.empty() || outputs_shape_.empty() || inputs_tensor_map_.empty() || outputs_tensor_map_.empty()) {
MS_LOG(ERROR) << name_ << ": Invalid args";
return FAILED;
}
for (size_t i = 0; i < inputs_tensor_map_.size(); ++i) {
TensorLayout input_layout;
if (input_layout.InitFromVector(dev_matrix_shape_, inputs_tensor_map_[i], inputs_shape_[i]) != SUCCESS) {
MS_LOG(ERROR) << name_ << ": Infer input tensor layout failed, the index is " << i;
return FAILED;
}
TensorInfo input_tensor_info(input_layout);
inputs_tensor_info_.push_back(input_tensor_info);
}
TensorInfo dim_tensor_info;
(void)inputs_tensor_info_.insert(inputs_tensor_info_.begin() + 1, dim_tensor_info);
for (size_t i = 0; i < outputs_tensor_map_.size(); ++i) {
TensorLayout output_layout;
if (output_layout.InitFromVector(dev_matrix_shape_, outputs_tensor_map_[i], outputs_shape_[i]) != SUCCESS) {
MS_LOG(ERROR) << name_ << ": Infer output tensor layout failed, the index is " << i;
return FAILED;
}
TensorInfo output_tensor_info(output_layout);
outputs_tensor_info_.push_back(output_tensor_info);
}
return SUCCESS;
}
Status GatherDInfo::InferMirrorOps() {
mirror_ops_.clear();
if (inputs_shape_.empty()) {
MS_LOG(INFO) << name_ << ": The inputs size is empty";
return SUCCESS;
}
if (inputs_tensor_map_.size() != inputs_shape_.size()) {
MS_LOG(ERROR) << name_ << ": The size of inputs tensor map is not equal to the size of inputs shape";
return FAILED;
}
std::vector<Group> group;
if (CreateGroupByTensorMap(inputs_tensor_map_[0], &group) != SUCCESS) {
MS_LOG(ERROR) << name_ << ": Create group failed";
return FAILED;
}
if (group.empty()) {
MS_LOG(INFO) << name_ << ": No need to create mirror ops";
return SUCCESS;
}
OperatorVector mirror_op = CreateMirrorOps(group[0].name(), group[0].GetDevNum());
mirror_ops_.push_back(mirror_op); // input
OperatorVector tmp_mirror_op; // dim
mirror_ops_.push_back(tmp_mirror_op);
mirror_ops_.push_back(mirror_op); // index
return SUCCESS;
}
void GatherDInfo::ReComputeBatchSplitFlagList() {
if (InferAttrs() != SUCCESS) {
MS_LOG(EXCEPTION) << name_ << ": Infer attrs failed";
}
if (dim_ == 0) {
MS_LOG(EXCEPTION)
<< name_
<< ": Can not generate batch data parallel strategy since the dim is 0, please set others strategy for it";
}
for (size_t i = 0; i < inputs_shape_.size(); ++i) {
split_flag_list_[i] = true;
}
}
Status GatherDInfo::SetCostUnderStrategy(const StrategyPtr &strategy) { return SetCostUnderStrategyBase(strategy); }
std::vector<StrategyPtr> GatherDInfo::GenerateOpStrategies(int64_t stage_id) {
Shape input0_split(inputs_shape_[0].size(), 1);
input0_split[dim_] = 0;
Shapes splittable_inputs = {input0_split};
Shapes tmp_inputs_shape = {inputs_shape_[0]};
std::vector<StrategyPtr> sp_vector;
if (GenerateStrategiesForIndependentInputs(stage_id, tmp_inputs_shape, splittable_inputs, &sp_vector) != SUCCESS) {
MS_LOG(EXCEPTION) << name_ << " : Generate strategies for independent inputs() failed.";
}
for (auto &sp : sp_vector) {
if ((sp == nullptr) || sp->GetInputDim().empty()) {
MS_LOG(EXCEPTION) << name_ << ": The strategy is null or empty";
}
Strategys tmp_strategy;
Dimensions first_input_strategy = sp->GetInputDim()[0];
for (size_t i = 0; i < inputs_shape_.size(); ++i) {
tmp_strategy.push_back(first_input_strategy);
}
sp->ResetInputs(tmp_strategy);
}
return sp_vector;
}
Status GatherDInfo::Init(const StrategyPtr &strategy) {
if (InitWithAutoRepeatCalc(strategy) != SUCCESS) {
MS_LOG(ERROR) << name_ << ": Init failed.";
return FAILED;
}
MS_LOG(INFO) << name_ << ": Init success.";
return SUCCESS;
}
Status GatherDInfo::InitForCostModel(const StrategyPtr &strategy) {
if (InitForCostModelWithAutoRepeatCalc(strategy) != SUCCESS) {
MS_LOG(ERROR) << name_ << ": Init for cost model failed.";
return FAILED;
}
MS_LOG(INFO) << name_ << ": Init for cost model success.";
return SUCCESS;
}
} // namespace parallel
} // namespace mindspore
|
#include <iostream>
#include <memory>
using namespace std;
class Foo{
public:
Foo(){
cout << "Creating foo at " << this << endl;
}
~Foo(){
cout << "destructing Foo at " << this << endl;
}
};
class Bar{
private:
std::shared_ptr<Foo> m_foo;
public:
Bar(){
m_foo.reset(new Foo());
cout << "creating Bar at" << this << endl;
}
~Bar(){
// delete m_foo;
cout << "Destructing Bar at " << this << endl;
}
};
int main(){
Bar original;
Bar copy = original; // unique_ptr is not copyable
return 0;
}
|
/**
* @file load_arff.hpp
* @author Ryan Curtin
*
* Load an ARFF dataset.
*/
#ifndef MLPACK_CORE_DATA_LOAD_ARFF_HPP
#define MLPACK_CORE_DATA_LOAD_ARFF_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace data {
/**
* A utility function to load an ARFF dataset as numeric features (that is, as
* an Armadillo matrix without any modification). An exception will be thrown
* if any features are non-numeric.
*/
template<typename eT>
void LoadARFF(const std::string& filename, arma::Mat<eT>& matrix);
/**
* A utility function to load an ARFF dataset as numeric and categorical
* features, using the DatasetInfo structure for mapping. An exception will be
* thrown upon failure.
*
* A pre-existing DatasetInfo object can be passed in, but if the dimensionality
* of the given DatasetInfo object (info.Dimensionality()) does not match the
* dimensionality of the data, a std::invalid_argument exception will be thrown.
* If an empty DatasetInfo object is given (constructed with the default
* constructor or otherwise, so that info.Dimensionality() is 0), it will be set
* to the right dimensionality.
*
* This ability to pass in pre-existing DatasetInfo objects is very necessary
* when, e.g., loading a test set after training. If the same DatasetInfo from
* loading the training set is not used, then the test set may be loaded with
* different mappings---which can cause horrible problems!
*
* @param filename Name of ARFF file to load.
* @param matrix Matrix to load data into.
* @param info DatasetInfo object; can be default-constructed or pre-existing
* from another call to LoadARFF().
*/
template<typename eT, typename PolicyType>
void LoadARFF(const std::string& filename,
arma::Mat<eT>& matrix,
DatasetMapper<PolicyType>& info);
} // namespace data
} // namespace mlpack
// Include implementation.
#include "load_arff_impl.hpp"
#endif
|
// Hash function hashlittle()
// from lookup3.c, by Bob Jenkins, May 2006, Public Domain
// bob_jenkins@burtleburtle.net
#include "stddef.h"
#include "vtkType.h"
#include "hash.h"
#define HASH_LITTLE_ENDIAN 1 // Intel and AMD are little endian
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
/*
-------------------------------------------------------------------------------
mix -- mix 3 32-bit values reversibly.
This is reversible, so any information in (a,b,c) before mix() is
still in (a,b,c) after mix().
If four pairs of (a,b,c) inputs are run through mix(), or through
mix() in reverse, there are at least 32 bits of the output that
are sometimes the same for one pair and different for another pair.
This was tested for:
* pairs that differed by one bit, by two bits, in any combination
of top bits of (a,b,c), or in any combination of bottom bits of
(a,b,c).
* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
is commonly produced by subtraction) look like a single 1-bit
difference.
* the base values were pseudorandom, all zero but one bit set, or
all zero plus a counter that starts at zero.
Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
satisfy this are
4 6 8 16 19 4
9 15 3 18 27 15
14 9 3 7 17 3
Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
for "differ" defined as + with a one-bit base and a two-bit delta. I
used http://burtleburtle.net/bob/hash/avalanche.html to choose
the operations, constants, and arrangements of the variables.
This does not achieve avalanche. There are input bits of (a,b,c)
that fail to affect some output bits of (a,b,c), especially of a. The
most thoroughly mixed value is c, but it doesn't really even achieve
avalanche in c.
This allows some parallelism. Read-after-writes are good at doubling
the number of bits affected, so the goal of mixing pulls in the opposite
direction as the goal of parallelism. I did what I could. Rotates
seem to cost as much as shifts on every machine I could lay my hands
on, and rotates are much kinder to the top and bottom bits, so I used
rotates.
-------------------------------------------------------------------------------
*/
#define mix(a,b,c) \
{ \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
/*
-------------------------------------------------------------------------------
final -- final mixing of 3 32-bit values (a,b,c) into c
Pairs of (a,b,c) values differing in only a few bits will usually
produce values of c that look totally different. This was tested for
* pairs that differed by one bit, by two bits, in any combination
of top bits of (a,b,c), or in any combination of bottom bits of
(a,b,c).
* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
is commonly produced by subtraction) look like a single 1-bit
difference.
* the base values were pseudorandom, all zero but one bit set, or
all zero plus a counter that starts at zero.
These constants passed:
14 11 25 16 4 14 24
12 14 25 16 4 14 24
and these came close:
4 8 15 26 3 22 24
10 8 15 26 3 22 24
11 8 15 26 3 22 24
-------------------------------------------------------------------------------
*/
#define final(a,b,c) \
{ \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
/*
-------------------------------------------------------------------------------
hashlittle() -- hash a variable-length key into a 32-bit value
k : the key (the unaligned variable-length array of bytes)
length : the length of the key, counting by bytes
initval : can be any 4-byte value
Returns a 32-bit value. Every bit of the key affects every bit of
the return value. Two keys differing by one or two bits will have
totally different hash values.
The best hash table sizes are powers of 2. There is no need to do
mod a prime (mod is sooo slow!). If you need less than 32 bits,
use a bitmask. For example, if you need only 10 bits, do
h = (h & hashmask(10));
In which case, the hash table should have hashsize(10) elements.
If you are hashing n strings (vtkTypeUInt8 **)k, do it like this:
for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
code any way you wish, private, educational, or commercial. It's free.
Use for hash table lookup, or anything where one collision in 2^^32 is
acceptable. Do NOT use for cryptographic purposes.
-------------------------------------------------------------------------------
*/
vtkTypeUInt32 hashlittle( const void *key, size_t length, vtkTypeUInt32 initval)
{
vtkTypeUInt32 a,b,c; /* internal state */
union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
/* Set up the internal state */
a = b = c = 0xdeadbeef + ((vtkTypeUInt32)length) + initval;
u.ptr = key;
if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
const vtkTypeUInt32 *k = (const vtkTypeUInt32 *)key; /* read 32-bit chunks */
const vtkTypeUInt8 *k8 = 0;
(void)k8;
/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
while (length > 12)
{
a += k[0];
b += k[1];
c += k[2];
mix(a,b,c);
length -= 12;
k += 3;
}
/*----------------------------- handle the last (probably partial) block */
/*
* "k[2]&0xffffff" actually reads beyond the end of the string, but
* then masks off the part it's not allowed to read. Because the
* string is aligned, the masked-off tail is in the same word as the
* rest of the string. Every machine with memory protection I've seen
* does it on word boundaries, so is OK with this. But VALGRIND will
* still catch it and complain. The masking trick does make the hash
* noticably faster for short strings (like English words).
*/
#ifndef VALGRIND
switch(length)
{
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
case 6 : b+=k[1]&0xffff; a+=k[0]; break;
case 5 : b+=k[1]&0xff; a+=k[0]; break;
case 4 : a+=k[0]; break;
case 3 : a+=k[0]&0xffffff; break;
case 2 : a+=k[0]&0xffff; break;
case 1 : a+=k[0]&0xff; break;
case 0 : return c; /* zero length strings require no mixing */
}
#else /* make valgrind happy */
k8 = (const vtkTypeUInt8 *)k;
switch(length)
{
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=((vtkTypeUInt32)k8[10])<<16; /* fall through */
case 10: c+=((vtkTypeUInt32)k8[9])<<8; /* fall through */
case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=((vtkTypeUInt32)k8[6])<<16; /* fall through */
case 6 : b+=((vtkTypeUInt32)k8[5])<<8; /* fall through */
case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]; break;
case 3 : a+=((vtkTypeUInt32)k8[2])<<16; /* fall through */
case 2 : a+=((vtkTypeUInt32)k8[1])<<8; /* fall through */
case 1 : a+=k8[0]; break;
case 0 : return c;
}
#endif /* !valgrind */
} else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
const vtkTypeUInt16 *k = (const vtkTypeUInt16 *)key; /* read 16-bit chunks */
const vtkTypeUInt8 *k8;
/*--------------- all but last block: aligned reads and different mixing */
while (length > 12)
{
a += k[0] + (((vtkTypeUInt32)k[1])<<16);
b += k[2] + (((vtkTypeUInt32)k[3])<<16);
c += k[4] + (((vtkTypeUInt32)k[5])<<16);
mix(a,b,c);
length -= 12;
k += 6;
}
/*----------------------------- handle the last (probably partial) block */
k8 = (const vtkTypeUInt8 *)k;
switch(length)
{
case 12: c+=k[4]+(((vtkTypeUInt32)k[5])<<16);
b+=k[2]+(((vtkTypeUInt32)k[3])<<16);
a+=k[0]+(((vtkTypeUInt32)k[1])<<16);
break;
case 11: c+=((vtkTypeUInt32)k8[10])<<16; /* fall through */
case 10: c+=k[4];
b+=k[2]+(((vtkTypeUInt32)k[3])<<16);
a+=k[0]+(((vtkTypeUInt32)k[1])<<16);
break;
case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[2]+(((vtkTypeUInt32)k[3])<<16);
a+=k[0]+(((vtkTypeUInt32)k[1])<<16);
break;
case 7 : b+=((vtkTypeUInt32)k8[6])<<16; /* fall through */
case 6 : b+=k[2];
a+=k[0]+(((vtkTypeUInt32)k[1])<<16);
break;
case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]+(((vtkTypeUInt32)k[1])<<16);
break;
case 3 : a+=((vtkTypeUInt32)k8[2])<<16; /* fall through */
case 2 : a+=k[0];
break;
case 1 : a+=k8[0];
break;
case 0 : return c; /* zero length requires no mixing */
}
} else { /* need to read the key one byte at a time */
const vtkTypeUInt8 *k = (const vtkTypeUInt8 *)key;
/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
while (length > 12)
{
a += k[0];
a += ((vtkTypeUInt32)k[1])<<8;
a += ((vtkTypeUInt32)k[2])<<16;
a += ((vtkTypeUInt32)k[3])<<24;
b += k[4];
b += ((vtkTypeUInt32)k[5])<<8;
b += ((vtkTypeUInt32)k[6])<<16;
b += ((vtkTypeUInt32)k[7])<<24;
c += k[8];
c += ((vtkTypeUInt32)k[9])<<8;
c += ((vtkTypeUInt32)k[10])<<16;
c += ((vtkTypeUInt32)k[11])<<24;
mix(a,b,c);
length -= 12;
k += 12;
}
/*-------------------------------- last block: affect all 32 bits of (c) */
switch(length) /* all the case statements fall through */
{
case 12: c+=((vtkTypeUInt32)k[11])<<24;
case 11: c+=((vtkTypeUInt32)k[10])<<16;
case 10: c+=((vtkTypeUInt32)k[9])<<8;
case 9 : c+=k[8];
case 8 : b+=((vtkTypeUInt32)k[7])<<24;
case 7 : b+=((vtkTypeUInt32)k[6])<<16;
case 6 : b+=((vtkTypeUInt32)k[5])<<8;
case 5 : b+=k[4];
case 4 : a+=((vtkTypeUInt32)k[3])<<24;
case 3 : a+=((vtkTypeUInt32)k[2])<<16;
case 2 : a+=((vtkTypeUInt32)k[1])<<8;
case 1 : a+=k[0];
break;
case 0 : return c;
}
}
final(a,b,c);
return c;
}
|
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2015 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#include "framework/image.h"
#include "ozz/base/io/stream.h"
#include "ozz/base/log.h"
#include "ozz/base/memory/allocator.h"
namespace ozz {
namespace sample {
namespace image {
bool HasAlpha(Format::Value _format) { return _format >= Format::kRGBA; }
int Stride(Format::Value _format) { return _format <= Format::kBGR ? 3 : 4; }
#define PUSH_PIXEL_RGB(_buffer, _size, _repetition, _pixel, _mapping) \
_buffer[_size + 0] = 0x80 | ((_repetition - 1) & 0xff); \
_buffer[_size + 1] = _pixel.c[_mapping[0]]; \
_buffer[_size + 2] = _pixel.c[_mapping[1]]; \
_buffer[_size + 3] = _pixel.c[_mapping[2]]; \
_size += 4;
#define PUSH_PIXEL_RGBA(_buffer, _size, _repetition, _pixel, _mapping) \
_buffer[_size + 0] = 0x80 | ((_repetition - 1) & 0xff); \
_buffer[_size + 1] = _pixel.c[_mapping[0]]; \
_buffer[_size + 2] = _pixel.c[_mapping[1]]; \
_buffer[_size + 3] = _pixel.c[_mapping[2]]; \
_buffer[_size + 4] = _pixel.c[_mapping[3]]; \
_size += 5;
bool WriteTGA(const char* _filename, int _width, int _height,
Format::Value _src_format, const uint8_t* _src_buffer,
bool _write_alpha) {
union Pixel {
uint8_t c[4];
uint32_t p;
};
assert(_filename && _src_buffer);
ozz::log::LogV() << "Write image to TGA file \"" << _filename << "\"."
<< std::endl;
// Opens output file.
ozz::io::File file(_filename, "wb");
if (!file.opened()) {
ozz::log::Err() << "Failed to open file \"" << _filename
<< "\" for writing." << std::endl;
return false;
}
// Builds and writes tga header.
const uint8_t header[] = {
0, // ID length
0, // Color map type
10, // Image type (RLE true-color)
0,
0,
0,
0,
0, // Color map specification (no color map)
0,
0, // X-origin (2 bytes little-endian)
0,
0, // Y-origin (2 bytes little-endian)
static_cast<uint8_t>(_width & 0xff), // Width (2 bytes little-endian)
static_cast<uint8_t>((_width >> 8) & 0xff),
static_cast<uint8_t>(_height & 0xff), // Height (2 bytes little-endian)
static_cast<uint8_t>((_height >> 8) & 0xff),
static_cast<uint8_t>(_write_alpha ? 32 : 24), // Pixel depth
0}; // Image descriptor
OZZ_STATIC_ASSERT(sizeof(header) == 18);
file.Write(header, sizeof(header));
// Early out if no pixel to write.
if (!_width || !_height) {
return true;
}
// Writes pixels, with RLE compression.
// Prepares component mappings from src to TARGA format.
const uint8_t mappings[4][4] = {
{2, 1, 0, 0}, {0, 1, 2, 0}, {2, 1, 0, 3}, {0, 1, 2, 3}};
const uint8_t* mapping = mappings[_src_format];
// Allocates enough space to store RLE packets for the worst case scenario.
uint8_t* dest_buffer = ozz::memory::default_allocator()->Allocate<uint8_t>(
(1 + (_write_alpha ? 4 : 3)) * _width * _height);
size_t dest_size = 0;
if (HasAlpha(_src_format)) {
assert(Stride(_src_format) == 4);
const int src_pitch = _width * 4;
const int src_size = _height * src_pitch;
if (_write_alpha) {
for (int line = 0; line < src_size; line += src_pitch) {
Pixel current = {{_src_buffer[line + 0], _src_buffer[line + 1],
_src_buffer[line + 2], _src_buffer[line + 3]}};
int count = 1;
for (int p = line + 4; p < line + _width * 4; p += 4, count++) {
const Pixel next = {{_src_buffer[p + 0], _src_buffer[p + 1],
_src_buffer[p + 2], _src_buffer[p + 3]}};
if (current.p != next.p || count == 128) {
// Writes current packet.
PUSH_PIXEL_RGBA(dest_buffer, dest_size, count, current, mapping);
// Starts new RLE packet.
current.p = next.p;
count = 0;
}
}
// Finishes the line.
assert(count > 0 && count <= 128);
PUSH_PIXEL_RGBA(dest_buffer, dest_size, count, current, mapping);
}
} else {
for (int line = 0; line < src_size; line += src_pitch) {
Pixel current = {{_src_buffer[line + 0], _src_buffer[line + 1],
_src_buffer[line + 2], 0}};
int count = 1;
for (int p = line + 4; p < line + _width * 4; p += 4, count++) {
const Pixel next = {
{_src_buffer[p + 0], _src_buffer[p + 1], _src_buffer[p + 2], 0}};
if (current.p != next.p || count == 128) {
// Writes current packet.
PUSH_PIXEL_RGB(dest_buffer, dest_size, count, current, mapping);
// Starts new RLE packet.
current.p = next.p;
count = 0;
}
}
// Finishes the line.
assert(count > 0 && count <= 128);
PUSH_PIXEL_RGB(dest_buffer, dest_size, count, current, mapping);
}
}
} else { // Source has no alpha channel.
assert(Stride(_src_format) == 3);
const int src_pitch = _width * 3;
const int src_size = _height * src_pitch;
if (_write_alpha) {
for (int line = 0; line < src_size; line += src_pitch) {
Pixel current = {{_src_buffer[line + 0], _src_buffer[line + 1],
_src_buffer[line + 2], 255}};
int count = 1;
for (int p = line + 3; p < line + _width * 3; p += 3, count++) {
const Pixel next = {{_src_buffer[p + 0], _src_buffer[p + 1],
_src_buffer[p + 2], 255}};
if (current.p != next.p || count == 128) {
// Writes current packet.
PUSH_PIXEL_RGBA(dest_buffer, dest_size, count, current, mapping);
// Starts new RLE packet.
current.p = next.p;
count = 0;
}
}
// Finishes the line.
assert(count > 0 && count <= 128);
PUSH_PIXEL_RGBA(dest_buffer, dest_size, count, current, mapping);
}
} else {
for (int line = 0; line < src_size; line += src_pitch) {
Pixel current = {{_src_buffer[line + 0], _src_buffer[line + 1],
_src_buffer[line + 2], 0}};
int count = 1;
for (int p = line + 3; p < line + _width * 3; p += 3, count++) {
const Pixel next = {
{_src_buffer[p + 0], _src_buffer[p + 1], _src_buffer[p + 2], 0}};
if (current.p != next.p || count == 128) {
// Writes current packet.
PUSH_PIXEL_RGB(dest_buffer, dest_size, count, current, mapping);
// Starts new RLE packet.
current.p = next.p;
count = 0;
}
}
// Finishes the line.
assert(count > 0 && count <= 128);
PUSH_PIXEL_RGB(dest_buffer, dest_size, count, current, mapping);
}
}
}
// Writes all the RLE packets buffer at once.
file.Write(dest_buffer, dest_size);
ozz::memory::default_allocator()->Deallocate(dest_buffer);
return true;
}
#undef PUSH_PIXEL_RGB
#undef PUSH_PIXEL_RGBA
} // image
} // sample
} // ozz
|
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "BsRendererDecal.h"
#include "BsRendererRenderable.h"
#include "Renderer/BsDecal.h"
#include "Mesh/BsMesh.h"
#include "Renderer/BsRendererUtility.h"
namespace bs { namespace ct
{
DecalParamDef gDecalParamDef;
void DecalRenderElement::draw() const
{
gRendererUtility().draw(mesh, subMesh);
}
RendererDecal::RendererDecal()
{
decalParamBuffer = gDecalParamDef.createBuffer();
perObjectParamBuffer = gPerObjectParamDef.createBuffer();
perCallParamBuffer = gPerCallParamDef.createBuffer();
}
void RendererDecal::updatePerObjectBuffer()
{
const Vector2 size = decal->getSize();
const Vector2 extent = size * 0.5f;
const float maxDistance = decal->getMaxDistance();
const Vector3 scale(extent.x, extent.y, maxDistance * 0.5f);
const Vector3 offset(0.0f, 0.0f, -maxDistance * 0.5f);
const Matrix4 scaleAndOffset = Matrix4::TRS(offset, Quaternion::IDENTITY, scale);
const Matrix4 worldTransform = decal->getMatrix() * scaleAndOffset;
const Matrix4 worldNoScaleTransform = decal->getMatrixNoScale() * scaleAndOffset;
PerObjectBuffer::update(perObjectParamBuffer, worldTransform, worldNoScaleTransform, 0);
const Transform& tfrm = decal->getTransform();
const Matrix4 view = Matrix4::view(tfrm.getPosition(), tfrm.getRotation());
const Matrix4 proj = Matrix4::projectionOrthographic(-extent.x, extent.x, extent.y, -extent.y, 0.0f,
decal->getMaxDistance());
const Matrix4 worldToDecal = proj * view;
const Vector3 decalNormal = -decal->getTransform().getRotation().zAxis();
const float normalTolerance = -0.05f;
float flipDerivatives = 1.0f;
const RenderAPIInfo& rapiInfo = RenderAPI::instance().getAPIInfo();
if(rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp))
flipDerivatives = -1.0f;
gDecalParamDef.gWorldToDecal.set(decalParamBuffer, worldToDecal);
gDecalParamDef.gDecalNormal.set(decalParamBuffer, decalNormal);
gDecalParamDef.gNormalTolerance.set(decalParamBuffer, normalTolerance);
gDecalParamDef.gFlipDerivatives.set(decalParamBuffer, flipDerivatives);
gDecalParamDef.gLayerMask.set(decalParamBuffer, (INT32)decal->getLayerMask());
}
void RendererDecal::updatePerCallBuffer(const Matrix4& viewProj, bool flush) const
{
const Matrix4 worldViewProjMatrix = viewProj * decal->getMatrix();
gPerCallParamDef.gMatWorldViewProj.set(perCallParamBuffer, worldViewProjMatrix);
if(flush)
perCallParamBuffer->flushToGPU();
}
}}
|
#include <occa/lang/attribute.hpp>
#include <occa/lang/expr.hpp>
#include <occa/lang/statement.hpp>
#include <occa/lang/variable.hpp>
namespace occa {
namespace lang {
//---[ Variable ]-------------------
variable_t::variable_t() :
vartype(),
source(new identifierToken(filePosition(), "")) {}
variable_t::variable_t(const vartype_t &vartype_,
const std::string &name_) :
vartype(vartype_),
source(new identifierToken(fileOrigin(), name_)) {}
variable_t::variable_t(const vartype_t &vartype_,
identifierToken *source_) :
vartype(vartype_),
source((identifierToken*) token_t::clone(source_)) {}
variable_t::variable_t(const variable_t &other) :
vartype(other.vartype),
source((identifierToken*) token_t::clone(other.source)),
attributes(other.attributes),
nameOverride(other.nameOverride) {}
variable_t& variable_t::operator = (const variable_t &other) {
if (this == &other) {
return *this;
}
vartype = other.vartype;
attributes = other.attributes;
nameOverride = other.nameOverride;
if (source != other.source) {
delete source;
source = (identifierToken*) token_t::clone(other.source);
}
return *this;
}
variable_t::~variable_t() {
delete source;
source = NULL;
}
bool variable_t::isNamed() const {
return source->value.size();
}
std::string& variable_t::name() {
if (!nameOverride.size() && source) {
return source->value;
}
return nameOverride;
}
const std::string& variable_t::name() const {
if (!nameOverride.size() && source) {
return source->value;
}
return nameOverride;
}
void variable_t::setName(const std::string &name_) {
nameOverride = name_;
}
variable_t& variable_t::clone() const {
return *(new variable_t(*this));
}
bool variable_t::operator == (const variable_t &other) const {
if (this == &other) {
return true;
}
if (name() != other.name()) {
return false;
}
return vartype == other.vartype;
}
bool variable_t::hasAttribute(const std::string &attr) const {
return (attributes.find(attr) != attributes.end());
}
void variable_t::addAttribute(attributeToken_t &attr) {
const std::string attributeName = attr.name();
if (!hasAttribute(attributeName)) {
attributes[attributeName] = attr;
}
}
// Qualifiers
bool variable_t::has(const qualifier_t &qualifier) const {
return vartype.has(qualifier);
}
variable_t& variable_t::operator += (const qualifier_t &qualifier) {
vartype += qualifier;
return *this;
}
variable_t& variable_t::operator -= (const qualifier_t &qualifier) {
vartype -= qualifier;
return *this;
}
variable_t& variable_t::operator += (const qualifiers_t &qualifiers) {
vartype += qualifiers;
return *this;
}
void variable_t::add(const fileOrigin &origin,
const qualifier_t &qualifier) {
vartype.add(origin, qualifier);
}
void variable_t::add(const qualifierWithSource &qualifier) {
vartype.add(qualifier);
}
void variable_t::add(const int index,
const fileOrigin &origin,
const qualifier_t &qualifier) {
vartype.add(index, origin, qualifier);
}
void variable_t::add(const int index,
const qualifierWithSource &qualifier) {
vartype.add(index, qualifier);
}
// Pointers
variable_t& variable_t::operator += (const pointer_t &pointer) {
vartype += pointer;
return *this;
}
variable_t& variable_t::operator += (const pointerVector &pointers) {
vartype += pointers;
return *this;
}
variable_t& variable_t::operator += (const array_t &array) {
vartype += array;
return *this;
}
variable_t& variable_t::operator += (const arrayVector &arrays) {
vartype += arrays;
return *this;
}
dtype_t variable_t::dtype() const {
return vartype.dtype();
}
void variable_t::debugPrint() const {
printer pout(io::stderr);
pout << "Declaration:\n";
printDeclaration(pout);
pout << "\nExtra:\n";
printExtraDeclaration(pout);
pout << "\nEnd\n";
}
void variable_t::printDeclaration(printer &pout,
const vartypePrintType_t printType) const {
vartype.printDeclaration(pout, name(), printType);
}
void variable_t::printExtraDeclaration(printer &pout) const {
vartype.printExtraDeclaration(pout, name());
}
void variable_t::printWarning(const std::string &message) const {
source->printWarning(message);
}
void variable_t::printError(const std::string &message) const {
source->printError(message);
}
printer& operator << (printer &pout,
const variable_t &var) {
pout << var.name();
return pout;
}
//==================================
//---[ Variable Declaration ]-------
variableDeclaration::variableDeclaration() :
varNode(NULL),
value(NULL) {}
variableDeclaration::variableDeclaration(variable_t &variable_,
exprNode *value_) :
varNode(new variableNode(variable_.source,
variable_)),
value(value_) {}
variableDeclaration::variableDeclaration(variable_t &variable_,
exprNode &value_) :
varNode(new variableNode(variable_.source,
variable_)),
value(&value_) {}
variableDeclaration::variableDeclaration(const variableDeclaration &other) :
varNode(NULL),
value(NULL) {
*this = other;
}
variableDeclaration& variableDeclaration::operator = (const variableDeclaration &other) {
varNode = (variableNode*) exprNode::clone(other.varNode);
value = exprNode::clone(other.value);
return *this;
}
variableDeclaration::~variableDeclaration() {
clear();
}
variableDeclaration variableDeclaration::clone() const {
return variableDeclaration(varNode->value.clone(),
exprNode::clone(value));
}
bool variableDeclaration::hasVariable() const {
return varNode;
}
bool variableDeclaration::hasValue() const {
return value;
}
variable_t& variableDeclaration::variable() {
return varNode->value;
}
const variable_t& variableDeclaration::variable() const {
return varNode->value;
}
void variableDeclaration::clear() {
delete varNode;
delete value;
varNode = NULL;
value = NULL;
}
void variableDeclaration::setVariable(variableNode *newVarNode) {
// No need to update anything
if (varNode == newVarNode) {
return;
}
delete varNode;
varNode = newVarNode;
}
void variableDeclaration::setVariable(variable_t &variable_) {
// No need to update anything
if (varNode && &(varNode->value) == &variable_) {
return;
}
delete varNode;
varNode = new variableNode(variable_.source,
variable_);
}
void variableDeclaration::setValue(exprNode *newValue) {
// No need to update anything
if (value == newValue) {
return;
}
delete value;
value = newValue;
}
void variableDeclaration::debugPrint() const {
printer pout(io::stderr);
pout << "Declaration:\n";
print(pout, true);
pout << "\nExtra:\n";
printAsExtra(pout);
pout << "\nEnd\n";
}
void variableDeclaration::print(printer &pout,
const bool typeDeclared) const {
const vartypePrintType_t printType = (
typeDeclared
? vartypePrintType_t::typeDeclaration
: vartypePrintType_t::type
);
variable().printDeclaration(pout, printType);
if (value) {
pout << " = " << *value;
}
}
void variableDeclaration::printAsExtra(printer &pout) const {
variable().printExtraDeclaration(pout);
if (value) {
pout << " = " << *value;
}
}
void variableDeclaration::printWarning(const std::string &message) const {
variable().printWarning(message);
}
void variableDeclaration::printError(const std::string &message) const {
variable().printError(message);
}
//==================================
}
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: Polyglot.LocalizedTextComponent`1
#include "Polyglot/LocalizedTextComponent_1.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: TMPro
namespace TMPro {
// Forward declaring type: TextMeshPro
class TextMeshPro;
// Forward declaring type: TextAlignmentOptions
struct TextAlignmentOptions;
}
// Forward declaring namespace: Polyglot
namespace Polyglot {
// Skipping declaration: LanguageDirection because it is already included!
}
// Completed forward declares
// Type namespace: Polyglot
namespace Polyglot {
// WARNING Size may be invalid!
// Autogenerated type: Polyglot.LocalizedTextMeshPro
// [AddComponentMenu] Offset: DFA420
// [RequireComponent] Offset: DFA420
class LocalizedTextMeshPro : public Polyglot::LocalizedTextComponent_1<TMPro::TextMeshPro*> {
public:
// Creating value type constructor for type: LocalizedTextMeshPro
LocalizedTextMeshPro() noexcept {}
// protected System.Void SetText(TMPro.TextMeshPro text, System.String value)
// Offset: 0x2336EF0
void SetText(TMPro::TextMeshPro* text, ::Il2CppString* value);
// protected System.Void UpdateAlignment(TMPro.TextMeshPro text, Polyglot.LanguageDirection direction)
// Offset: 0x2336F10
void UpdateAlignment(TMPro::TextMeshPro* text, Polyglot::LanguageDirection direction);
// private System.Boolean IsOppositeDirection(TMPro.TextAlignmentOptions alignment, Polyglot.LanguageDirection direction)
// Offset: 0x2336FE8
bool IsOppositeDirection(TMPro::TextAlignmentOptions alignment, Polyglot::LanguageDirection direction);
// private System.Boolean IsAlignmentRight(TMPro.TextAlignmentOptions alignment)
// Offset: 0x2337040
bool IsAlignmentRight(TMPro::TextAlignmentOptions alignment);
// private System.Boolean IsAlignmentLeft(TMPro.TextAlignmentOptions alignment)
// Offset: 0x2337068
bool IsAlignmentLeft(TMPro::TextAlignmentOptions alignment);
// public System.Void .ctor()
// Offset: 0x2337090
// Implemented from: Polyglot.LocalizedTextComponent`1
// Base method: System.Void LocalizedTextComponent_1::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LocalizedTextMeshPro* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("Polyglot::LocalizedTextMeshPro::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LocalizedTextMeshPro*, creationType>()));
}
}; // Polyglot.LocalizedTextMeshPro
}
DEFINE_IL2CPP_ARG_TYPE(Polyglot::LocalizedTextMeshPro*, "Polyglot", "LocalizedTextMeshPro");
|
/**
* Copyright (C) 2015 MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kQuery
#include "mongo/platform/basic.h"
#include "mongo/db/pipeline/document_source_sample_from_random_cursor.h"
#include <boost/math/distributions/beta.hpp>
#include "mongo/db/client.h"
#include "mongo/db/pipeline/document.h"
#include "mongo/db/pipeline/expression.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/value.h"
#include "mongo/util/log.h"
namespace mongo {
using boost::intrusive_ptr;
DocumentSourceSampleFromRandomCursor::DocumentSourceSampleFromRandomCursor(
const intrusive_ptr<ExpressionContext>& pExpCtx,
long long size,
std::string idField,
long long nDocsInCollection)
: DocumentSource(pExpCtx),
_size(size),
_idField(std::move(idField)),
_seenDocs(pExpCtx->getValueComparator().makeUnorderedValueSet()),
_nDocsInColl(nDocsInCollection) {}
const char* DocumentSourceSampleFromRandomCursor::getSourceName() const {
return "$sampleFromRandomCursor";
}
namespace {
/**
* Select a random value drawn according to the distribution Beta(alpha=1, beta=N). The kth smallest
* value of a sample of size N from a Uniform(0, 1) distribution has a Beta(k, N + 1 - k)
* distribution, so the return value represents the smallest value from such a sample. This is also
* the expected distance between the values drawn from a uniform distribution, which is how it is
* being used here.
*/
double smallestFromSampleOfUniform(PseudoRandom* prng, size_t N) {
boost::math::beta_distribution<double> betaDist(1.0, static_cast<double>(N));
double p = prng->nextCanonicalDouble();
return boost::math::quantile(betaDist, p);
}
} // namespace
DocumentSource::GetNextResult DocumentSourceSampleFromRandomCursor::getNext() {
pExpCtx->checkForInterrupt();
if (_seenDocs.size() >= static_cast<size_t>(_size))
return GetNextResult::makeEOF();
auto nextResult = getNextNonDuplicateDocument();
if (!nextResult.isAdvanced()) {
return nextResult;
}
// Assign it a random value to enable merging by random value, attempting to avoid bias in that
// process.
auto& prng = pExpCtx->opCtx->getClient()->getPrng();
_randMetaFieldVal -= smallestFromSampleOfUniform(&prng, _nDocsInColl);
MutableDocument md(nextResult.releaseDocument());
md.setRandMetaField(_randMetaFieldVal);
return md.freeze();
}
DocumentSource::GetNextResult DocumentSourceSampleFromRandomCursor::getNextNonDuplicateDocument() {
// We may get duplicate documents back from the random cursor, and should not return duplicate
// documents, so keep trying until we get a new one.
const int kMaxAttempts = 100;
for (int i = 0; i < kMaxAttempts; ++i) {
auto nextInput = pSource->getNext();
switch (nextInput.getStatus()) {
case GetNextResult::ReturnStatus::kAdvanced: {
auto idField = nextInput.getDocument()[_idField];
uassert(28793,
str::stream()
<< "The optimized $sample stage requires all documents have a "
<< _idField
<< " field in order to de-duplicate results, but encountered a "
"document without a "
<< _idField
<< " field: "
<< nextInput.getDocument().toString(),
!idField.missing());
if (_seenDocs.insert(std::move(idField)).second) {
return nextInput;
}
LOG(1) << "$sample encountered duplicate document: "
<< nextInput.getDocument().toString();
break; // Try again with the next document.
}
case GetNextResult::ReturnStatus::kPauseExecution: {
MONGO_UNREACHABLE; // Our input should be a random cursor, which should never
// result in kPauseExecution.
}
case GetNextResult::ReturnStatus::kEOF: {
return nextInput;
}
}
}
uasserted(28799,
str::stream() << "$sample stage could not find a non-duplicate document after "
<< kMaxAttempts
<< " while using a random cursor. This is likely a "
"sporadic failure, please try again.");
}
Value DocumentSourceSampleFromRandomCursor::serialize(
boost::optional<ExplainOptions::Verbosity> explain) const {
return Value(DOC(getSourceName() << DOC("size" << _size)));
}
DocumentSource::GetDepsReturn DocumentSourceSampleFromRandomCursor::getDependencies(
DepsTracker* deps) const {
deps->fields.insert(_idField);
return SEE_NEXT;
}
intrusive_ptr<DocumentSourceSampleFromRandomCursor> DocumentSourceSampleFromRandomCursor::create(
const intrusive_ptr<ExpressionContext>& expCtx,
long long size,
std::string idField,
long long nDocsInCollection) {
intrusive_ptr<DocumentSourceSampleFromRandomCursor> source(
new DocumentSourceSampleFromRandomCursor(expCtx, size, idField, nDocsInCollection));
return source;
}
} // mongo
|
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Map.h"
#include "Entity_Book.h"
#include "j1Input.h"
#include "j1Window.h"
#include "j1Collision.h"
#include "j1Render.h"
#include "j1Entitites.h"
#include "j1Scene.h"
#include "j1Gui.h"
#include "j1FadeToBlack.h"
#include "GUI_Image.h"
#include "Entity_Player.h"
#include "Entity_Gaara.h"
Entity_Book::Entity_Book(int x, int y) : Entity(x, y)
{
idle.PushBack({2,13,28,29});
idle.PushBack({ 0,0,0,0});
idle.speed = 0.05f;
idle.loop = true;
animation = &idle;
}
Entity_Book::~Entity_Book()
{
App->tex->UnLoad(sprites);
}
void Entity_Book::Update(float dt)
{
if (firstUpdate == true) {
sprites = App->tex->Load("textures/Objects.png");
collider = App->collision->AddCollider({ 0, 0, 28, 25 }, COLLIDER_TYPE::COLLIDER_POWER_UP, App->entities);
firstUpdate = false;
}
}
void Entity_Book::OnCollision(Collider* collider)
{
if (collider->type == COLLIDER_TYPE::COLLIDER_PLAYER) {
LOG("COLLISION");
if (App->entities->player != nullptr)
{
App->entities->player->can_tp = true;
}
else if (App->entities->gaara != nullptr)
{
App->entities->gaara->can_tp = true;
}
is_caught = true;
delete_entity = true;
UpdateBookUI(is_caught);
}
}
bool Entity_Book::Load(pugi::xml_node& data)
{
if (App->entities->player != nullptr) {
App->entities->player->can_tp = data.child("book").attribute("caught").as_bool();
position.x = data.child("position").attribute("x").as_int();
position.y = data.child("position").attribute("y").as_int();
}
return true;
}
bool Entity_Book::Save(pugi::xml_node& data)const
{
if (App->entities->player != nullptr) {
data.append_child("book").append_attribute("caught") = App->entities->player->can_tp;
}
else if (App->entities->gaara != nullptr)
{
data.append_child("book").append_attribute("caught") = App->entities->gaara->can_tp;
}
data.append_child("position").append_attribute("x") = position.x;
data.child("position").append_attribute("y") = position.y;
return true;
}
void Entity_Book::UpdateBookUI(bool book_caught)
{
if(book_caught)
App->scene->book_caught_ui = App->gui->AddImage(200, 20, &App->scene->book_caught_rect, nullptr,nullptr, nullptr);
if(!book_caught)
App->scene->book_caught_ui = App->gui->AddImage(200, 20, &App->scene->book_not_caught_rect, nullptr,nullptr, nullptr);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* Copyright (c) 2017 by Contributors
* \file requantize.cc
* \brief
*/
#include "./requantize-inl.h"
#include "./quantize-inl.h"
#if MXNET_USE_ONEDNN == 1
#include "./mkldnn/mkldnn_requantize-inl.h"
#endif
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(RequantizeParam);
bool RequantizeStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
*dispatch_mode = DispatchMode::kFCompute;
#if MXNET_USE_ONEDNN == 1
if (dev_mask == mshadow::cpu::kDevMask) {
*dispatch_mode = DispatchMode::kFComputeEx;
}
#endif
(*out_attrs)[0] = kDefaultStorage;
(*out_attrs)[1] = kDefaultStorage;
(*out_attrs)[2] = kDefaultStorage;
return true;
}
NNVM_REGISTER_OP(_contrib_requantize)
.add_alias("_npx_requantize")
.describe(R"code(Given data that is quantized in int32 and the corresponding thresholds,
requantize the data into int8 using min and max thresholds either calculated at runtime
or from calibration. It's highly recommended to pre-calucate the min and max thresholds
through calibration since it is able to save the runtime of the operator and improve the
inference accuracy.
.. Note::
This operator only supports forward propogation. DO NOT use it in training.)code" ADD_FILELINE)
.set_attr_parser(ParamParser<RequantizeParam>)
.set_num_inputs(3)
.set_num_outputs(3)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"data", "min_range", "max_range"};
})
.set_attr<mxnet::FInferShape>("FInferShape", QuantizeShape)
.set_attr<nnvm::FInferType>("FInferType", RequantizeType)
.set_attr<FInferStorageType>("FInferStorageType", RequantizeStorageType)
// TODO(Xinyu): a temp solution to enable GluonCV INT8 flow,
// will be reverted after the improvement of CachedOP is done.
.set_attr<nnvm::FGradient>("FGradient", MakeZeroGradNodes)
#if MXNET_USE_ONEDNN == 1
.set_attr<bool>("TIsMKLDNN", true)
.set_attr<FComputeEx>("FComputeEx<cpu>", MKLDNNRequantizeForward)
#else
.set_attr<FCompute>("FCompute<cpu>", RequantizeForward<cpu>)
#endif
.set_attr<FNeedCalibrateInput>("FNeedCalibrateInput", [](const NodeAttrs& attrs){
return std::vector<int>{0};
})
.set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& attrs) {
const RequantizeParam& param =
nnvm::get<RequantizeParam>(attrs.parsed);
if (param.min_calib_range.has_value() && param.max_calib_range.has_value()) {
return std::vector<ResourceRequest>();
} else {
return std::vector<ResourceRequest>(1, ResourceRequest::kTempSpace);
}
})
.add_argument("data", "NDArray-or-Symbol", "A ndarray/symbol of type `int32`")
.add_argument("min_range", "NDArray-or-Symbol", "The original minimum scalar value "
"in the form of float32 used for quantizing data into int32.")
.add_argument("max_range", "NDArray-or-Symbol", "The original maximum scalar value "
"in the form of float32 used for quantizing data into int32.")
.add_arguments(RequantizeParam::__FIELDS__());
} // namespace op
} // namespace mxnet
|
//
// Copyright (c) 2011, Willow Garage, 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 Willow Garage, Inc. 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.
//
#include <gtest/gtest.h>
#include <ecto/ecto.hpp>
using namespace ecto;
TEST(SporeTest, LifeTime)
{
{
spore<double> d = make_tendril<double>();
EXPECT_TRUE(d);
}
{
spore<double> d;
EXPECT_FALSE(d);
EXPECT_ANY_THROW(*d);
d = make_tendril<double>();
EXPECT_TRUE(d);
*d = 3.555;
EXPECT_EQ(*d, 3.555);
// reassign
d = make_tendril<double>();
ASSERT_NE(*d, 3.555);
EXPECT_ANY_THROW(d = make_tendril<std::string>());
}
}
TEST(SporeTest, NoDefault)
{
tendril_ptr p = make_tendril<double>();
spore<double> d = p; //p has to stay in scope...
EXPECT_FALSE(d.user_supplied());
EXPECT_FALSE(d.dirty());
EXPECT_FALSE(d.has_default());
*d = 3.14;
EXPECT_FALSE(d.dirty());
EXPECT_FALSE(d.user_supplied());
EXPECT_FALSE(d.has_default());
d.set_default_val(10);
EXPECT_TRUE(d.has_default());
}
TEST(SporeTest, Default)
{
tendril_ptr p = make_tendril<double>();
EXPECT_FALSE(p->dirty());
spore<double> d = p; //p has to stay in scope...
EXPECT_FALSE(d.dirty());
d.set_default_val(1.41421356);
EXPECT_FALSE(d.user_supplied());
EXPECT_FALSE(d.dirty());
EXPECT_TRUE(d.has_default());
EXPECT_EQ(*d, 1.41421356);
EXPECT_FALSE(d.dirty());
d.notify();
EXPECT_FALSE(d.dirty());
*d = 3.14;
EXPECT_FALSE(d.dirty());
EXPECT_FALSE(d.user_supplied());
EXPECT_TRUE(d.has_default());
}
template<typename T>
struct cbs
{
cbs() : count(0), val(0) { }
void operator()(const T& new_val)
{
val = new_val;
count++;
}
int count;
T val;
};
TEST(SporeTest, Callbacks)
{
tendril_ptr p = make_tendril<double>();
spore<double> d = p; //p has to stay in scope...
d.set_default_val(1.41421356);
cbs<double> c;
d.set_callback(boost::ref(c));
d.notify();
EXPECT_EQ(c.count, 0);
EXPECT_EQ(c.val, 0);
*d = 3.14;
d.dirty(true); //dirtiness is explicit
d.notify();
EXPECT_EQ(c.count, 1);
EXPECT_EQ(c.val, 3.14);
*d = 5.55;
EXPECT_FALSE(d.dirty());
// callback didn't fire
EXPECT_EQ(c.count, 1);
EXPECT_EQ(c.val, 3.14);
d.notify();
// it didn't fire cause it aint dirty
EXPECT_EQ(c.count, 1);
EXPECT_EQ(c.val, 3.14);
d.dirty(true);
// still didn't fire... not notified
EXPECT_EQ(c.count, 1);
EXPECT_EQ(c.val, 3.14);
// notifed, and was dirty... now it fires
d.notify();
EXPECT_EQ(c.count, 2);
EXPECT_EQ(c.val, 5.55);
EXPECT_FALSE(d.dirty());
}
TEST(SporeTest, Expressions)
{
tendril_ptr ta = make_tendril<double>(),
tb = make_tendril<double>(),
tc = make_tendril<double>()
;
spore<double> a(ta), b(tb), c(tc);
*a = 13.;
EXPECT_EQ(*a, 13.);
*b = 14.;
EXPECT_EQ(*b, 14.);
*c = 15.;
EXPECT_EQ(*c, 15.);
*a = (*b + *c);
EXPECT_EQ(*a, 29.);
EXPECT_EQ(*b, 14.);
EXPECT_EQ(*c, 15.);
}
struct SporeCellConst
{
static void declare_params(tendrils&p)
{
p.declare<std::string>("foo");
}
static void declare_io(const tendrils& p, tendrils& i, tendrils& o)
{
i.declare<double>("d");
o.declare<double>("out");
}
void configure(const tendrils& p,const tendrils& i,const tendrils& o)
{
foo = p["foo"];
d = i["d"];
out = o["out"];
//shouldn't compile.
//i.declare<double>("d","a new d.");
}
int process(const tendrils& i,const tendrils& o)
{
*out = *d;
// out << d; //fail to compile
// o["out"] << d;//fail to compile
o["out"] << *d;
o["out"] << 3.4;
o["out"] << i["d"];
// o["out"] = 2.0;//fail to compile.
// tendril_ptr tp = out.get();//fail to compile
//out >> d; //should fail to compile
//i["d"] >> out; //should fail at compile time. FIXME this doesn't fail but should not compile.
i["d"] >> *out; //should not fail.
return ecto::OK;
}
spore<double> d,out;
spore<std::string> foo;
};
TEST(SporeTest, Semantics)
{
cell::ptr c1(new cell_<SporeCellConst>);
c1->declare_params();
c1->declare_io();
c1->configure();
c1->process();
}
TEST(SporeTest, DefaultConstruction)
{
spore<double> d;
//post conditions
EXPECT_FALSE(d);
EXPECT_TRUE(!d);
}
TEST(SporeTest, CopyConstructionDefault)
{
spore<double> d1;
spore<double> d2(d1);
//post condition
EXPECT_FALSE(d2);
spore<double> d3 = d1;
//post condition
EXPECT_FALSE(d3);
d1 = make_tendril<double>();
EXPECT_TRUE(d1);
EXPECT_FALSE(d3);
EXPECT_FALSE(d2);
}
TEST(SporeTest, CopyConstructionValue)
{
spore<double> d1( make_tendril<double>());
spore<double> d2(d1);
//post condition
EXPECT_TRUE(d2);
spore<double> d3 = d1;
//post condition
EXPECT_TRUE(d3);
//all point to the same thing here.
*d1 = 3.14;
EXPECT_EQ(*d1,*d2);
EXPECT_EQ(*d2,*d3);
//assign a null spore to d2, noone else should be affected.
d2 = spore<double>();
EXPECT_TRUE(d1);
EXPECT_TRUE(d3);
EXPECT_FALSE(d2);
}
TEST(SporeTest, ImplicitConstructor)
{
tendril_ptr d = make_tendril<double>();
tendril_ptr s = make_tendril<std::string>();
spore<double> dd;
spore<std::string> ss;
dd = d;
ss = s;
EXPECT_THROW(dd = s,ecto::except::TypeMismatch);
EXPECT_THROW(ss = d,ecto::except::TypeMismatch);
}
TEST(SporeTest, NullAssign)
{
spore<std::string> ss;
EXPECT_THROW(
ss = tendril_ptr();
,
ecto::except::NullTendril);
}
|
/***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* SeisComP Public License for more details. *
***************************************************************************/
#include <seiscomp3/math/filter/iirfilter.h>
namespace Seiscomp
{
namespace Math
{
namespace Filtering
{
template <typename T>
IIRFilter<T>::IIRFilter() {
}
template <typename T>
IIRFilter<T>::IIRFilter(int na, int nb, const double *a, const double *b) {
setCoefficients(na, nb, a, b);
}
template <typename T>
IIRFilter<T>::~IIRFilter() {
}
template <typename T>
void IIRFilter<T>::setCoefficients(int na, int nb, const double *a, const double *b) {
_na = na;
_nb = nb;
_a.assign(a, a+na);
_b.assign(b, b+nb);
int n = std::max<int>(na, nb);
_lastValues.resize(n, 0);
}
template <typename T>
void IIRFilter<T>::setSamplingFrequency(double fsamp) {}
template <typename T>
int IIRFilter<T>::setParameters(int n, const double *params) {
if ( n < 2 ) return 2;
// na is first parameter
int na = (int)params[0];
int nb = 0;
const double *a = NULL;
const double *b = NULL;
if ( na ) {
// The a coefficients are stored directly after the
// first parameters
a = params + 1;
// At least parameter nb is missing
if ( n < na+2 )
return na+2;
nb = (int)params[na+1];
if ( n < na+nb+2 )
return na+nb+2;
b = params + na+2;
}
else {
nb = (int)params[1];
// b coefficients are missing or not complete
if ( n < nb+2 )
return nb+2;
b = params + 2;
}
setCoefficients(na, nb, a, b);
return n;
}
template <typename T>
void IIRFilter<T>::apply(int n, T *inout) {
/*
// TODO: Store lastValues
T sum = 0;
for ( int i = 0; i < n; ++i ) {
for ( int k = 0; k < _na; ++k )
sum += _a[k] * inout[i-k];
for ( int k = 0; k < _nb; ++k )
sum += _b[k] * inout[i-k];
inout[i] = sum;
}
*/
}
template <typename T>
InPlaceFilter<T>* IIRFilter<T>::clone() const {
return new IIRFilter<T>(_na, _nb, &_a[0], &_b[0]);
}
INSTANTIATE_INPLACE_FILTER(IIRFilter, SC_SYSTEM_CORE_API);
}
}
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkHierarchicalGraphView.cxx
-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkHierarchicalGraphView.h"
#include "vtkDataObject.h"
#include "vtkDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkRenderedHierarchyRepresentation.h"
#include "vtkTree.h"
#include "vtkTrivialProducer.h"
vtkStandardNewMacro(vtkHierarchicalGraphView);
//------------------------------------------------------------------------------
vtkHierarchicalGraphView::vtkHierarchicalGraphView() = default;
//------------------------------------------------------------------------------
vtkHierarchicalGraphView::~vtkHierarchicalGraphView() = default;
//------------------------------------------------------------------------------
vtkRenderedGraphRepresentation* vtkHierarchicalGraphView::GetGraphRepresentation()
{
vtkRenderedHierarchyRepresentation* graphRep = nullptr;
for (int i = 0; i < this->GetNumberOfRepresentations(); ++i)
{
vtkDataRepresentation* rep = this->GetRepresentation(i);
graphRep = vtkRenderedHierarchyRepresentation::SafeDownCast(rep);
if (graphRep)
{
break;
}
}
if (!graphRep)
{
vtkSmartPointer<vtkTree> t = vtkSmartPointer<vtkTree>::New();
graphRep =
vtkRenderedHierarchyRepresentation::SafeDownCast(this->AddRepresentationFromInput(t));
vtkSmartPointer<vtkDirectedGraph> g = vtkSmartPointer<vtkDirectedGraph>::New();
graphRep->SetInputData(1, g);
}
return graphRep;
}
//------------------------------------------------------------------------------
vtkRenderedHierarchyRepresentation* vtkHierarchicalGraphView::GetHierarchyRepresentation()
{
return vtkRenderedHierarchyRepresentation::SafeDownCast(this->GetGraphRepresentation());
}
//------------------------------------------------------------------------------
vtkDataRepresentation* vtkHierarchicalGraphView::CreateDefaultRepresentation(
vtkAlgorithmOutput* port)
{
vtkRenderedHierarchyRepresentation* rep = vtkRenderedHierarchyRepresentation::New();
rep->SetInputConnection(port);
return rep;
}
//------------------------------------------------------------------------------
vtkDataRepresentation* vtkHierarchicalGraphView::SetHierarchyFromInputConnection(
vtkAlgorithmOutput* conn)
{
this->GetHierarchyRepresentation()->SetInputConnection(0, conn);
return this->GetHierarchyRepresentation();
}
//------------------------------------------------------------------------------
vtkDataRepresentation* vtkHierarchicalGraphView::SetHierarchyFromInput(vtkDataObject* input)
{
vtkSmartPointer<vtkTrivialProducer> tp = vtkSmartPointer<vtkTrivialProducer>::New();
tp->SetOutput(input);
return this->SetHierarchyFromInputConnection(tp->GetOutputPort());
}
//------------------------------------------------------------------------------
vtkDataRepresentation* vtkHierarchicalGraphView::SetGraphFromInputConnection(
vtkAlgorithmOutput* conn)
{
this->GetHierarchyRepresentation()->SetInputConnection(1, conn);
return this->GetHierarchyRepresentation();
}
//------------------------------------------------------------------------------
vtkDataRepresentation* vtkHierarchicalGraphView::SetGraphFromInput(vtkDataObject* input)
{
vtkSmartPointer<vtkTrivialProducer> tp = vtkSmartPointer<vtkTrivialProducer>::New();
tp->SetOutput(input);
return this->SetGraphFromInputConnection(tp->GetOutputPort());
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetGraphEdgeLabelArrayName(const char* name)
{
this->GetHierarchyRepresentation()->SetGraphEdgeLabelArrayName(name);
}
//------------------------------------------------------------------------------
const char* vtkHierarchicalGraphView::GetGraphEdgeLabelArrayName()
{
return this->GetHierarchyRepresentation()->GetGraphEdgeLabelArrayName();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetGraphEdgeLabelVisibility(bool vis)
{
this->GetHierarchyRepresentation()->SetGraphEdgeLabelVisibility(vis);
}
//------------------------------------------------------------------------------
bool vtkHierarchicalGraphView::GetGraphEdgeLabelVisibility()
{
return this->GetHierarchyRepresentation()->GetGraphEdgeLabelVisibility();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetGraphEdgeColorArrayName(const char* name)
{
this->GetHierarchyRepresentation()->SetGraphEdgeColorArrayName(name);
}
//------------------------------------------------------------------------------
const char* vtkHierarchicalGraphView::GetGraphEdgeColorArrayName()
{
return this->GetHierarchyRepresentation()->GetGraphEdgeColorArrayName();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetGraphEdgeColorToSplineFraction()
{
this->GetHierarchyRepresentation()->SetGraphEdgeColorToSplineFraction();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetColorGraphEdgesByArray(bool vis)
{
this->GetHierarchyRepresentation()->SetColorGraphEdgesByArray(vis);
}
//------------------------------------------------------------------------------
bool vtkHierarchicalGraphView::GetColorGraphEdgesByArray()
{
return this->GetHierarchyRepresentation()->GetColorGraphEdgesByArray();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetGraphVisibility(bool vis)
{
this->GetHierarchyRepresentation()->SetGraphVisibility(vis);
}
//------------------------------------------------------------------------------
bool vtkHierarchicalGraphView::GetGraphVisibility()
{
return this->GetHierarchyRepresentation()->GetGraphVisibility();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetBundlingStrength(double strength)
{
this->GetHierarchyRepresentation()->SetBundlingStrength(strength);
}
//------------------------------------------------------------------------------
double vtkHierarchicalGraphView::GetBundlingStrength()
{
return this->GetHierarchyRepresentation()->GetBundlingStrength();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::SetGraphEdgeLabelFontSize(const int size)
{
this->GetHierarchyRepresentation()->SetGraphEdgeLabelFontSize(size);
}
//------------------------------------------------------------------------------
int vtkHierarchicalGraphView::GetGraphEdgeLabelFontSize()
{
return this->GetHierarchyRepresentation()->GetGraphEdgeLabelFontSize();
}
//------------------------------------------------------------------------------
void vtkHierarchicalGraphView::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
|
// Copyright (c) 2020 Bita Hasheminezhad
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <phylanx/phylanx.hpp>
#include <hpx/hpx_main.hpp>
#include <hpx/modules/testing.hpp>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
phylanx::execution_tree::primitive_argument_type compile_and_run(
std::string const& codestr)
{
phylanx::execution_tree::compiler::function_list snippets;
phylanx::execution_tree::compiler::environment env =
phylanx::execution_tree::compiler::default_environment();
auto const& code = phylanx::execution_tree::compile(codestr, snippets, env);
return code.run().arg_;
}
void test_operation(char const* code, char const* expectedstr)
{
auto result = compile_and_run(code);
auto expected = compile_and_run(expectedstr);
HPX_TEST_EQ(result, expected);
}
int main(int argc, char* argv[])
{
test_operation(R"(astype([1, 0, 1], "bool"))", "[true, false, true]");
test_operation(R"(block(
define(a, [1, 0, 1]),
astype(a, "bool")
))",
"[true, false, true]");
return hpx::util::report_errors();
}
|
// GROUP: X
// ID: XXXXXXXX
// Assign: 12
// Assign: KnapsackBT
// UVA: 10130
// Name: XX STUDENT FULL NAME
// UVA Username: UVA username of student
#include <bits/stdc++.h>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<class Type>
void Merge(Type* a, int n, bool (*IsBefore)(Type& a, Type& b))
{
int mid = (n+1)/2;
int i = 0, j = mid;
int k = 0;
Type* arr = new Type[n];
while(i < mid || j < n)
{
if(i >= mid && j < n)
{
arr[k++] = a[j++];
}
else if ((j >= n && i < mid) || IsBefore(a[i], a[j]))
{
arr[k++] = a[i++];
}
else
{
arr[k++] = a[j++];
}
}
for(int l = 0 ; l < n ; l++)
{
a[l] = arr[l];
}
delete[] arr;
}
template<class Type>
void MergeSort(Type* a, int n, bool (*IsBefore)(Type& a, Type& b))
{
if(n<=1)
{
return;
}
int mid = (n+1)/2;
MergeSort<Type>(a,mid,IsBefore);
MergeSort<Type>(a+mid,n-mid,IsBefore);
Merge<Type>(a,n,IsBefore);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct Obj
{
int v;
int w;
};
int n; // number of objects (input)
Obj a[1000]; // objects (input)
////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool IsBefore(Obj& a, Obj& b)// return true if unit value of a is greater than unit value of b
{
return (float)a.v/a.w > (float)b.v/b.w;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
int best_val; // the best total value found until now
int Bound(int i, int w) // upper bound on the total value of items [i..n-1] that can fit in w
{
float val = 0;
int weight = 0;
for(int j = i ; j < n ; j++)
{
val += a[j].v*((float)(min(a[j].w, w - weight))/a[j].w);
weight += min(a[j].w, w - weight);
}
return ceil(val);
}
void BackTrack(int i, int w, int cur_val) // starting from item i, remaining weight w, cur_value of objects[0..i-1]
{
if(i == n)
{
best_val = max(cur_val, best_val);
return;
}
if(cur_val + Bound(i, w) <= best_val)
{
return;
}
if(w >= a[i].w)
{
BackTrack(i+1, w - a[i].w, cur_val + a[i].v);
}
BackTrack(i+1, w, cur_val);
}
int ComputeKnapsack(int N, int W) // solve knapsack of N objects and W weight
{
best_val = 0;
MergeSort(a, N, IsBefore);
n = N;
BackTrack(0,W,0);
return best_val;
}
void Compute()
{
int T, N, G, W, TW;
cin >> T;
while(T--)
{
TW = 0;
cin >> N;
for(int i = 0; i < N; i++)
{
cin >> a[i].v >> a[i].w;
}
cin >> G;
for(int i = 0; i < G; i++)
{
cin >> W;
TW += ComputeKnapsack(N, W);
}
cout << TW << endl;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
//freopen("input_assign12_10130.txt", "r", stdin);
Compute();
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
/*************************************************************************/
/* android_support.cpp */
/*************************************************************************/
/* This file is part of: */
/* Valjang Engine */
/* http://Valjang.fr */
/*************************************************************************/
/* Copyright (c) 2007-2020 Valjang. */
/* Copyright (c) 2014-2020 Valjang Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "android_support.h"
#if defined(ANDROID_ENABLED)
#include <dlfcn.h> // dlopen, dlsym
#include <mono/utils/mono-dl-fallback.h>
#include <sys/system_properties.h>
#include <cstddef>
#if __ANDROID_API__ < 24
#include "thirdparty/misc/ifaddrs-android.h"
#else
#include <ifaddrs.h>
#endif
#include "core/os/os.h"
#include "core/ustring.h"
#include "platform/android/java_godot_wrapper.h"
#include "platform/android/os_android.h"
#include "platform/android/thread_jandroid.h"
#include "../../utils/path_utils.h"
#include "../../utils/string_utils.h"
#include "../gd_mono_cache.h"
#include "../gd_mono_marshal.h"
// Warning: JNI boilerplate ahead... continue at your own risk
namespace gdmono {
namespace android {
namespace support {
template <typename T>
struct ScopedLocalRef {
JNIEnv *env;
T local_ref;
_FORCE_INLINE_ T get() const { return local_ref; }
_FORCE_INLINE_ operator T() const { return local_ref; }
_FORCE_INLINE_ operator jvalue() const { return (jvalue)local_ref; }
_FORCE_INLINE_ operator bool() const { return local_ref != nullptr; }
_FORCE_INLINE_ bool operator==(std::nullptr_t) const {
return local_ref == nullptr;
}
_FORCE_INLINE_ bool operator!=(std::nullptr_t) const {
return local_ref != nullptr;
}
ScopedLocalRef(const ScopedLocalRef &) = delete;
ScopedLocalRef &operator=(const ScopedLocalRef &) = delete;
ScopedLocalRef(JNIEnv *p_env, T p_local_ref) :
env(p_env),
local_ref(p_local_ref) {
}
~ScopedLocalRef() {
if (local_ref) {
env->DeleteLocalRef(local_ref);
}
}
};
bool jni_exception_check(JNIEnv *p_env) {
if (p_env->ExceptionCheck()) {
// Print the exception to logcat
p_env->ExceptionDescribe();
p_env->ExceptionClear();
return true;
}
return false;
}
String app_native_lib_dir_cache;
String determine_app_native_lib_dir() {
JNIEnv *env = ThreadAndroid::get_env();
ScopedLocalRef<jclass> activityThreadClass(env, env->FindClass("android/app/ActivityThread"));
jmethodID currentActivityThread = env->GetStaticMethodID(activityThreadClass, "currentActivityThread", "()Landroid/app/ActivityThread;");
ScopedLocalRef<jobject> activityThread(env, env->CallStaticObjectMethod(activityThreadClass, currentActivityThread));
jmethodID getApplication = env->GetMethodID(activityThreadClass, "getApplication", "()Landroid/app/Application;");
ScopedLocalRef<jobject> ctx(env, env->CallObjectMethod(activityThread, getApplication));
jmethodID getApplicationInfo = env->GetMethodID(env->GetObjectClass(ctx), "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;");
ScopedLocalRef<jobject> applicationInfo(env, env->CallObjectMethod(ctx, getApplicationInfo));
jfieldID nativeLibraryDirField = env->GetFieldID(env->GetObjectClass(applicationInfo), "nativeLibraryDir", "Ljava/lang/String;");
ScopedLocalRef<jstring> nativeLibraryDir(env, (jstring)env->GetObjectField(applicationInfo, nativeLibraryDirField));
String result;
const char *const nativeLibraryDirUtf8 = env->GetStringUTFChars(nativeLibraryDir, nullptr);
if (nativeLibraryDirUtf8) {
result.parse_utf8(nativeLibraryDirUtf8);
env->ReleaseStringUTFChars(nativeLibraryDir, nativeLibraryDirUtf8);
}
return result;
}
String get_app_native_lib_dir() {
if (app_native_lib_dir_cache.empty())
app_native_lib_dir_cache = determine_app_native_lib_dir();
return app_native_lib_dir_cache;
}
int gd_mono_convert_dl_flags(int flags) {
// from mono's runtime-bootstrap.c
int lflags = flags & MONO_DL_LOCAL ? 0 : RTLD_GLOBAL;
if (flags & MONO_DL_LAZY)
lflags |= RTLD_LAZY;
else
lflags |= RTLD_NOW;
return lflags;
}
#ifndef GD_MONO_SO_NAME
#define GD_MONO_SO_NAME "libmonosgen-2.0.so"
#endif
const char *mono_so_name = GD_MONO_SO_NAME;
const char *godot_so_name = "libgodot_android.so";
void *mono_dl_handle = nullptr;
void *godot_dl_handle = nullptr;
void *try_dlopen(const String &p_so_path, int p_flags) {
if (!FileAccess::exists(p_so_path)) {
if (OS::get_singleton()->is_stdout_verbose())
OS::get_singleton()->print("Cannot find shared library: '%s'\n", p_so_path.utf8().get_data());
return nullptr;
}
int lflags = gd_mono_convert_dl_flags(p_flags);
void *handle = dlopen(p_so_path.utf8().get_data(), lflags);
if (!handle) {
if (OS::get_singleton()->is_stdout_verbose())
OS::get_singleton()->print("Failed to open shared library: '%s'. Error: '%s'\n", p_so_path.utf8().get_data(), dlerror());
return nullptr;
}
if (OS::get_singleton()->is_stdout_verbose())
OS::get_singleton()->print("Successfully loaded shared library: '%s'\n", p_so_path.utf8().get_data());
return handle;
}
void *gd_mono_android_dlopen(const char *p_name, int p_flags, char **r_err, void *p_user_data) {
if (p_name == nullptr) {
// __Internal
if (!mono_dl_handle) {
String app_native_lib_dir = get_app_native_lib_dir();
String so_path = path::join(app_native_lib_dir, mono_so_name);
mono_dl_handle = try_dlopen(so_path, p_flags);
}
return mono_dl_handle;
}
String name = String::utf8(p_name);
if (name.ends_with(".dll.so") || name.ends_with(".exe.so")) {
String app_native_lib_dir = get_app_native_lib_dir();
String orig_so_name = name.get_file();
String so_name = "lib-aot-" + orig_so_name;
String so_path = path::join(app_native_lib_dir, so_name);
return try_dlopen(so_path, p_flags);
}
return nullptr;
}
void *gd_mono_android_dlsym(void *p_handle, const char *p_name, char **r_err, void *p_user_data) {
void *sym_addr = dlsym(p_handle, p_name);
if (sym_addr)
return sym_addr;
if (p_handle == mono_dl_handle && godot_dl_handle) {
// Looking up for '__Internal' P/Invoke. We want to search in both the Mono and Godot shared libraries.
// This is needed to resolve the monodroid P/Invoke functions that are defined at the bottom of the file.
sym_addr = dlsym(godot_dl_handle, p_name);
if (sym_addr)
return sym_addr;
}
if (r_err)
*r_err = str_format_new("%s\n", dlerror());
return nullptr;
}
void *gd_mono_android_dlclose(void *p_handle, void *p_user_data) {
dlclose(p_handle);
// Not sure if this ever happens. Does Mono close the handle for the main module?
if (p_handle == mono_dl_handle)
mono_dl_handle = nullptr;
return nullptr;
}
int32_t build_version_sdk_int = 0;
int32_t get_build_version_sdk_int() {
// The JNI code is the equivalent of:
//
// android.os.Build.VERSION.SDK_INT
if (build_version_sdk_int == 0) {
JNIEnv *env = ThreadAndroid::get_env();
jclass versionClass = env->FindClass("android/os/Build$VERSION");
ERR_FAIL_NULL_V(versionClass, 0);
jfieldID sdkIntField = env->GetStaticFieldID(versionClass, "SDK_INT", "I");
ERR_FAIL_NULL_V(sdkIntField, 0);
build_version_sdk_int = (int32_t)env->GetStaticIntField(versionClass, sdkIntField);
}
return build_version_sdk_int;
}
jobject certStore = nullptr; // KeyStore
MonoBoolean _gd_mono_init_cert_store() {
// The JNI code is the equivalent of:
//
// try {
// certStoreLocal = KeyStore.getInstance("AndroidCAStore");
// certStoreLocal.load(null);
// certStore = certStoreLocal;
// return true;
// } catch (Exception e) {
// return false;
// }
JNIEnv *env = ThreadAndroid::get_env();
ScopedLocalRef<jclass> keyStoreClass(env, env->FindClass("java/security/KeyStore"));
jmethodID getInstance = env->GetStaticMethodID(keyStoreClass, "getInstance", "(Ljava/lang/String;)Ljava/security/KeyStore;");
jmethodID load = env->GetMethodID(keyStoreClass, "load", "(Ljava/security/KeyStore$LoadStoreParameter;)V");
ScopedLocalRef<jstring> androidCAStoreString(env, env->NewStringUTF("AndroidCAStore"));
ScopedLocalRef<jobject> certStoreLocal(env, env->CallStaticObjectMethod(keyStoreClass, getInstance, androidCAStoreString.get()));
if (jni_exception_check(env))
return 0;
env->CallVoidMethod(certStoreLocal, load, nullptr);
if (jni_exception_check(env))
return 0;
certStore = env->NewGlobalRef(certStoreLocal);
return 1;
}
MonoArray *_gd_mono_android_cert_store_lookup(MonoString *p_alias) {
// The JNI code is the equivalent of:
//
// Certificate certificate = certStore.getCertificate(alias);
// if (certificate == null)
// return null;
// return certificate.getEncoded();
MonoError mono_error;
char *alias_utf8 = mono_string_to_utf8_checked(p_alias, &mono_error);
if (!mono_error_ok(&mono_error)) {
ERR_PRINT(String() + "Failed to convert MonoString* to UTF-8: '" + mono_error_get_message(&mono_error) + "'.");
mono_error_cleanup(&mono_error);
return nullptr;
}
JNIEnv *env = ThreadAndroid::get_env();
ScopedLocalRef<jstring> js_alias(env, env->NewStringUTF(alias_utf8));
mono_free(alias_utf8);
ScopedLocalRef<jclass> keyStoreClass(env, env->FindClass("java/security/KeyStore"));
ERR_FAIL_NULL_V(keyStoreClass, nullptr);
ScopedLocalRef<jclass> certificateClass(env, env->FindClass("java/security/cert/Certificate"));
ERR_FAIL_NULL_V(certificateClass, nullptr);
jmethodID getCertificate = env->GetMethodID(keyStoreClass, "getCertificate", "(Ljava/lang/String;)Ljava/security/cert/Certificate;");
ERR_FAIL_NULL_V(getCertificate, nullptr);
jmethodID getEncoded = env->GetMethodID(certificateClass, "getEncoded", "()[B");
ERR_FAIL_NULL_V(getEncoded, nullptr);
ScopedLocalRef<jobject> certificate(env, env->CallObjectMethod(certStore, getCertificate, js_alias.get()));
if (!certificate)
return nullptr;
ScopedLocalRef<jbyteArray> encoded(env, (jbyteArray)env->CallObjectMethod(certificate, getEncoded));
jsize encodedLength = env->GetArrayLength(encoded);
MonoArray *encoded_ret = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), encodedLength);
uint8_t *dest = (uint8_t *)mono_array_addr(encoded_ret, uint8_t, 0);
env->GetByteArrayRegion(encoded, 0, encodedLength, reinterpret_cast<jbyte *>(dest));
return encoded_ret;
}
void register_internal_calls() {
mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_init_cert_store", (void *)_gd_mono_init_cert_store);
mono_add_internal_call("Android.Runtime.AndroidEnvironment::_gd_mono_android_cert_store_lookup", (void *)_gd_mono_android_cert_store_lookup);
}
void initialize() {
// We need to set this environment variable to make the monodroid BCL use btls instead of legacy as the default provider
OS::get_singleton()->set_environment("XA_TLS_PROVIDER", "btls");
mono_dl_fallback_register(gd_mono_android_dlopen, gd_mono_android_dlsym, gd_mono_android_dlclose, nullptr);
String app_native_lib_dir = get_app_native_lib_dir();
String so_path = path::join(app_native_lib_dir, godot_so_name);
godot_dl_handle = try_dlopen(so_path, gd_mono_convert_dl_flags(MONO_DL_LAZY));
}
void cleanup() {
// This is called after shutting down the Mono runtime
if (mono_dl_handle)
gd_mono_android_dlclose(mono_dl_handle, nullptr);
if (godot_dl_handle)
gd_mono_android_dlclose(godot_dl_handle, nullptr);
JNIEnv *env = ThreadAndroid::get_env();
if (certStore) {
env->DeleteGlobalRef(certStore);
certStore = nullptr;
}
}
} // namespace support
} // namespace android
} // namespace gdmono
using namespace gdmono::android::support;
// The following are P/Invoke functions required by the monodroid profile of the BCL.
// These are P/Invoke functions and not internal calls, hence why they use
// 'mono_bool' and 'const char*' instead of 'MonoBoolean' and 'MonoString*'.
#define GD_PINVOKE_EXPORT extern "C" __attribute__((visibility("default")))
GD_PINVOKE_EXPORT int32_t _monodroid_get_android_api_level() {
return get_build_version_sdk_int();
}
GD_PINVOKE_EXPORT void monodroid_free(void *ptr) {
free(ptr);
}
GD_PINVOKE_EXPORT int32_t monodroid_get_system_property(const char *p_name, char **r_value) {
char prop_value_str[PROP_VALUE_MAX + 1] = { 0 };
int len = __system_property_get(p_name, prop_value_str);
if (r_value) {
if (len >= 0) {
*r_value = (char *)malloc(len + 1);
if (!*r_value)
return -1;
memcpy(*r_value, prop_value_str, len);
(*r_value)[len] = '\0';
} else {
*r_value = nullptr;
}
}
return len;
}
GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_up_state(const char *p_ifname, mono_bool *r_is_up) {
// The JNI code is the equivalent of:
//
// NetworkInterface.getByName(p_ifname).isUp()
if (!r_is_up || !p_ifname || strlen(p_ifname) == 0)
return 0;
*r_is_up = 0;
JNIEnv *env = ThreadAndroid::get_env();
jclass networkInterfaceClass = env->FindClass("java/net/NetworkInterface");
ERR_FAIL_NULL_V(networkInterfaceClass, 0);
jmethodID getByName = env->GetStaticMethodID(networkInterfaceClass, "getByName", "(Ljava/lang/String;)Ljava/net/NetworkInterface;");
ERR_FAIL_NULL_V(getByName, 0);
jmethodID isUp = env->GetMethodID(networkInterfaceClass, "isUp", "()Z");
ERR_FAIL_NULL_V(isUp, 0);
ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname));
ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get()));
if (!networkInterface)
return 0;
*r_is_up = (mono_bool)env->CallBooleanMethod(networkInterface, isUp);
return 1;
}
GD_PINVOKE_EXPORT mono_bool _monodroid_get_network_interface_supports_multicast(const char *p_ifname, mono_bool *r_supports_multicast) {
// The JNI code is the equivalent of:
//
// NetworkInterface.getByName(p_ifname).supportsMulticast()
if (!r_supports_multicast || !p_ifname || strlen(p_ifname) == 0)
return 0;
*r_supports_multicast = 0;
JNIEnv *env = ThreadAndroid::get_env();
jclass networkInterfaceClass = env->FindClass("java/net/NetworkInterface");
ERR_FAIL_NULL_V(networkInterfaceClass, 0);
jmethodID getByName = env->GetStaticMethodID(networkInterfaceClass, "getByName", "(Ljava/lang/String;)Ljava/net/NetworkInterface;");
ERR_FAIL_NULL_V(getByName, 0);
jmethodID supportsMulticast = env->GetMethodID(networkInterfaceClass, "supportsMulticast", "()Z");
ERR_FAIL_NULL_V(supportsMulticast, 0);
ScopedLocalRef<jstring> js_ifname(env, env->NewStringUTF(p_ifname));
ScopedLocalRef<jobject> networkInterface(env, env->CallStaticObjectMethod(networkInterfaceClass, getByName, js_ifname.get()));
if (!networkInterface)
return 0;
*r_supports_multicast = (mono_bool)env->CallBooleanMethod(networkInterface, supportsMulticast);
return 1;
}
static const int dns_servers_len = 8;
static void interop_get_active_network_dns_servers(char **r_dns_servers, int *dns_servers_count) {
// The JNI code is the equivalent of:
//
// ConnectivityManager connectivityManager = (ConnectivityManager)getApplicationContext()
// .getSystemService(Context.CONNECTIVITY_SERVICE);
// Network activeNerwork = connectivityManager.getActiveNetwork();
// LinkProperties linkProperties = connectivityManager.getLinkProperties(activeNerwork);
// List<String> dnsServers = linkProperties.getDnsServers().stream()
// .map(inetAddress -> inetAddress.getHostAddress()).collect(Collectors.toList());
#ifdef DEBUG_ENABLED
CRASH_COND(get_build_version_sdk_int() < 23);
#endif
JNIEnv *env = ThreadAndroid::get_env();
GodotJavaWrapper *godot_java = ((OS_Android *)OS::get_singleton())->get_godot_java();
jobject activity = godot_java->get_activity();
ScopedLocalRef<jclass> activityClass(env, env->GetObjectClass(activity));
ERR_FAIL_NULL(activityClass);
jmethodID getApplicationContext = env->GetMethodID(activityClass, "getApplicationContext", "()Landroid/content/Context;");
ScopedLocalRef<jobject> applicationContext(env, env->CallObjectMethod(activity, getApplicationContext));
ScopedLocalRef<jclass> contextClass(env, env->FindClass("android/content/Context"));
ERR_FAIL_NULL(contextClass);
jfieldID connectivityServiceField = env->GetStaticFieldID(contextClass, "CONNECTIVITY_SERVICE", "Ljava/lang/String;");
ScopedLocalRef<jstring> connectivityServiceString(env, (jstring)env->GetStaticObjectField(contextClass, connectivityServiceField));
jmethodID getSystemService = env->GetMethodID(contextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
ScopedLocalRef<jobject> connectivityManager(env, env->CallObjectMethod(applicationContext, getSystemService, connectivityServiceString.get()));
if (!connectivityManager)
return;
ScopedLocalRef<jclass> connectivityManagerClass(env, env->FindClass("android/net/ConnectivityManager"));
ERR_FAIL_NULL(connectivityManagerClass);
jmethodID getActiveNetwork = env->GetMethodID(connectivityManagerClass, "getActiveNetwork", "()Landroid/net/Network;");
ERR_FAIL_NULL(getActiveNetwork);
ScopedLocalRef<jobject> activeNetwork(env, env->CallObjectMethod(connectivityManager, getActiveNetwork));
if (!activeNetwork)
return;
jmethodID getLinkProperties = env->GetMethodID(connectivityManagerClass,
"getLinkProperties", "(Landroid/net/Network;)Landroid/net/LinkProperties;");
ERR_FAIL_NULL(getLinkProperties);
ScopedLocalRef<jobject> linkProperties(env, env->CallObjectMethod(connectivityManager, getLinkProperties, activeNetwork.get()));
if (!linkProperties)
return;
ScopedLocalRef<jclass> linkPropertiesClass(env, env->FindClass("android/net/LinkProperties"));
ERR_FAIL_NULL(linkPropertiesClass);
jmethodID getDnsServers = env->GetMethodID(linkPropertiesClass, "getDnsServers", "()Ljava/util/List;");
ERR_FAIL_NULL(getDnsServers);
ScopedLocalRef<jobject> dnsServers(env, env->CallObjectMethod(linkProperties, getDnsServers));
if (!dnsServers)
return;
ScopedLocalRef<jclass> listClass(env, env->FindClass("java/util/List"));
ERR_FAIL_NULL(listClass);
jmethodID listSize = env->GetMethodID(listClass, "size", "()I");
ERR_FAIL_NULL(listSize);
int dnsServersCount = env->CallIntMethod(dnsServers, listSize);
if (dnsServersCount > dns_servers_len)
dnsServersCount = dns_servers_len;
if (dnsServersCount <= 0)
return;
jmethodID listGet = env->GetMethodID(listClass, "get", "(I)Ljava/lang/Object;");
ERR_FAIL_NULL(listGet);
ScopedLocalRef<jclass> inetAddressClass(env, env->FindClass("java/net/InetAddress"));
ERR_FAIL_NULL(inetAddressClass);
jmethodID getHostAddress = env->GetMethodID(inetAddressClass, "getHostAddress", "()Ljava/lang/String;");
ERR_FAIL_NULL(getHostAddress);
for (int i = 0; i < dnsServersCount; i++) {
ScopedLocalRef<jobject> dnsServer(env, env->CallObjectMethod(dnsServers, listGet, (jint)i));
if (!dnsServer)
continue;
ScopedLocalRef<jstring> hostAddress(env, (jstring)env->CallObjectMethod(dnsServer, getHostAddress));
const char *host_address = env->GetStringUTFChars(hostAddress, 0);
r_dns_servers[i] = strdup(host_address); // freed by the BCL
(*dns_servers_count)++;
env->ReleaseStringUTFChars(hostAddress, host_address);
}
// jesus...
}
GD_PINVOKE_EXPORT int32_t _monodroid_get_dns_servers(void **r_dns_servers_array) {
if (!r_dns_servers_array)
return -1;
*r_dns_servers_array = nullptr;
char *dns_servers[dns_servers_len];
int dns_servers_count = 0;
if (_monodroid_get_android_api_level() < 26) {
// The 'net.dns*' system properties are no longer available in Android 8.0 (API level 26) and greater:
// http://developer.android.com/about/versions/oreo/android-8.0-changes.html#o-pri
char prop_name[] = "net.dns*";
for (int i = 0; i < dns_servers_len; i++) {
prop_name[7] = (char)(i + 0x31);
char *prop_value;
int32_t len = monodroid_get_system_property(prop_name, &prop_value);
if (len > 0) {
dns_servers[dns_servers_count] = strndup(prop_value, (size_t)len); // freed by the BCL
dns_servers_count++;
free(prop_value);
}
}
} else {
// Alternative for Oreo and greater
interop_get_active_network_dns_servers(dns_servers, &dns_servers_count);
}
if (dns_servers_count > 0) {
size_t ret_size = sizeof(char *) * (size_t)dns_servers_count;
*r_dns_servers_array = malloc(ret_size); // freed by the BCL
memcpy(*r_dns_servers_array, dns_servers, ret_size);
}
return dns_servers_count;
}
GD_PINVOKE_EXPORT const char *_monodroid_timezone_get_default_id() {
// The JNI code is the equivalent of:
//
// TimeZone.getDefault().getID()
JNIEnv *env = ThreadAndroid::get_env();
ScopedLocalRef<jclass> timeZoneClass(env, env->FindClass("java/util/TimeZone"));
ERR_FAIL_NULL_V(timeZoneClass, nullptr);
jmethodID getDefault = env->GetStaticMethodID(timeZoneClass, "getDefault", "()Ljava/util/TimeZone;");
ERR_FAIL_NULL_V(getDefault, nullptr);
jmethodID getID = env->GetMethodID(timeZoneClass, "getID", "()Ljava/lang/String;");
ERR_FAIL_NULL_V(getID, nullptr);
ScopedLocalRef<jobject> defaultTimeZone(env, env->CallStaticObjectMethod(timeZoneClass, getDefault));
if (!defaultTimeZone)
return nullptr;
ScopedLocalRef<jstring> defaultTimeZoneID(env, (jstring)env->CallObjectMethod(defaultTimeZone, getID));
if (!defaultTimeZoneID)
return nullptr;
const char *default_time_zone_id = env->GetStringUTFChars(defaultTimeZoneID, 0);
char *result = strdup(default_time_zone_id); // freed by the BCL
env->ReleaseStringUTFChars(defaultTimeZoneID, default_time_zone_id);
return result;
}
GD_PINVOKE_EXPORT int32_t _monodroid_getifaddrs(struct ifaddrs **p_ifap) {
return getifaddrs(p_ifap);
}
GD_PINVOKE_EXPORT void _monodroid_freeifaddrs(struct ifaddrs *p_ifap) {
freeifaddrs(p_ifap);
}
#endif
|
/*
This is a set of dummy definitions for the canonical machining
functions given in canon.hh. These functions just print. On each
output line is printed:
1. an output line number (sequential, starting with 1).
2. an input line number read from the input (or ... if not provided).
3. a printed representation of the function call which was made.
If an interpreter which makes these calls is compiled with this set of
definitions, it can be used as a translator by redirecting output from
stdout to a file.
*/
/*
Modification history:
1-Nov-2000 WPS added unused variables a,b,c to ARC_FEED,STRAIHT_FEED, etc.
24-Feb-2000 FMP added CANON_UPDATE_POSITION()
*/
#define _CRT_SECURE_NO_DEPRECATE 1
#define NO_WARN_MBCS_MFC_DEPRECATION
#include "StdAfx.h"
#include "rs274ngc_return.h"
#define AND &&
#define IS ==
#define ISNT !=
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define NOT !
#define OR ||
#define SET_TO =
int HandleThreading(double *FeedRate);
int CheckIfThreadingInProgress(void);
char Output[MAX_LINE];
char ErrorOutput[MAX_LINE];
CGCodeInterpreter *GC;
CCoordMotion *CM;;
void print_nc_line_number()
{
char s[256];
// int line_number SET_TO _interpreter_block.line_number;
int line_number SET_TO 0;
if (line_number IS -1)
sprintf(s," N ... ");
else if (line_number < 10)
sprintf(s," N%d ", line_number);
else if (line_number < 100)
sprintf(s," N%d ", line_number);
else if (line_number < 1000)
sprintf(s," N%d ", line_number);
else if (line_number < 10000)
sprintf(s," N%d ", line_number);
else
sprintf(s,"N%d ", line_number);
// Output += s;
strcat(Output,"-"); // this looks a little nicer in the KMotion app
}
#define PRINT0(control) if (1) \
{ \
char _s[256]; \
sprintf(_s,"%5d ", line_number++); \
strcat(Output,_s); \
print_nc_line_number(); \
sprintf(_s,control); \
if ('\n'==_s[strlen(_s)-1]) _s[strlen(_s)-1]=0; \
strcat(Output,_s); \
sprintf(_s,"@%.3f\r\n",((double)GetTickCount())/1000.0); \
strcat(Output,_s); \
} else
#define PRINT1(control, arg1) if (1) \
{ \
char _s[256]; \
sprintf(_s,"%5d ", line_number++); \
strcat(Output,_s); \
print_nc_line_number(); \
sprintf(_s,control, arg1); \
if ('\n'==_s[strlen(_s)-1]) _s[strlen(_s)-1]=0; \
strcat(Output,_s); \
sprintf(_s,"@%.3f\r\n",((double)GetTickCount())/1000.0); \
strcat(Output,_s); \
} else
#define PRINT2(control, arg1, arg2) if (1) \
{ \
char _s[256]; \
sprintf(_s,"%5d ", line_number++); \
strcat(Output,_s); \
print_nc_line_number(); \
sprintf(_s,control, arg1, arg2); \
if ('\n'==_s[strlen(_s)-1]) _s[strlen(_s)-1]=0; \
strcat(Output,_s); \
sprintf(_s,"@%.3f\r\n",((double)GetTickCount())/1000.0); \
strcat(Output,_s); \
} else
#define PRINT3(control, arg1, arg2, arg3) if (1) \
{ \
char _s[256]; \
sprintf(_s,"%5d ", line_number++); \
strcat(Output,_s); \
print_nc_line_number(); \
sprintf(_s,control, arg1, arg2, arg3); \
if ('\n'==_s[strlen(_s)-1]) _s[strlen(_s)-1]=0; \
strcat(Output,_s); \
sprintf(_s,"@%.3f\r\n",((double)GetTickCount())/1000.0); \
strcat(Output,_s); \
} else
#define PRINT4(control, arg1, arg2, arg3, arg4) if (1) \
{ \
char _s[256]; \
sprintf(_s,"%5d ", line_number++); \
strcat(Output,_s); \
print_nc_line_number(); \
sprintf(_s,control, arg1, arg2, arg3, arg4); \
if ('\n'==_s[strlen(_s)-1]) _s[strlen(_s)-1]=0; \
strcat(Output,_s); \
sprintf(_s,"@%.3f\r\n",((double)GetTickCount())/1000.0); \
strcat(Output,_s); \
} else
#define PRINT6(control, arg1, arg2, arg3, arg4, arg5, arg6) if (1) \
{ \
char _s[256]; \
sprintf(_s,"%5d ", line_number++); \
strcat(Output,_s); \
print_nc_line_number(); \
sprintf(_s,control, arg1, arg2, arg3, arg4, arg5, arg6); \
if ('\n'==_s[strlen(_s)-1]) _s[strlen(_s)-1]=0; \
strcat(Output,_s); \
sprintf(_s,"@%.3f\r\n",((double)GetTickCount())/1000.0); \
strcat(Output,_s); \
} else
int line_number SET_TO 1;
static CANON_VECTOR program_origin;
static CANON_UNITS length_units = CANON_UNITS_MM;
static CANON_PLANE active_plane = CANON_PLANE_XY;
/* Representation */
void SET_ORIGIN_OFFSETS(double x, double y, double z,
double a, double b, double c, double u, double v)
{PRINT3("SET_ORIGIN_OFFSETS(%.4f, %.4f, %.4f)\n", x, y, z);
program_origin.x SET_TO x;
program_origin.y SET_TO y;
program_origin.z SET_TO z;
}
void USE_LENGTH_UNITS(CANON_UNITS in_unit)
{PRINT1("USE_LENGTH_UNITS(%s)\n",
(in_unit IS CANON_UNITS_INCHES) ? "CANON_UNITS_INCHES" :
(in_unit IS CANON_UNITS_MM) ? "CANON_UNITS_MM" : "UNKNOWN");
}
/* Free Space Motion */
void SET_TRAVERSE_RATE(double rate)
{PRINT1("SET_TRAVERSE_RATE(%.4f)\n", rate);}
void STRAIGHT_TRAVERSE (double x, double y, double z,
double a, double b, double c, double u, double v)
{
PRINT4("STRAIGHT_TRAVERSE(%.4f, %.4f, %.4f, %.4f)\n", x, y, z, a);
if (CheckIfThreadingInProgress()) return;
GC->SaveStateOnceOnly(); // save the state here before creating any motion segments
CM->StraightTraverse(GC->UserUnitsToInchesX(x+_setup.axis_offset_x+_setup.origin_offset_x+_setup.tool_xoffset),
GC->UserUnitsToInches(y+_setup.axis_offset_y+_setup.origin_offset_y+_setup.tool_yoffset),
GC->UserUnitsToInches(z+_setup.axis_offset_z+_setup.origin_offset_z+_setup.tool_length_offset),
GC->UserUnitsToInchesOrDegA(a+_setup.AA_axis_offset+_setup.AA_origin_offset),
GC->UserUnitsToInchesOrDegB(b + _setup.BB_axis_offset + _setup.BB_origin_offset),
GC->UserUnitsToInchesOrDegC(c + _setup.CC_axis_offset + _setup.CC_origin_offset),
GC->UserUnitsToInches(u + _setup.UU_axis_offset + _setup.UU_origin_offset),
GC->UserUnitsToInches(v + _setup.VV_axis_offset + _setup.VV_origin_offset),
false,_setup.sequence_number,0);
}
/* Machining Attributes */
void SET_FEED_RATE(double rate)
{
PRINT1("SET_FEED_RATE(%.4f)\n", rate);
}
void SET_FEED_REFERENCE(CANON_FEED_REFERENCE reference)
{PRINT1("SET_FEED_REFERENCE(%s)\n",
(reference IS CANON_WORKPIECE) ? "CANON_WORKPIECE" : "CANON_XYZ");}
void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode)
{PRINT1("SET_MOTION_CONTROL_MODE(%s)\n",
(mode IS CANON_EXACT_PATH) ? "CANON_EXACT_PATH" :
(mode IS CANON_EXACT_STOP) ? "CANON_EXACT_STOP" : "CANON_CONTINUOUS");}
void SET_SPINDLE_MODE(CANON_SPINDLE_MODE mode)
{PRINT1("SET_MOTION_CONTROL_MODE(%s)\n",
(mode IS CANON_SPINDLE_NORMAL) ? "CANON_SPINDLE_NORMAL" :
(mode IS CANON_SPINDLE_CSS) ? "CANON_SPINDLE_CSS" : "CANON_SPINDLE_INVALID");
GC->SetCSS(mode);
}
void SELECT_PLANE(CANON_PLANE in_plane)
{PRINT1("SELECT_PLANE(%s)\n",
(in_plane IS CANON_PLANE_XY) ? "CANON_PLANE_XY" :
(in_plane IS CANON_PLANE_YZ) ? "CANON_PLANE_YZ" :
(in_plane IS CANON_PLANE_XZ) ? "CANON_PLANE_XZ" : "UNKNOWN");
}
void SET_CUTTER_RADIUS_COMPENSATION(double radius)
{PRINT1("SET_CUTTER_RADIUS_COMPENSATION(%.4f)\n", radius);}
void START_CUTTER_RADIUS_COMPENSATION(int side)
{PRINT1("START_CUTTER_RADIUS_COMPENSATION(%s)\n",
(side IS LEFT) ? "LEFT" :
(side IS RIGHT) ? "RIGHT" : "UNKNOWN");
}
void STOP_CUTTER_RADIUS_COMPENSATION()
{PRINT0 ("STOP_CUTTER_RADIUS_COMPENSATION()\n");}
void START_SPEED_FEED_SYNCH()
{PRINT0 ("START_SPEED_FEED_SYNCH()\n");}
void STOP_SPEED_FEED_SYNCH()
{PRINT0 ("STOP_SPEED_FEED_SYNCH()\n");}
void SELECT_MOTION_MODE(CANON_MOTION_MODE mode)
{PRINT1("SELECT_MOTION_MODE(%s)\n",
(mode IS CANON_EXACT_STOP) ? "CANON_EXACT_STOP" :
(mode IS CANON_EXACT_PATH) ? "CANON_EXACT_PATH" :
(mode IS CANON_CONTINUOUS) ? "CANON_CONTINUOUS" :
"UNKNOWN");
}
void SELECT_SPINDLE_MODE(CANON_SPINDLE_MODE mode)
{PRINT1("SELECT_SPINDLE_MODE(%s)\n",
(mode IS CANON_SPINDLE_NORMAL) ? "CANON_SPINDLE_NORMAL" :
(mode IS CANON_SPINDLE_CSS) ? "CANON_SPINDLE_CSS" :
"UNKNOWN");
}
/* Machining Functions */
void ARC_FEED(double first_end, double second_end,
double first_axis, double second_axis, int rotation,
double axis_end_point,
double a, double b, double c, double u, double v, int ID)
{
double FeedRate;
PRINT6("ARC_FEED(%.4f, %.4f, %.4f, %.4f, %d, %.4f)\n",
first_end, second_end, first_axis, second_axis, rotation,
axis_end_point);
if (HandleThreading(&FeedRate)) return;
if (!CM->m_ThreadingMode) // Threading?
{
if (CheckIfThreadingInProgress()) return;
FeedRate = GC->UserUnitsToInches(_setup.feed_rate) / 60.0;
}
GC->SaveStateOnceOnly(); // save the state here before creating any motion segments
if (_setup.plane == CANON_PLANE_XY)
{
CM->ArcFeed(FeedRate, _setup.plane,
GC->UserUnitsToInchesX(first_end+_setup.axis_offset_x+_setup.origin_offset_x+_setup.tool_xoffset),
GC->UserUnitsToInches(second_end+_setup.axis_offset_y+_setup.origin_offset_y+_setup.tool_yoffset),
GC->UserUnitsToInchesX(first_axis+_setup.axis_offset_x+_setup.origin_offset_x+_setup.tool_xoffset),
GC->UserUnitsToInches(second_axis+_setup.axis_offset_y+_setup.origin_offset_y+_setup.tool_yoffset),
(rotation==1 ? 1 : 0),
GC->UserUnitsToInches(axis_end_point+_setup.axis_offset_z+_setup.origin_offset_z+_setup.tool_length_offset),
GC->UserUnitsToInchesOrDegA(a + _setup.AA_axis_offset + _setup.AA_origin_offset),
GC->UserUnitsToInchesOrDegB(b + _setup.BB_axis_offset + _setup.BB_origin_offset),
GC->UserUnitsToInchesOrDegC(c + _setup.CC_axis_offset + _setup.CC_origin_offset),
GC->UserUnitsToInches(u + _setup.UU_axis_offset + _setup.UU_origin_offset),
GC->UserUnitsToInches(v + _setup.VV_axis_offset + _setup.VV_origin_offset),
_setup.sequence_number, ID);
}
else if (_setup.plane == CANON_PLANE_XZ)
{
// Actually more like ZX plane
CM->ArcFeed(FeedRate, _setup.plane,
GC->UserUnitsToInches(first_end+_setup.axis_offset_z+_setup.origin_offset_z+_setup.tool_length_offset),
GC->UserUnitsToInchesX(second_end+_setup.axis_offset_x+_setup.origin_offset_x+_setup.tool_xoffset),
GC->UserUnitsToInches(first_axis+_setup.axis_offset_z+_setup.origin_offset_z+_setup.tool_length_offset),
GC->UserUnitsToInchesX(second_axis+_setup.axis_offset_x+_setup.origin_offset_x+_setup.tool_xoffset),
(rotation==1 ? 1 : 0),
GC->UserUnitsToInches(axis_end_point+_setup.axis_offset_y+_setup.origin_offset_y+_setup.tool_yoffset),
GC->UserUnitsToInchesOrDegA(a + _setup.AA_axis_offset + _setup.AA_origin_offset),
GC->UserUnitsToInchesOrDegB(b + _setup.BB_axis_offset + _setup.BB_origin_offset),
GC->UserUnitsToInchesOrDegC(c + _setup.CC_axis_offset + _setup.CC_origin_offset),
GC->UserUnitsToInches(u + _setup.UU_axis_offset + _setup.UU_origin_offset),
GC->UserUnitsToInches(v + _setup.VV_axis_offset + _setup.VV_origin_offset),
_setup.sequence_number, ID);
}
else
{
CM->ArcFeed(FeedRate, _setup.plane,
GC->UserUnitsToInches(first_end+_setup.axis_offset_y+_setup.origin_offset_y+_setup.tool_yoffset),
GC->UserUnitsToInches(second_end+_setup.axis_offset_z+_setup.origin_offset_z+_setup.tool_length_offset),
GC->UserUnitsToInches(first_axis+_setup.axis_offset_y+_setup.origin_offset_y+_setup.tool_yoffset),
GC->UserUnitsToInches(second_axis+_setup.axis_offset_z+_setup.origin_offset_z+_setup.tool_length_offset),
(rotation==1 ? 1 : 0),
GC->UserUnitsToInchesX(axis_end_point+_setup.axis_offset_x+_setup.origin_offset_x+_setup.tool_xoffset),
GC->UserUnitsToInchesOrDegA(a + _setup.AA_axis_offset + _setup.AA_origin_offset),
GC->UserUnitsToInchesOrDegB(b + _setup.BB_axis_offset + _setup.BB_origin_offset),
GC->UserUnitsToInchesOrDegC(c + _setup.CC_axis_offset + _setup.CC_origin_offset),
GC->UserUnitsToInches(u + _setup.UU_axis_offset + _setup.UU_origin_offset),
GC->UserUnitsToInches(v + _setup.VV_axis_offset + _setup.VV_origin_offset),
_setup.sequence_number, ID);
}
}
void STRAIGHT_FEED (double x, double y, double z,
double a, double b, double c, double u, double v, int ID)
{
PRINT4("STRAIGHT_FEED(%.4f, %.4f, %.4f, %.4f)\n", x, y, z, a);
double FeedRate;
if (HandleThreading(&FeedRate)) return;
if (!CM->m_ThreadingMode) // Threading?
{
if (CheckIfThreadingInProgress()) return;
// must do this to determine if feed is a pure angle
// if so feedrate is in degrees/min so don't convert from mm to inches
double dx = x - _setup.current_x;
double dy = y - _setup.current_y;
double dz = z - _setup.current_z;
double da = a - _setup.AA_current;
double db = b - _setup.BB_current;
double dc = c - _setup.CC_current;
double du = u - _setup.UU_current;
double dv = v - _setup.VV_current;
BOOL pure_angle;
CM->FeedRateDistance(dx, dy, dz, da, db, dc, du, dv, &pure_angle);
if (pure_angle)
FeedRate = _setup.feed_rate/60.0; // convert to degrees/sec
else
FeedRate = GC->UserUnitsToInches(_setup.feed_rate)/60.0; // convert to inches/sec
}
GC->SaveStateOnceOnly(); // save the state here before creating any motion segments
CM->StraightFeed(FeedRate,
GC->UserUnitsToInchesX(x+_setup.axis_offset_x+_setup.origin_offset_x+_setup.tool_xoffset),
GC->UserUnitsToInches(y+_setup.axis_offset_y+_setup.origin_offset_y+_setup.tool_yoffset),
GC->UserUnitsToInches(z+_setup.axis_offset_z+_setup.origin_offset_z+_setup.tool_length_offset),
GC->UserUnitsToInchesOrDegA(a+_setup.AA_axis_offset+_setup.AA_origin_offset),
GC->UserUnitsToInchesOrDegB(b + _setup.BB_axis_offset + _setup.BB_origin_offset),
GC->UserUnitsToInchesOrDegC(c + _setup.CC_axis_offset + _setup.CC_origin_offset),
GC->UserUnitsToInches(u + _setup.UU_axis_offset + _setup.UU_origin_offset),
GC->UserUnitsToInches(v + _setup.VV_axis_offset + _setup.VV_origin_offset),
_setup.sequence_number,ID);
}
// determine if we are to be in Threading mode based on Feed and Motion Modes
// if Threading return calculated feedrate
// if transitioning to Threading mode Flush any previous motion
int HandleThreading(double *FeedRate)
{
if (_setup.motion_mode == G_32 ||
((_setup.feed_mode == UNITS_PER_REV)
&& (_setup.motion_mode == G_1 || _setup.motion_mode == G_2 || _setup.motion_mode == G_3))) // Threading?
{
double InchesPerRev = GC->UserUnitsToInches(_setup.feed_rate);
double RevsPerSec = _setup.speed / 60.0;
*FeedRate = InchesPerRev * RevsPerSec;
// if not already in threading mode, then wait for anything that
// may already be in progress to complete so when we re-launch motion
// we will be in sychronized mode
if (!CM->m_ThreadingMode)
{
if (CM->FlushSegments()) { CM->SetAbort(); return 1; }
if (CM->WaitForSegmentsFinished(TRUE)) { CM->SetAbort(); return 1; }
}
if (GC->p_setup->spindle_turning == CANON_COUNTERCLOCKWISE)
CM->m_ThreadingBaseSpeedRPS = -RevsPerSec;
else
CM->m_ThreadingBaseSpeedRPS = RevsPerSec;
CM->m_ThreadingMode = true;
}
return 0;
}
// whenever a new motion is to be initiated that is not spindle synchronized
// and spindle synchronized mode had been in progress then make sure it finishes
// so a new launch of coordinated motion (without spindle sync) will be generated
int CheckIfThreadingInProgress(void)
{
if (CM->m_ThreadingMode)
{
if (CM->FlushSegments()) {CM->SetAbort(); return 1;}
if (CM->WaitForSegmentsFinished(TRUE)) {CM->SetAbort(); return 1;}
}
return 0;
}
void STRAIGHT_PROBE (double x, double y, double z,
double a, double b, double c, double u, double v)
{PRINT3("STRAIGHT_PROBE(%.4f, %.4f, %.4f)\n", x, y, z);}
/*
void PARAMETRIC_2D_CURVE_FEED(FunctionPtr f1, FunctionPtr f2,
double start_parameter_value,
double end_parameter_value) {}
void PARAMETRIC_3D_CURVE_FEED(FunctionPtr xfcn, FunctionPtr yfcn,
FunctionPtr zfcn, double start_parameter_value,
double end_parameter_value) {}
*/
void DWELL(double seconds)
{
PRINT1("DWELL(%.4f)\n", seconds);
if (CheckIfThreadingInProgress()) return;
GC->SaveStateOnceOnly(); // save the state here before creating any motion segments
CM->Dwell(seconds,_setup.sequence_number);
}
/* Spindle Functions */
void SPINDLE_RETRACT_TRAVERSE()
{PRINT0("SPINDLE_RETRACT_TRAVERSE()\n");}
void START_SPINDLE_CLOCKWISE()
{
PRINT0("START_SPINDLE_CLOCKWISE()\n");
GC->InvokeAction(3); // do the defined action for M Code
}
void START_SPINDLE_COUNTERCLOCKWISE()
{
PRINT0("START_SPINDLE_COUNTERCLOCKWISE()\n");
GC->InvokeAction(4); // do the defined action for M Code
}
void SET_SPINDLE_SPEED(double r)
{
PRINT1("SET_SPINDLE_SPEED(%.4f)\n", r);
GC->InvokeAction(10); // do the defined action for S Speed
}
void STOP_SPINDLE_TURNING()
{
PRINT0("STOP_SPINDLE_TURNING()\n");
GC->InvokeAction(5); // do the defined action for M Code
}
void SPINDLE_RETRACT()
{PRINT0("SPINDLE_RETRACT()\n");}
void ORIENT_SPINDLE(double orientation, CANON_DIRECTION direction)
{PRINT2("ORIENT_SPINDLE(%.4f, %s)\n", orientation,
(direction IS CANON_CLOCKWISE) ? "CANON_CLOCKWISE" :
"CANON_COUNTERCLOCKWISE");
}
void USE_NO_SPINDLE_FORCE()
{PRINT0("USE_NO_SPINDLE_FORCE()\n");}
/* Tool Functions */
void USE_TOOL_LENGTH_OFFSET(double length_units, double xoffset_units, double yoffset_units)
{
double Acts[MAX_ACTUATORS];
PRINT1("USE_TOOL_LENGTH_OFFSET(%.4f)\n", length_units);
double xoffset = GC->UserUnitsToInchesX(xoffset_units);
double yoffset = GC->UserUnitsToInches(yoffset_units);
double length = GC->UserUnitsToInches(length_units);
// Things get complicated if Tool Center point changes on-the-fly
// for non-linear Kineamtics. So if tool offset changes Flush
// KFLOP buffer before changes. For optimization
// only flush when some offset changed and TCP is used
if (CM->m_TCP_affects_actuators &&
(CM->GetMotionParams()->TCP_X != xoffset ||
CM->GetMotionParams()->TCP_Y != yoffset ||
CM->GetMotionParams()->TCP_Z != length))
{
if (CM->FlushSegments()) { CM->SetAbort(); return; }
if (CM->WaitForSegmentsFinished(TRUE)) { CM->SetAbort(); return; }
CM->Kinematics->TransformCADtoActuators(CM->current_x, CM->current_y, CM->current_z, CM->current_a, CM->current_b, CM->current_c, CM->current_u, CM->current_v, Acts);
CM->GetMotionParams()->TCP_X = xoffset;
CM->GetMotionParams()->TCP_Y = yoffset;
CM->GetMotionParams()->TCP_Z = length;
CM->Kinematics->TransformActuatorstoCAD(Acts, &CM->current_x, &CM->current_y, &CM->current_z, &CM->current_a, &CM->current_b, &CM->current_c, &CM->current_u, &CM->current_v);
GC->ConvertAbsoluteToInterpreterCoord(CM->current_x, CM->current_y, CM->current_z, CM->current_a, CM->current_b, CM->current_c, CM->current_u, CM->current_v,
&_setup.current_x, &_setup.current_y, &_setup.current_z, &_setup.AA_current, &_setup.BB_current, &_setup.CC_current, &_setup.UU_current, &_setup.VV_current, &_setup);
}
}
void CHANGE_TOOL(int slot)
{
PRINT1("CHANGE_TOOL(%d)\n", slot);
GC->InvokeAction(6); // do the defined action for M Code
}
int M100(int mcode) /* User M code */
{
PRINT1("MCODE(%d)\n", mcode);
return GC->InvokeAction(mcode); // do the defined action for M Code
}
void SELECT_TOOL(int slot)
{PRINT1("SELECT_TOOL(%d)\n", slot);}
/* Misc Functions */
void CLAMP_AXIS(CANON_AXIS axis)
{PRINT1("CLAMP_AXIS(%s)\n",
(axis IS CANON_AXIS_X) ? "CANON_AXIS_X" :
(axis IS CANON_AXIS_Y) ? "CANON_AXIS_Y" :
(axis IS CANON_AXIS_Z) ? "CANON_AXIS_Z" : "UNKNOWN");}
// check for CMD,xxxxxx any case and after removing whitespace
int CheckForPassThroughCommand(char *comment)
{ /* string with comment */
int m;
int item;
for (m = 0; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'C') && (item != 'c')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'M') && (item != 'm')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'D') && (item != 'd')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if (item != ',') return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
PRINT1("COMMAND(\"%s\")\n", comment + m);
CM->DoKMotionCmd(comment + m, TRUE);
return 1;
}
int CheckForBufferedCommand(char *comment)
{ /* string with comment */
int m;
int item;
for (m = 0; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'B') && (item != 'b')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'U') && (item != 'u')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'F') && (item != 'f')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if (item != ',') return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
PRINT1("BUFFER(\"%s\")\n", comment + m);
CM->DoKMotionBufCmd(comment + m,GC->p_setup->sequence_number);
return 1;
}
int CheckForUserCallback(char *comment)
{ /* string with comment */
int m;
int item;
for (m = 0; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'U') && (item != 'u')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'S') && (item != 's')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if ((item != 'R') && (item != 'r')) return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
if (item != ',') return 0;
for (m++; ((item = comment[m]) == ' ') || (item == '\t'); m++);
PRINT1("USR(\"%s\")\n", comment + m);
if (GC->m_UserFn)
{
if (CM->FlushSegments()) {CM->SetAbort(); return 1;}
if (CM->WaitForSegmentsFinished(TRUE)) {CM->SetAbort(); return 1;}
if (GC->m_UserFn(comment + m)){CM->SetAbort(); return 1;}
// don't sample positions until everything is stopped
if (CM->WaitForSegmentsFinished()) return 1;
if (CM->WaitForMoveXYZABCFinished()) return 1;
if (!CM->m_Simulate && GC->ReadAndSyncCurPositions(&_setup.current_x,&_setup.current_y,&_setup.current_z,
&_setup.AA_current, &_setup.BB_current, &_setup.CC_current, &_setup.UU_current, &_setup.VV_current))
return 1;
}
return 1;
}
void COMMENT(char *s)
{
if (CheckForBufferedCommand(s)) return;
if (CheckForPassThroughCommand(s)) return;
if (CheckForUserCallback(s)) return;
PRINT1("COMMENT(\"%s\")\n", s);
}
void DISABLE_FEED_OVERRIDE()
{PRINT0("DISABLE_FEED_OVERRIDE()\n");}
void DISABLE_SPEED_OVERRIDE()
{PRINT0("DISABLE_SPEED_OVERRIDE()\n");}
void ENABLE_FEED_OVERRIDE()
{PRINT0("ENABLE_FEED_OVERRIDE()\n");}
void ENABLE_SPEED_OVERRIDE()
{PRINT0("ENABLE_SPEED_OVERRIDE()\n");}
void FLOOD_OFF()
{
PRINT0("FLOOD_OFF()\n");
}
void FLOOD_ON()
{
PRINT0("FLOOD_ON()\n");
GC->InvokeAction(8); // do the defined action for M Code
}
void MESSAGE(char *s)
{
if (CM->FlushSegments()) {CM->SetAbort(); return;}
if (CM->WaitForSegmentsFinished(TRUE)) {CM->SetAbort(); return;}
PRINT1("MESSAGE(\"%s\")\n", s);
if (AfxMessageBox(s,MB_OKCANCEL|MB_TOPMOST|MB_SETFOREGROUND|MB_SYSTEMMODAL)==IDCANCEL)
{
GC->Abort();
}
}
void MIST_OFF()
{
PRINT0("MIST_OFF()\n");
GC->InvokeAction(9); // do the defined action for M Code
}
void MIST_ON()
{
PRINT0("MIST_ON()\n");
GC->InvokeAction(7); // do the defined action for M Code
}
void PALLET_SHUTTLE()
{PRINT0("PALLET_SHUTTLE()\n");}
void TURN_PROBE_OFF()
{PRINT0("TURN_PROBE_OFF()\n");}
void TURN_PROBE_ON()
{PRINT0("TURN_PROBE_ON()\n");}
void UNCLAMP_AXIS(CANON_AXIS axis)
{PRINT1("UNCLAMP_AXIS(%s)\n",
(axis IS CANON_AXIS_X) ? "CANON_AXIS_X" :
(axis IS CANON_AXIS_Y) ? "CANON_AXIS_Y" :
(axis IS CANON_AXIS_Z) ? "CANON_AXIS_Z" : "UNKNOWN");}
/* Program Functions */
void PROGRAM_STOP()
{
PRINT0("PROGRAM_STOP()\n");
// GC->m_Halt=true;
GC->InvokeAction(0,TRUE);
GC->m_end=0; // force line number to be passed
}
void OPTIONAL_PROGRAM_STOP()
{
GC->InvokeAction(1,TRUE);
PRINT0("OPTIONAL_PROGRAM_STOP()\n");
}
void PROGRAM_END(int MCode)
{
PRINT0("PROGRAM_END()\n");
CM->FlushSegments();
if (MCode==30)
GC->InvokeAction(24,TRUE); // M30 Special Operation
else if (MCode==2)
GC->InvokeAction(2,TRUE); // M2 Special Operation
}
/* returns the current x, y, z origin offsets */
CANON_VECTOR GET_PROGRAM_ORIGIN()
{
return program_origin;
}
/* returns the current active units */
CANON_UNITS GET_LENGTH_UNITS()
{
return length_units;
}
CANON_PLANE GET_PLANE()
{
return active_plane;
}
/*********************************************************************/
/*
The purpose of these GET_XXX (and other) functions is to provide for
local emulation of the world modeling done by the EMC system.
/*********************************************************************/
/* GET_EXTERNAL_FEED_RATE
called by: rs274ngc_synch
This is a stub.
*/
double GET_EXTERNAL_FEED_RATE()
{
return _setup.feed_rate;
}
/*********************************************************************/
int GET_EXTERNAL_FLOOD()
{
return OFF;
}
/*********************************************************************/
int GET_EXTERNAL_MIST()
{
return OFF;
}
/*********************************************************************/
int GET_EXTERNAL_POCKET()
{
return 1;
}
/*********************************************************************/
CANON_POSITION GET_EXTERNAL_POSITION()
{
return CANON_POSITION(_setup.current_x,
_setup.current_y,
_setup.current_z,
0.0,
0.0,
0.0,
0.0,
0.0);
}
/*********************************************************************/
CANON_POSITION GET_EXTERNAL_PROBE_POSITION()
{
return CANON_POSITION(_setup.current_x,
_setup.current_y,
_setup.current_z,
0.0,
0.0,
0.0,
0.0,
0.0);
}
/*********************************************************************/
double GET_EXTERNAL_PROBE_VALUE()
{
return 1.0;
}
/*********************************************************************/
double GET_EXTERNAL_SPEED()
{
// speed is in RPMs everywhere
return 1000;
}
/*********************************************************************/
CANON_DIRECTION GET_EXTERNAL_SPINDLE()
{
return CANON_STOPPED;
}
/*********************************************************************/
int GET_EXTERNAL_TOOL()
{
return 1;
}
/*********************************************************************/
int GET_EXTERNAL_TOOL_MAX()
{
return CANON_TOOL_MAX;
}
/*********************************************************************/
CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int pocket)
{
CANON_TOOL_TABLE retval;
if (pocket == 0)
{
retval.id = 1;
retval.length = 2.0;
retval.diameter = 1.0;
}
else if (pocket == 1)
{
retval.id = 1;
retval.length = 2.0;
retval.diameter = 1.0;
}
else if (pocket == 2)
{
retval.id = 2;
retval.length = 1.0;
retval.diameter = 2.0;
}
else
{
retval.id = 0;
retval.length = 0.0;
retval.diameter = 0.0;
}
return retval;
}
/*********************************************************************/
double GET_EXTERNAL_TRAVERSE_RATE()
{
return 100.0;
}
/*********************************************************************/
CANON_MOTION_MODE GET_MOTION_CONTROL_MODE()
{
return CANON_CONTINUOUS;
// return CANON_EXACT_PATH;
}
/*********************************************************************/
CANON_SPINDLE_MODE GET_SPINDLE_MODE()
{
return CANON_SPINDLE_NORMAL;
}
/*********************************************************************/
/* INIT_CANON()
called by: rs274ngc_init
This is a stub.
*/
void INIT_CANON()
{}
/*********************************************************************/
/*
IS_EXTERNAL_QUEUE_EMPTY emulates the EMC external to the
interpreter. It just returns 1, meaning the queue is empty (any
non-zero means the queue is empty).
*/
int IS_EXTERNAL_QUEUE_EMPTY()
{
return 1;
}
/*********************************************************************/
/*
CANON_UPDATE_POSITION tells the canonical interface that it should
update the end position it may have been saving, due to an abort other
other external event that may have made the end position different.
Here it does nothing since the standalone interpreter doesn't keep track
of the end position.
*/
void CANON_UPDATE_POSITION()
{
return;
}
/*********************************************************************/
CANON_MOTION_MODE MotionMode = CANON_EXACT_STOP;
// Returns the current motion control mode
CANON_MOTION_MODE GET_EXTERNAL_MOTION_CONTROL_MODE()
{
return MotionMode;
}
CANON_SPINDLE_MODE SpindleMode = CANON_SPINDLE_NORMAL;
// Returns the current motion control mode
CANON_SPINDLE_MODE GET_EXTERNAL_SPINDLE_MODE()
{
return SpindleMode;
}
// returns nothing but copies the name of the parameter file into
// the filename array, stopping at max_size if the name is longer
// An empty string may be placed in filename.
void GET_EXTERNAL_PARAMETER_FILE_NAME(char *filename, int max_size)
{
if (GC->VarsFile[0] == 0)
sprintf(filename, "%s%cData%cemc.var",GC->CoordMotion->MainPathRoot, PATH_SEPARATOR, PATH_SEPARATOR);
else
strcpy(filename, GC->VarsFile);
}
// returns the currently active plane
CANON_PLANE GET_EXTERNAL_PLANE() { return CANON_PLANE_XY; };
// returns the current a-axis position
double GET_EXTERNAL_POSITION_A() { return 0.0; };
// returns the current b-axis position
double GET_EXTERNAL_POSITION_B() { return 0.0; };
// returns the current c-axis position
double GET_EXTERNAL_POSITION_C() { return 0.0; };
// returns the current u-axis position
double GET_EXTERNAL_POSITION_U() { return 0.0; };
// returns the current v-axis position
double GET_EXTERNAL_POSITION_V() { return 0.0; };
// returns the current x-axis position
double GET_EXTERNAL_POSITION_X() { return 0.0; };
// returns the current y-axis position
double GET_EXTERNAL_POSITION_Y() { return 0.0; };
// returns the current z-axis position
double GET_EXTERNAL_POSITION_Z() { return 0.0; };
// Returns the machine A-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_A() { return 0.0; };
// Returns the machine B-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_B() { return 0.0; };
// Returns the machine C-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_C() { return 0.0; };
// Returns the machine U-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_U() { return 0.0; };
// Returns the machine V-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_V() { return 0.0; };
// Returns the machine X-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_X() { return 0.0; };
// Returns the machine Y-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_Y() { return 0.0; };
// Returns the machine Z-axis position at the last probe trip.
double GET_EXTERNAL_PROBE_POSITION_Z() { return 0.0; };
// Returns zero if queue is not empty, non-zero if the queue is empty
// This always returns a valid value
int GET_EXTERNAL_QUEUE_EMPTY() { return 1; };
// returns current tool length offset
double GET_EXTERNAL_TOOL_LENGTH_OFFSET() { return 0.0; };
// Returns the system length unit type
CANON_UNITS GET_EXTERNAL_LENGTH_UNIT_TYPE() {return CANON_UNITS_MM; };
// Returns the system value for the carousel slot in which the tool
// currently in the spindle belongs. Return value zero means there is no
// tool in the spindle.
int GET_EXTERNAL_TOOL_SLOT() { return 0; };
void SET_CANON_DEVICE(int *device)
{
CGCodeInterpreter *GC=(CGCodeInterpreter *)device;
}
int CHECK_INIT_ON_EXE()
{
if (GC->m_InitializeOnExecute)
{
return GC->InitializeInterp();
}
else
{
return 0;
}
}
int CHECK_PREVIOUS_STOP(double mx, double my, int log)
{
if (!CM->m_PreviouslyStopped || CM->m_PreviouslyStoppedID==1)
{
return 1;
}
else
{
if(log)
{
CM->m_StoppedMidx = mx;
CM->m_StoppedMidy = my;
}
return 0;
}
}
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/types.pb.h"
namespace tensorflow {
namespace {
class ConstOp : public XlaOpKernel {
public:
explicit ConstOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
const TensorProto* proto = nullptr;
OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto));
proto_ = *proto;
OP_REQUIRES(
ctx, ctx->output_type(0) == proto_.dtype(),
errors::InvalidArgument("Type mismatch between value (",
DataTypeString(proto_.dtype()), ") and dtype (",
DataTypeString(ctx->output_type(0)), ")"));
OP_REQUIRES_OK(ctx, TensorShape::IsValidShape(proto_.tensor_shape()));
}
void Compile(XlaOpKernelContext* ctx) override {
TensorShape shape(proto_.tensor_shape());
xla::XlaBuilder* b = ctx->builder();
// To avoid blowups for large constants filled with the same value,
// recognize that case and emit a scalar broadcast instead.
if (shape.num_elements() > 1) {
switch (proto_.dtype()) {
case DT_BOOL:
if (proto_.bool_val_size() == 1) {
ctx->SetOutput(
0, xla::Broadcast(xla::ConstantR0<bool>(b, proto_.bool_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_FLOAT:
if (proto_.float_val_size() == 1) {
ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<float>(
b, proto_.float_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_DOUBLE:
if (proto_.double_val_size() == 1) {
ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<double>(
b, proto_.double_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_COMPLEX64:
if (proto_.scomplex_val_size() == 2) {
ctx->SetOutput(
0,
xla::Broadcast(xla::ConstantR0<xla::complex64>(
b, xla::complex64(proto_.scomplex_val(0),
proto_.scomplex_val(1))),
shape.dim_sizes()));
return;
}
break;
case DT_COMPLEX128:
if (proto_.scomplex_val_size() == 2) {
ctx->SetOutput(
0,
xla::Broadcast(xla::ConstantR0<xla::complex128>(
b, xla::complex128(proto_.dcomplex_val(0),
proto_.dcomplex_val(1))),
shape.dim_sizes()));
return;
}
break;
case DT_INT32:
if (proto_.int_val_size() == 1) {
ctx->SetOutput(
0, xla::Broadcast(xla::ConstantR0<int32>(b, proto_.int_val(0)),
shape.dim_sizes()));
return;
}
break;
case DT_INT64:
if (proto_.int64_val_size() == 1) {
ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<int64>(
b, proto_.int64_val(0)),
shape.dim_sizes()));
return;
}
break;
default:
break;
}
}
// General case
Tensor tensor(proto_.dtype());
OP_REQUIRES(ctx, tensor.FromProto(cpu_allocator(), proto_),
errors::InvalidArgument("Cannot parse tensor from proto: ",
proto_.DebugString()));
ctx->SetConstantOutput(0, tensor);
}
private:
TensorProto proto_;
TF_DISALLOW_COPY_AND_ASSIGN(ConstOp);
};
// XLA_* devices also register a "real" Const operator so we suppress the
// dummy operator using CompilationOnly().
REGISTER_XLA_OP(Name("Const").CompilationOnly(), ConstOp);
} // namespace
} // namespace tensorflow
|
//@ Project : ssTools
//@ Copyright : Non-unruly (Git)
//@ Git: https://github.com/Non-Unruly/ssTools
//@
//@ Launch Date : 2020-06-27
//@ Update: 2020-12-15
#include "ssTools.h"
std::vector<std::string> ssTools::ss_split(std::string str, std::string key)
{
std::vector<std::string> texts;
int keyLen = key.length();
if (keyLen == 0)
{
texts.push_back(str);
return texts;
}
std::string step;
size_t pos = 0;
while (pos < str.length())
{
int cur_pos = str.find(key, pos);
step = str.substr(pos, cur_pos - pos);
if (step.length() > 0)
texts.push_back(step);
step.clear();
if (cur_pos == -1)
break;
pos = cur_pos + key.length();
}
return texts;
}
std::string ssTools::ss_keyJoint(std::vector<std::string> elems, std::string key, bool leftJoint, bool rightJoint)
{
std::string str = "";
if (leftJoint)
str = key;
for (std::vector<std::string>::iterator iter = elems.begin(); iter != elems.end(); iter++)
{
if (iter == (elems.end() - 1))
str = str + (*iter);
else
str = str + (*iter) + key;
}
if (rightJoint)
str = str + key;
return str;
}
unsigned long ssTools::ss_timetick()
{
#if defined _WIN32 || defined _WIN64
//windows 平台
__int64 Freq = 0;
__int64 Count = 0;
if (QueryPerformanceFrequency((LARGE_INTEGER*)&Freq)
&& Freq > 0
&& QueryPerformanceCounter((LARGE_INTEGER*)&Count))
{
//乘以1000,把秒化为毫秒
return (unsigned long)(double)Count / (double)Freq * 1000.0;
}
return 0.0;
#else
//Linux 平台
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_usec / 1000 + tv.tv_sec * 1000;
#endif // WIN32
}
std::string ssTools::ss_datetime()
{
char result[1024];
memset(result, 0, 1024);
#if defined _WIN32 || defined _WIN64
//windows 平台
SYSTEMTIME tm;
GetLocalTime(&tm);
sprintf(result, "%04d%02d%02d %02d:%02d:%02d:%03ld",
tm.wYear,
tm.wMonth,
tm.wDay,
tm.wHour,
tm.wMinute,
tm.wSecond,
tm.wMilliseconds
);
#else
//Linux 平台
struct timeval tv;
gettimeofday(&tv, 0);
struct tm* pTempTm = localtime(&tv.tv_sec);
if (pTempTm != NULL)
{
sprintf(result, "%04d%02d%02d %02d:%02d:%02d:%03ld",
pTempTm->tm_year + 1900,
pTempTm->tm_mon + 1,
pTempTm->tm_mday,
pTempTm->tm_hour,
pTempTm->tm_min,
pTempTm->tm_sec,
tv.tv_usec / 1000);
}
#endif // WIN32
return std::string(result);
}
std::string ssTools::ss_datetime_simple()
{
char result[1024];
memset(result, 0, 1024);
#if defined _WIN32 || defined _WIN64
//windows 平台
SYSTEMTIME tm;
GetLocalTime(&tm);
sprintf(result, "%04d%02d%02d%02d%02d%02d",
tm.wYear,
tm.wMonth,
tm.wDay,
tm.wHour,
tm.wMinute,
tm.wSecond
);
#else
//Linux 平台
struct timeval tv;
gettimeofday(&tv, 0);
struct tm* pTempTm = localtime(&tv.tv_sec);
if (pTempTm != NULL)
{
sprintf(result, "%04d%02d%02d%02d%02d%02d",
pTempTm->tm_year + 1900,
pTempTm->tm_mon + 1,
pTempTm->tm_mday,
pTempTm->tm_hour,
pTempTm->tm_min,
pTempTm->tm_sec);
}
#endif // WIN32
return std::string(result);
}
bool ssTools::ss_makePath(const char * path)
{
if (strlen(path) <= 0)
return false;
char *cmd = new char[32 + strlen(path)];
std::string dir;
#if defined _WIN32 || defined _WIN64
//windows 平台
for (int i = 0; i < strlen(path); i++)
dir += path[i] == '/' ? '\\' : path[i];
sprintf(cmd, "md %s\0", dir.c_str());
#else
//Linux 平台
for (int i = 0; i < strlen(path); i++)
dir += path[i] == '\\' ? '/' : path[i];
sprintf(cmd, "mkdir -vp %s\0", dir.c_str());
#endif
system(cmd);
delete[]cmd;
return true;
}
short ssTools::hex2i(const char * _hex)
{
short res = 0;
std::string hex(_hex);
if (hex.length() != 2)
return -1;
std::transform(hex.begin(), hex.end(), hex.begin(), toupper);
for (int i = 0; i < 2; i++)
{
if (hex[i] >= '0' && hex[i] <= '9')
{
res += (hex[i] - '0')*pow(16, 1 - i);
continue;
}
else if (hex[i] >= 'A' && hex[i] <= 'F')
{
res += (hex[i] - 'A' + 10)*pow(16, 1 - i);;
continue;
}
else
{
return -1;
}
}
return res;
}
|
/* Loop versioning pass.
Copyright (C) 2018-2020 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3, or (at your option) any
later version.
GCC is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "backend.h"
#include "tree.h"
#include "gimple.h"
#include "gimple-iterator.h"
#include "tree-pass.h"
#include "gimplify-me.h"
#include "cfgloop.h"
#include "tree-ssa-loop.h"
#include "ssa.h"
#include "tree-scalar-evolution.h"
#include "tree-chrec.h"
#include "tree-ssa-loop-ivopts.h"
#include "fold-const.h"
#include "tree-ssa-propagate.h"
#include "tree-inline.h"
#include "domwalk.h"
#include "alloc-pool.h"
#include "vr-values.h"
#include "gimple-ssa-evrp-analyze.h"
#include "tree-vectorizer.h"
#include "omp-general.h"
#include "predict.h"
#include "tree-into-ssa.h"
namespace {
/* This pass looks for loops that could be simplified if certain loop
invariant conditions were true. It is effectively a form of loop
splitting in which the pass produces the split conditions itself,
instead of using ones that are already present in the IL.
Versioning for when strides are 1
---------------------------------
At the moment the only thing the pass looks for are memory references
like:
for (auto i : ...)
...x[i * stride]...
It considers changing such loops to:
if (stride == 1)
for (auto i : ...) [A]
...x[i]...
else
for (auto i : ...) [B]
...x[i * stride]...
This can have several benefits:
(1) [A] is often easier or cheaper to vectorize than [B].
(2) The scalar code in [A] is simpler than the scalar code in [B]
(if the loops cannot be vectorized or need an epilogue loop).
(3) We might recognize [A] as a pattern, such as a memcpy or memset.
(4) [A] has simpler address evolutions, which can help other passes
like loop interchange.
The optimization is particularly useful for assumed-shape arrays in
Fortran, where the stride of the innermost dimension depends on the
array descriptor but is often equal to 1 in practice. For example:
subroutine f1(x)
real :: x(:)
x(:) = 100
end subroutine f1
generates the equivalent of:
raw_stride = *x.dim[0].stride;
stride = raw_stride != 0 ? raw_stride : 1;
x_base = *x.data;
...
tmp1 = stride * S;
tmp2 = tmp1 - stride;
*x_base[tmp2] = 1.0e+2;
but in the common case that stride == 1, the last three statements
simplify to:
tmp3 = S + -1;
*x_base[tmp3] = 1.0e+2;
The optimization is in principle very simple. The difficult parts are:
(a) deciding which parts of a general address calculation correspond
to the inner dimension of an array, since this usually isn't explicit
in the IL, and for C often isn't even explicit in the source code
(b) estimating when the transformation is worthwhile
Structure
---------
The pass has four phases:
(1) Walk through the statements looking for and recording potential
versioning opportunities. Stop if there are none.
(2) Use context-sensitive range information to see whether any versioning
conditions are impossible in practice. Remove them if so, and stop
if no opportunities remain.
(We do this only after (1) to keep compile time down when no
versioning opportunities exist.)
(3) Apply the cost model. Decide which versioning opportunities are
worthwhile and at which nesting level they should be applied.
(4) Attempt to version all the loops selected by (3), so that:
for (...)
...
becomes:
if (!cond)
for (...) // Original loop
...
else
for (...) // New loop
...
Use the version condition COND to simplify the new loop. */
/* Enumerates the likelihood that a particular value indexes the inner
dimension of an array. */
enum inner_likelihood {
INNER_UNLIKELY,
INNER_DONT_KNOW,
INNER_LIKELY
};
/* Information about one term of an address_info. */
struct address_term_info
{
/* The value of the term is EXPR * MULTIPLIER. */
tree expr;
unsigned HOST_WIDE_INT multiplier;
/* The stride applied by EXPR in each iteration of some unrecorded loop,
or null if no stride has been identified. */
tree stride;
/* Enumerates the likelihood that EXPR indexes the inner dimension
of an array. */
enum inner_likelihood inner_likelihood;
/* True if STRIDE == 1 is a versioning opportunity when considered
in isolation. */
bool versioning_opportunity_p;
};
/* Information about an address calculation, and the range of constant
offsets applied to it. */
class address_info
{
public:
static const unsigned int MAX_TERMS = 8;
/* One statement that calculates the address. If multiple statements
share the same address, we only record the first. */
gimple *stmt;
/* The loop containing STMT (cached for convenience). If multiple
statements share the same address, they all belong to this loop. */
class loop *loop;
/* A decomposition of the calculation into a sum of terms plus an
optional base. When BASE is provided, it is never an SSA name.
Once initialization is complete, all members of TERMs are SSA names. */
tree base;
auto_vec<address_term_info, MAX_TERMS> terms;
/* All bytes accessed from the address fall in the offset range
[MIN_OFFSET, MAX_OFFSET). */
HOST_WIDE_INT min_offset, max_offset;
};
/* Stores addresses based on their base and terms (ignoring the offsets). */
struct address_info_hasher : nofree_ptr_hash <address_info>
{
static hashval_t hash (const address_info *);
static bool equal (const address_info *, const address_info *);
};
/* Information about the versioning we'd like to apply to a loop. */
class loop_info
{
public:
bool worth_versioning_p () const;
/* True if we've decided not to version this loop. The remaining
fields are meaningless if so. */
bool rejected_p;
/* True if at least one subloop of this loop benefits from versioning. */
bool subloops_benefit_p;
/* An estimate of the total number of instructions in the loop,
excluding those in subloops that benefit from versioning. */
unsigned int num_insns;
/* The outermost loop that can handle all the version checks
described below. */
class loop *outermost;
/* The first entry in the list of blocks that belong to this loop
(and not to subloops). m_next_block_in_loop provides the chain
pointers for the list. */
basic_block block_list;
/* We'd like to version the loop for the case in which these SSA names
(keyed off their SSA_NAME_VERSION) are all equal to 1 at runtime. */
bitmap_head unity_names;
/* If versioning succeeds, this points the version of the loop that
assumes the version conditions holds. */
class loop *optimized_loop;
};
/* The main pass structure. */
class loop_versioning
{
public:
loop_versioning (function *);
~loop_versioning ();
unsigned int run ();
private:
/* Used to walk the dominator tree to find loop versioning conditions
that are always false. */
class lv_dom_walker : public dom_walker
{
public:
lv_dom_walker (loop_versioning &);
edge before_dom_children (basic_block) FINAL OVERRIDE;
void after_dom_children (basic_block) FINAL OVERRIDE;
private:
/* The parent pass. */
loop_versioning &m_lv;
/* Used to build context-dependent range information. */
evrp_range_analyzer m_range_analyzer;
};
/* Used to simplify statements based on conditions that are established
by the version checks. */
class name_prop : public substitute_and_fold_engine
{
public:
name_prop (loop_info &li) : m_li (li) {}
tree get_value (tree) FINAL OVERRIDE;
private:
/* Information about the versioning we've performed on the loop. */
loop_info &m_li;
};
loop_info &get_loop_info (class loop *loop) { return m_loops[loop->num]; }
unsigned int max_insns_for_loop (class loop *);
bool expensive_stmt_p (gimple *);
void version_for_unity (gimple *, tree);
bool acceptable_multiplier_p (tree, unsigned HOST_WIDE_INT,
unsigned HOST_WIDE_INT * = 0);
bool acceptable_type_p (tree, unsigned HOST_WIDE_INT *);
bool multiply_term_by (address_term_info &, tree);
inner_likelihood get_inner_likelihood (tree, unsigned HOST_WIDE_INT);
void dump_inner_likelihood (address_info &, address_term_info &);
void analyze_stride (address_info &, address_term_info &,
tree, class loop *);
bool find_per_loop_multiplication (address_info &, address_term_info &);
bool analyze_term_using_scevs (address_info &, address_term_info &);
void analyze_arbitrary_term (address_info &, address_term_info &);
void analyze_address_fragment (address_info &);
void record_address_fragment (gimple *, unsigned HOST_WIDE_INT,
tree, unsigned HOST_WIDE_INT, HOST_WIDE_INT);
void analyze_expr (gimple *, tree);
bool analyze_block (basic_block);
bool analyze_blocks ();
void prune_loop_conditions (class loop *, vr_values *);
bool prune_conditions ();
void merge_loop_info (class loop *, class loop *);
void add_loop_to_queue (class loop *);
bool decide_whether_loop_is_versionable (class loop *);
bool make_versioning_decisions ();
bool version_loop (class loop *);
void implement_versioning_decisions ();
/* The function we're optimizing. */
function *m_fn;
/* The obstack to use for all pass-specific bitmaps. */
bitmap_obstack m_bitmap_obstack;
/* An obstack to use for general allocation. */
obstack m_obstack;
/* The number of loops in the function. */
unsigned int m_nloops;
/* The total number of loop version conditions we've found. */
unsigned int m_num_conditions;
/* Assume that an address fragment of the form i * stride * scale
(for variable stride and constant scale) will not benefit from
versioning for stride == 1 when scale is greater than this value. */
unsigned HOST_WIDE_INT m_maximum_scale;
/* Information about each loop. */
auto_vec<loop_info> m_loops;
/* Used to form a linked list of blocks that belong to a loop,
started by loop_info::block_list. */
auto_vec<basic_block> m_next_block_in_loop;
/* The list of loops that we've decided to version. */
auto_vec<class loop *> m_loops_to_version;
/* A table of addresses in the current loop, keyed off their values
but not their offsets. */
hash_table <address_info_hasher> m_address_table;
/* A list of all addresses in M_ADDRESS_TABLE, in a predictable order. */
auto_vec <address_info *, 32> m_address_list;
};
/* If EXPR is an SSA name and not a default definition, return the
defining statement, otherwise return null. */
static gimple *
maybe_get_stmt (tree expr)
{
if (TREE_CODE (expr) == SSA_NAME && !SSA_NAME_IS_DEFAULT_DEF (expr))
return SSA_NAME_DEF_STMT (expr);
return NULL;
}
/* Like maybe_get_stmt, but also return null if the defining
statement isn't an assignment. */
static gassign *
maybe_get_assign (tree expr)
{
return safe_dyn_cast <gassign *> (maybe_get_stmt (expr));
}
/* Return true if this pass should look through a cast of expression FROM
to type TYPE when analyzing pieces of an address. */
static bool
look_through_cast_p (tree type, tree from)
{
return (INTEGRAL_TYPE_P (TREE_TYPE (from)) == INTEGRAL_TYPE_P (type)
&& POINTER_TYPE_P (TREE_TYPE (from)) == POINTER_TYPE_P (type));
}
/* Strip all conversions of integers or pointers from EXPR, regardless
of whether the conversions are nops. This is useful in the context
of this pass because we're not trying to fold or simulate the
expression; we just want to see how it's structured. */
static tree
strip_casts (tree expr)
{
const unsigned int MAX_NITERS = 4;
tree type = TREE_TYPE (expr);
while (CONVERT_EXPR_P (expr)
&& look_through_cast_p (type, TREE_OPERAND (expr, 0)))
expr = TREE_OPERAND (expr, 0);
for (unsigned int niters = 0; niters < MAX_NITERS; ++niters)
{
gassign *assign = maybe_get_assign (expr);
if (assign
&& CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (assign))
&& look_through_cast_p (type, gimple_assign_rhs1 (assign)))
expr = gimple_assign_rhs1 (assign);
else
break;
}
return expr;
}
/* Compare two address_term_infos in the same address_info. */
static int
compare_address_terms (const void *a_uncast, const void *b_uncast)
{
const address_term_info *a = (const address_term_info *) a_uncast;
const address_term_info *b = (const address_term_info *) b_uncast;
if (a->expr != b->expr)
return SSA_NAME_VERSION (a->expr) < SSA_NAME_VERSION (b->expr) ? -1 : 1;
if (a->multiplier != b->multiplier)
return a->multiplier < b->multiplier ? -1 : 1;
return 0;
}
/* Dump ADDRESS using flags FLAGS. */
static void
dump_address_info (dump_flags_t flags, address_info &address)
{
if (address.base)
dump_printf (flags, "%T + ", address.base);
for (unsigned int i = 0; i < address.terms.length (); ++i)
{
if (i != 0)
dump_printf (flags, " + ");
dump_printf (flags, "%T", address.terms[i].expr);
if (address.terms[i].multiplier != 1)
dump_printf (flags, " * %wd", address.terms[i].multiplier);
}
dump_printf (flags, " + [%wd, %wd]",
address.min_offset, address.max_offset - 1);
}
/* Hash an address_info based on its base and terms. */
hashval_t
address_info_hasher::hash (const address_info *info)
{
inchash::hash hash;
hash.add_int (info->base ? TREE_CODE (info->base) : 0);
hash.add_int (info->terms.length ());
for (unsigned int i = 0; i < info->terms.length (); ++i)
{
hash.add_int (SSA_NAME_VERSION (info->terms[i].expr));
hash.add_hwi (info->terms[i].multiplier);
}
return hash.end ();
}
/* Return true if two address_infos have equal bases and terms. Other
properties might be different (such as the statement or constant
offset range). */
bool
address_info_hasher::equal (const address_info *a, const address_info *b)
{
if (a->base != b->base
&& (!a->base || !b->base || !operand_equal_p (a->base, b->base, 0)))
return false;
if (a->terms.length () != b->terms.length ())
return false;
for (unsigned int i = 0; i < a->terms.length (); ++i)
if (a->terms[i].expr != b->terms[i].expr
|| a->terms[i].multiplier != b->terms[i].multiplier)
return false;
return true;
}
/* Return true if we want to version the loop, i.e. if we have a
specific reason for doing so and no specific reason not to. */
bool
loop_info::worth_versioning_p () const
{
return (!rejected_p
&& (!bitmap_empty_p (&unity_names) || subloops_benefit_p));
}
loop_versioning::lv_dom_walker::lv_dom_walker (loop_versioning &lv)
: dom_walker (CDI_DOMINATORS), m_lv (lv), m_range_analyzer (false)
{
}
/* Process BB before processing the blocks it dominates. */
edge
loop_versioning::lv_dom_walker::before_dom_children (basic_block bb)
{
m_range_analyzer.enter (bb);
if (bb == bb->loop_father->header)
m_lv.prune_loop_conditions (bb->loop_father,
m_range_analyzer.get_vr_values ());
for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
gsi_next (&si))
m_range_analyzer.record_ranges_from_stmt (gsi_stmt (si), false);
return NULL;
}
/* Process BB after processing the blocks it dominates. */
void
loop_versioning::lv_dom_walker::after_dom_children (basic_block bb)
{
m_range_analyzer.leave (bb);
}
/* Decide whether to replace VAL with a new value in a versioned loop.
Return the new value if so, otherwise return null. */
tree
loop_versioning::name_prop::get_value (tree val)
{
if (TREE_CODE (val) == SSA_NAME
&& bitmap_bit_p (&m_li.unity_names, SSA_NAME_VERSION (val)))
return build_one_cst (TREE_TYPE (val));
return NULL_TREE;
}
/* Initialize the structure to optimize FN. */
loop_versioning::loop_versioning (function *fn)
: m_fn (fn),
m_nloops (number_of_loops (fn)),
m_num_conditions (0),
m_address_table (31)
{
bitmap_obstack_initialize (&m_bitmap_obstack);
gcc_obstack_init (&m_obstack);
/* Initialize the loop information. */
m_loops.safe_grow_cleared (m_nloops);
for (unsigned int i = 0; i < m_nloops; ++i)
{
m_loops[i].outermost = get_loop (m_fn, 0);
bitmap_initialize (&m_loops[i].unity_names, &m_bitmap_obstack);
}
/* Initialize the list of blocks that belong to each loop. */
unsigned int nbbs = last_basic_block_for_fn (fn);
m_next_block_in_loop.safe_grow (nbbs);
basic_block bb;
FOR_EACH_BB_FN (bb, fn)
{
loop_info &li = get_loop_info (bb->loop_father);
m_next_block_in_loop[bb->index] = li.block_list;
li.block_list = bb;
}
/* MAX_FIXED_MODE_SIZE should be a reasonable maximum scale for
unvectorizable code, since it is the largest size that can be
handled efficiently by scalar code. omp_max_vf calculates the
maximum number of bytes in a vector, when such a value is relevant
to loop optimization. */
m_maximum_scale = estimated_poly_value (omp_max_vf ());
m_maximum_scale = MAX (m_maximum_scale, MAX_FIXED_MODE_SIZE);
}
loop_versioning::~loop_versioning ()
{
bitmap_obstack_release (&m_bitmap_obstack);
obstack_free (&m_obstack, NULL);
}
/* Return the maximum number of instructions allowed in LOOP before
it becomes too big for versioning.
There are separate limits for inner and outer loops. The limit for
inner loops applies only to loops that benefit directly from versioning.
The limit for outer loops applies to all code in the outer loop and
its subloops that *doesn't* benefit directly from versioning; such code
would be "taken along for the ride". The idea is that if the cost of
the latter is small, it is better to version outer loops rather than
inner loops, both to reduce the number of repeated checks and to enable
more of the loop nest to be optimized as a natural nest (e.g. by loop
interchange or outer-loop vectorization). */
unsigned int
loop_versioning::max_insns_for_loop (class loop *loop)
{
return (loop->inner
? param_loop_versioning_max_outer_insns
: param_loop_versioning_max_inner_insns);
}
/* Return true if for cost reasons we should avoid versioning any loop
that contains STMT.
Note that we don't need to check whether versioning is invalid for
correctness reasons, since the versioning process does that for us.
The conditions involved are too rare to be worth duplicating here. */
bool
loop_versioning::expensive_stmt_p (gimple *stmt)
{
if (gcall *call = dyn_cast <gcall *> (stmt))
/* Assume for now that the time spent in an "expensive" call would
overwhelm any saving from versioning. */
return !gimple_inexpensive_call_p (call);
return false;
}
/* Record that we want to version the loop that contains STMT for the
case in which SSA name NAME is equal to 1. We already know that NAME
is invariant in the loop. */
void
loop_versioning::version_for_unity (gimple *stmt, tree name)
{
class loop *loop = loop_containing_stmt (stmt);
loop_info &li = get_loop_info (loop);
if (bitmap_set_bit (&li.unity_names, SSA_NAME_VERSION (name)))
{
/* This is the first time we've wanted to version LOOP for NAME.
Keep track of the outermost loop that can handle all versioning
checks in LI. */
class loop *outermost
= outermost_invariant_loop_for_expr (loop, name);
if (loop_depth (li.outermost) < loop_depth (outermost))
li.outermost = outermost;
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, stmt, "want to version containing loop"
" for when %T == 1", name);
if (outermost == loop)
dump_printf (MSG_NOTE, "; cannot hoist check further");
else
{
dump_printf (MSG_NOTE, "; could implement the check at loop"
" depth %d", loop_depth (outermost));
if (loop_depth (li.outermost) > loop_depth (outermost))
dump_printf (MSG_NOTE, ", but other checks only allow"
" a depth of %d", loop_depth (li.outermost));
}
dump_printf (MSG_NOTE, "\n");
}
m_num_conditions += 1;
}
else
{
/* This is a duplicate request. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, stmt, "already asked to version containing"
" loop for when %T == 1\n", name);
}
}
/* Return true if OP1_TREE is constant and if in principle it is worth
versioning an address fragment of the form:
i * OP1_TREE * OP2 * stride
for the case in which stride == 1. This in practice means testing
whether:
OP1_TREE * OP2 <= M_MAXIMUM_SCALE.
If RESULT is nonnull, store OP1_TREE * OP2 there when returning true. */
bool
loop_versioning::acceptable_multiplier_p (tree op1_tree,
unsigned HOST_WIDE_INT op2,
unsigned HOST_WIDE_INT *result)
{
if (tree_fits_uhwi_p (op1_tree))
{
unsigned HOST_WIDE_INT op1 = tree_to_uhwi (op1_tree);
/* The first part checks for overflow. */
if (op1 * op2 >= op2 && op1 * op2 <= m_maximum_scale)
{
if (result)
*result = op1 * op2;
return true;
}
}
return false;
}
/* Return true if it is worth using loop versioning on a memory access
of type TYPE. Store the size of the access in *SIZE if so. */
bool
loop_versioning::acceptable_type_p (tree type, unsigned HOST_WIDE_INT *size)
{
return (TYPE_SIZE_UNIT (type)
&& acceptable_multiplier_p (TYPE_SIZE_UNIT (type), 1, size));
}
/* See whether OP is constant and whether we can multiply TERM by that
constant without exceeding M_MAXIMUM_SCALE. Return true and update
TERM if so. */
bool
loop_versioning::multiply_term_by (address_term_info &term, tree op)
{
return acceptable_multiplier_p (op, term.multiplier, &term.multiplier);
}
/* Decide whether an address fragment of the form STRIDE * MULTIPLIER
is likely to be indexing an innermost dimension, returning the result
as an INNER_* probability. */
inner_likelihood
loop_versioning::get_inner_likelihood (tree stride,
unsigned HOST_WIDE_INT multiplier)
{
const unsigned int MAX_NITERS = 8;
/* Iterate over possible values of STRIDE. Return INNER_LIKELY if at
least one of those values is likely to be for the innermost dimension.
Record in UNLIKELY_P if at least one of those values is unlikely to be
for the innermost dimension.
E.g. for:
stride = cond ? a * b : 1
we should treat STRIDE as being a likely inner dimension, since
we know that it is 1 under at least some circumstances. (See the
Fortran example below.) However:
stride = a * b
on its own is unlikely to be for the innermost dimension, since
that would require both a and b to be 1 at runtime. */
bool unlikely_p = false;
tree worklist[MAX_NITERS];
unsigned int length = 0;
worklist[length++] = stride;
for (unsigned int i = 0; i < length; ++i)
{
tree expr = worklist[i];
if (CONSTANT_CLASS_P (expr))
{
/* See if EXPR * MULTIPLIER would be consistent with an individual
access or a small grouped access. */
if (acceptable_multiplier_p (expr, multiplier))
return INNER_LIKELY;
else
unlikely_p = true;
}
else if (gimple *stmt = maybe_get_stmt (expr))
{
/* If EXPR is set by a PHI node, queue its arguments in case
we find one that is consistent with an inner dimension.
An important instance of this is the Fortran handling of array
descriptors, which calculates the stride of the inner dimension
using a PHI equivalent of:
raw_stride = a.dim[0].stride;
stride = raw_stride != 0 ? raw_stride : 1;
(Strides for outer dimensions do not treat 0 specially.) */
if (gphi *phi = dyn_cast <gphi *> (stmt))
{
unsigned int nargs = gimple_phi_num_args (phi);
for (unsigned int j = 0; j < nargs && length < MAX_NITERS; ++j)
worklist[length++] = strip_casts (gimple_phi_arg_def (phi, j));
}
/* If the value is set by an assignment, expect it to be read
from memory (such as an array descriptor) rather than be
calculated. */
else if (gassign *assign = dyn_cast <gassign *> (stmt))
{
if (!gimple_assign_load_p (assign))
unlikely_p = true;
}
/* Things like calls don't really tell us anything. */
}
}
/* We didn't find any possible values of STRIDE that were likely to be
for the innermost dimension. If we found one that was actively
unlikely to be for the innermost dimension, assume that that applies
to STRIDE too. */
return unlikely_p ? INNER_UNLIKELY : INNER_DONT_KNOW;
}
/* Dump the likelihood that TERM's stride is for the innermost dimension.
ADDRESS is the address that contains TERM. */
void
loop_versioning::dump_inner_likelihood (address_info &address,
address_term_info &term)
{
if (term.inner_likelihood == INNER_LIKELY)
dump_printf_loc (MSG_NOTE, address.stmt, "%T is likely to be the"
" innermost dimension\n", term.stride);
else if (term.inner_likelihood == INNER_UNLIKELY)
dump_printf_loc (MSG_NOTE, address.stmt, "%T is probably not the"
" innermost dimension\n", term.stride);
else
dump_printf_loc (MSG_NOTE, address.stmt, "cannot tell whether %T"
" is the innermost dimension\n", term.stride);
}
/* The caller has identified that STRIDE is the stride of interest
in TERM, and that the stride is applied in OP_LOOP. Record this
information in TERM, deciding whether STRIDE is likely to be for
the innermost dimension of an array and whether it represents a
versioning opportunity. ADDRESS is the address that contains TERM. */
void
loop_versioning::analyze_stride (address_info &address,
address_term_info &term,
tree stride, class loop *op_loop)
{
term.stride = stride;
term.inner_likelihood = get_inner_likelihood (stride, term.multiplier);
if (dump_enabled_p ())
dump_inner_likelihood (address, term);
/* To be a versioning opportunity we require:
- The multiplier applied by TERM is equal to the access size,
so that when STRIDE is 1, the accesses in successive loop
iterations are consecutive.
This is deliberately conservative. We could relax it to handle
other cases (such as those with gaps between iterations) if we
find any real testcases for which it's useful.
- the stride is applied in the same loop as STMT rather than
in an outer loop. Although versioning for strides applied in
outer loops could help in some cases -- such as enabling
more loop interchange -- the savings are much lower than for
inner loops.
- the stride is an SSA name that is invariant in STMT's loop,
since otherwise versioning isn't possible. */
unsigned HOST_WIDE_INT access_size = address.max_offset - address.min_offset;
if (term.multiplier == access_size
&& address.loop == op_loop
&& TREE_CODE (stride) == SSA_NAME
&& expr_invariant_in_loop_p (address.loop, stride))
{
term.versioning_opportunity_p = true;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, address.stmt, "%T == 1 is a versioning"
" opportunity\n", stride);
}
}
/* See whether address term TERM (which belongs to ADDRESS) is the result
of multiplying a varying SSA name by a loop-invariant SSA name.
Return true and update TERM if so.
This handles both cases that SCEV might handle, such as:
for (int i = 0; i < n; ++i)
res += a[i * stride];
and ones in which the term varies arbitrarily between iterations, such as:
for (int i = 0; i < n; ++i)
res += a[index[i] * stride]; */
bool
loop_versioning::find_per_loop_multiplication (address_info &address,
address_term_info &term)
{
gassign *mult = maybe_get_assign (term.expr);
if (!mult || gimple_assign_rhs_code (mult) != MULT_EXPR)
return false;
class loop *mult_loop = loop_containing_stmt (mult);
if (!loop_outer (mult_loop))
return false;
tree op1 = strip_casts (gimple_assign_rhs1 (mult));
tree op2 = strip_casts (gimple_assign_rhs2 (mult));
if (TREE_CODE (op1) != SSA_NAME || TREE_CODE (op2) != SSA_NAME)
return false;
bool invariant1_p = expr_invariant_in_loop_p (mult_loop, op1);
bool invariant2_p = expr_invariant_in_loop_p (mult_loop, op2);
if (invariant1_p == invariant2_p)
return false;
/* Make sure that the loop invariant is OP2 rather than OP1. */
if (invariant1_p)
std::swap (op1, op2);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, address.stmt, "address term %T = varying %T"
" * loop-invariant %T\n", term.expr, op1, op2);
analyze_stride (address, term, op2, mult_loop);
return true;
}
/* Try to use scalar evolutions to find an address stride for TERM,
which belongs to ADDRESS. Return true and update TERM if so.
Here we are interested in any evolution information we can find,
not just evolutions wrt ADDRESS->LOOP. For example, if we find that
an outer loop obviously iterates over the inner dimension of an array,
that information can help us eliminate worthless versioning opportunities
in inner loops. */
bool
loop_versioning::analyze_term_using_scevs (address_info &address,
address_term_info &term)
{
gimple *setter = maybe_get_stmt (term.expr);
if (!setter)
return false;
class loop *wrt_loop = loop_containing_stmt (setter);
if (!loop_outer (wrt_loop))
return false;
tree chrec = strip_casts (analyze_scalar_evolution (wrt_loop, term.expr));
if (TREE_CODE (chrec) == POLYNOMIAL_CHREC)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, address.stmt,
"address term %T = %T\n", term.expr, chrec);
/* Peel casts and accumulate constant multiplications, up to the
limit allowed by M_MAXIMUM_SCALE. */
tree stride = strip_casts (CHREC_RIGHT (chrec));
while (TREE_CODE (stride) == MULT_EXPR
&& multiply_term_by (term, TREE_OPERAND (stride, 1)))
stride = strip_casts (TREE_OPERAND (stride, 0));
gassign *assign;
while ((assign = maybe_get_assign (stride))
&& gimple_assign_rhs_code (assign) == MULT_EXPR
&& multiply_term_by (term, gimple_assign_rhs2 (assign)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, address.stmt,
"looking through %G", assign);
stride = strip_casts (gimple_assign_rhs1 (assign));
}
analyze_stride (address, term, stride, get_chrec_loop (chrec));
return true;
}
return false;
}
/* Address term TERM is an arbitrary term that provides no versioning
opportunities. Analyze it to see whether it contains any likely
inner strides, so that we don't mistakenly version for other
(less likely) candidates.
This copes with invariant innermost indices such as:
x(i, :) = 100
where the "i" component of the address is invariant in the loop
but provides the real inner stride.
ADDRESS is the address that contains TERM. */
void
loop_versioning::analyze_arbitrary_term (address_info &address,
address_term_info &term)
{
/* A multiplication offers two potential strides. Pick the one that
is most likely to be an innermost stride. */
tree expr = term.expr, alt = NULL_TREE;
gassign *mult = maybe_get_assign (expr);
if (mult && gimple_assign_rhs_code (mult) == MULT_EXPR)
{
expr = strip_casts (gimple_assign_rhs1 (mult));
alt = strip_casts (gimple_assign_rhs2 (mult));
}
term.stride = expr;
term.inner_likelihood = get_inner_likelihood (expr, term.multiplier);
if (alt)
{
inner_likelihood alt_l = get_inner_likelihood (alt, term.multiplier);
if (alt_l > term.inner_likelihood)
{
term.stride = alt;
term.inner_likelihood = alt_l;
}
}
if (dump_enabled_p ())
dump_inner_likelihood (address, term);
}
/* Try to identify loop strides in ADDRESS and try to choose realistic
versioning opportunities based on these strides.
The main difficulty here isn't finding strides that could be used
in a version check (that's pretty easy). The problem instead is to
avoid versioning for some stride S that is unlikely ever to be 1 at
runtime. Versioning for S == 1 on its own would lead to unnecessary
code bloat, while adding S == 1 to more realistic version conditions
would lose the optimisation opportunity offered by those other conditions.
For example, versioning for a stride of 1 in the Fortran code:
integer :: a(:,:)
a(1,:) = 1
is not usually a good idea, since the assignment is iterating over
an outer dimension and is relatively unlikely to have a stride of 1.
(It isn't impossible, since the inner dimension might be 1, or the
array might be transposed.) Similarly, in:
integer :: a(:,:), b(:,:)
b(:,1) = a(1,:)
b(:,1) is relatively likely to have a stride of 1 while a(1,:) isn't.
Versioning for when both strides are 1 would lose most of the benefit
of versioning for b's access.
The approach we take is as follows:
- Analyze each term to see whether it has an identifiable stride,
regardless of which loop applies the stride.
- Evaluate the likelihood that each such stride is for the innermost
dimension of an array, on the scale "likely", "don't know" or "unlikely".
- If there is a single "likely" innermost stride, and that stride is
applied in the loop that contains STMT, version the loop for when the
stride is 1. This deals with the cases in which we're fairly
confident of doing the right thing, such as the b(:,1) reference above.
- If there are no "likely" innermost strides, and the loop that contains
STMT uses a stride that we rated as "don't know", version for when
that stride is 1. This is principally used for C code such as:
for (int i = 0; i < n; ++i)
a[i * x] = ...;
and:
for (int j = 0; j < n; ++j)
for (int i = 0; i < n; ++i)
a[i * x + j * y] = ...;
where nothing in the way "x" and "y" are set gives a hint as to
whether "i" iterates over the innermost dimension of the array.
In these situations it seems reasonable to assume the
programmer has nested the loops appropriately (although of course
there are examples like GEMM in which this assumption doesn't hold
for all accesses in the loop).
This case is also useful for the Fortran equivalent of the
above C code. */
void
loop_versioning::analyze_address_fragment (address_info &address)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, address.stmt, "analyzing address fragment ");
dump_address_info (MSG_NOTE, address);
dump_printf (MSG_NOTE, "\n");
}
/* Analyze each component of the sum to see whether it involves an
apparent stride.
There is an overlap between the addresses that
find_per_loop_multiplication and analyze_term_using_scevs can handle,
but the former is much cheaper than SCEV analysis, so try it first. */
for (unsigned int i = 0; i < address.terms.length (); ++i)
if (!find_per_loop_multiplication (address, address.terms[i])
&& !analyze_term_using_scevs (address, address.terms[i])
&& !POINTER_TYPE_P (TREE_TYPE (address.terms[i].expr)))
analyze_arbitrary_term (address, address.terms[i]);
/* Check for strides that are likely to be for the innermost dimension.
1. If there is a single likely inner stride, if it is an SSA name,
and if it is worth versioning the loop for when the SSA name
equals 1, record that we want to do so.
2. Otherwise, if there any likely inner strides, bail out. This means
one of:
(a) There are multiple likely inner strides. This suggests we're
confused and be can't be confident of doing the right thing.
(b) There is a single likely inner stride and it is a constant
rather than an SSA name. This can mean either that the access
is a natural one without any variable strides, such as:
for (int i = 0; i < n; ++i)
a[i] += 1;
or that a variable stride is applied to an outer dimension,
such as:
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
a[j * stride][i] += 1;
(c) There is a single likely inner stride, and it is an SSA name,
but it isn't a worthwhile versioning opportunity. This usually
means that the variable stride is applied by an outer loop,
such as:
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
a[j][i * stride] += 1;
or (using an example with a more natural loop nesting):
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
a[i][j] += b[i * stride];
in cases where b[i * stride] cannot (yet) be hoisted for
aliasing reasons.
3. If there are no likely inner strides, fall through to the next
set of checks.
Pointer equality is enough to check for uniqueness in (1), since we
only care about SSA names. */
tree chosen_stride = NULL_TREE;
tree version_stride = NULL_TREE;
for (unsigned int i = 0; i < address.terms.length (); ++i)
if (chosen_stride != address.terms[i].stride
&& address.terms[i].inner_likelihood == INNER_LIKELY)
{
if (chosen_stride)
return;
chosen_stride = address.terms[i].stride;
if (address.terms[i].versioning_opportunity_p)
version_stride = chosen_stride;
}
/* If there are no likely inner strides, see if there is a single
versioning opportunity for a stride that was rated as INNER_DONT_KNOW.
See the comment above the function for the cases that this code
handles. */
if (!chosen_stride)
for (unsigned int i = 0; i < address.terms.length (); ++i)
if (version_stride != address.terms[i].stride
&& address.terms[i].inner_likelihood == INNER_DONT_KNOW
&& address.terms[i].versioning_opportunity_p)
{
if (version_stride)
return;
version_stride = address.terms[i].stride;
}
if (version_stride)
version_for_unity (address.stmt, version_stride);
}
/* Treat EXPR * MULTIPLIER + OFFSET as a fragment of an address that addresses
TYPE_SIZE bytes and record this address fragment for later processing.
STMT is the statement that contains the address. */
void
loop_versioning::record_address_fragment (gimple *stmt,
unsigned HOST_WIDE_INT type_size,
tree expr,
unsigned HOST_WIDE_INT multiplier,
HOST_WIDE_INT offset)
{
/* We're only interested in computed values. */
if (TREE_CODE (expr) != SSA_NAME)
return;
/* Quick exit if no part of the address is calculated in STMT's loop,
since such addresses have no versioning opportunities. */
class loop *loop = loop_containing_stmt (stmt);
if (expr_invariant_in_loop_p (loop, expr))
return;
/* Set up an address_info for EXPR * MULTIPLIER. */
address_info *address = XOBNEW (&m_obstack, address_info);
new (address) address_info;
address->stmt = stmt;
address->loop = loop;
address->base = NULL_TREE;
address->terms.quick_grow (1);
address->terms[0].expr = expr;
address->terms[0].multiplier = multiplier;
address->terms[0].stride = NULL_TREE;
address->terms[0].inner_likelihood = INNER_UNLIKELY;
address->terms[0].versioning_opportunity_p = false;
address->min_offset = offset;
/* Peel apart the expression into a sum of address_terms, where each
term is multiplied by a constant. Treat a + b and a - b the same,
since it doesn't matter for our purposes whether an address is
increasing or decreasing. Distribute (a + b) * constant into
a * constant + b * constant.
We don't care which loop each term belongs to, since we want to
examine as many candidate strides as possible when determining
which is likely to be for the innermost dimension. We therefore
don't limit the search to statements in STMT's loop. */
for (unsigned int i = 0; i < address->terms.length (); )
{
if (gassign *assign = maybe_get_assign (address->terms[i].expr))
{
tree_code code = gimple_assign_rhs_code (assign);
if (code == PLUS_EXPR
|| code == POINTER_PLUS_EXPR
|| code == MINUS_EXPR)
{
tree op1 = gimple_assign_rhs1 (assign);
tree op2 = gimple_assign_rhs2 (assign);
if (TREE_CODE (op2) == INTEGER_CST)
{
address->terms[i].expr = strip_casts (op1);
/* This is heuristic only, so don't worry about truncation
or overflow. */
address->min_offset += (TREE_INT_CST_LOW (op2)
* address->terms[i].multiplier);
continue;
}
else if (address->terms.length () < address_info::MAX_TERMS)
{
unsigned int j = address->terms.length ();
address->terms.quick_push (address->terms[i]);
address->terms[i].expr = strip_casts (op1);
address->terms[j].expr = strip_casts (op2);
continue;
}
}
if (code == MULT_EXPR)
{
tree op1 = gimple_assign_rhs1 (assign);
tree op2 = gimple_assign_rhs2 (assign);
if (multiply_term_by (address->terms[i], op2))
{
address->terms[i].expr = strip_casts (op1);
continue;
}
}
if (CONVERT_EXPR_CODE_P (code))
{
tree op1 = gimple_assign_rhs1 (assign);
address->terms[i].expr = strip_casts (op1);
continue;
}
}
i += 1;
}
/* Peel off any symbolic pointer. */
if (TREE_CODE (address->terms[0].expr) != SSA_NAME
&& address->terms[0].multiplier == 1)
{
if (address->terms.length () == 1)
{
obstack_free (&m_obstack, address);
return;
}
address->base = address->terms[0].expr;
address->terms.ordered_remove (0);
}
/* Require all remaining terms to be SSA names. (This could be false
for unfolded statements, but they aren't worth dealing with.) */
for (unsigned int i = 0; i < address->terms.length (); ++i)
if (TREE_CODE (address->terms[i].expr) != SSA_NAME)
{
obstack_free (&m_obstack, address);
return;
}
/* The loop above set MIN_OFFSET based on the first byte of the
referenced data. Calculate the end + 1. */
address->max_offset = address->min_offset + type_size;
/* Put the terms into a canonical order for the hash table lookup below. */
address->terms.qsort (compare_address_terms);
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, stmt, "recording address fragment %T", expr);
if (multiplier != 1)
dump_printf (MSG_NOTE, " * %wd", multiplier);
dump_printf (MSG_NOTE, " = ");
dump_address_info (MSG_NOTE, *address);
dump_printf (MSG_NOTE, "\n");
}
/* Pool address information with the same terms (but potentially
different offsets). */
address_info **slot = m_address_table.find_slot (address, INSERT);
if (address_info *old_address = *slot)
{
/* We've already seen an address with the same terms. Extend the
offset range to account for this access. Doing this can paper
over gaps, such as in:
a[i * stride * 4] + a[i * stride * 4 + 3];
where nothing references "+ 1" or "+ 2". However, the vectorizer
handles such gapped accesses without problems, so it's not worth
trying to exclude them. */
if (old_address->min_offset > address->min_offset)
old_address->min_offset = address->min_offset;
if (old_address->max_offset < address->max_offset)
old_address->max_offset = address->max_offset;
obstack_free (&m_obstack, address);
}
else
{
/* This is the first time we've seen an address with these terms. */
*slot = address;
m_address_list.safe_push (address);
}
}
/* Analyze expression EXPR, which occurs in STMT. */
void
loop_versioning::analyze_expr (gimple *stmt, tree expr)
{
unsigned HOST_WIDE_INT type_size;
while (handled_component_p (expr))
{
/* See whether we can use versioning to avoid a multiplication
in an array index. */
if (TREE_CODE (expr) == ARRAY_REF
&& acceptable_type_p (TREE_TYPE (expr), &type_size))
record_address_fragment (stmt, type_size,
TREE_OPERAND (expr, 1), type_size, 0);
expr = TREE_OPERAND (expr, 0);
}
/* See whether we can use versioning to avoid a multiplication
in the pointer calculation of a MEM_REF. */
if (TREE_CODE (expr) == MEM_REF
&& acceptable_type_p (TREE_TYPE (expr), &type_size))
record_address_fragment (stmt, type_size, TREE_OPERAND (expr, 0), 1,
/* This is heuristic only, so don't worry
about truncation or overflow. */
TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)));
/* These would be easy to handle if they existed at this stage. */
gcc_checking_assert (TREE_CODE (expr) != TARGET_MEM_REF);
}
/* Analyze all the statements in BB looking for useful version checks.
Return true on success, false if something prevents the block from
being versioned. */
bool
loop_versioning::analyze_block (basic_block bb)
{
class loop *loop = bb->loop_father;
loop_info &li = get_loop_info (loop);
for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
gsi_next (&gsi))
{
gimple *stmt = gsi_stmt (gsi);
if (is_gimple_debug (stmt))
continue;
if (expensive_stmt_p (stmt))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, stmt, "expensive statement"
" prevents versioning: %G", stmt);
return false;
}
/* Only look for direct versioning opportunities in inner loops
since the benefit tends to be much smaller for outer loops. */
if (!loop->inner)
{
unsigned int nops = gimple_num_ops (stmt);
for (unsigned int i = 0; i < nops; ++i)
if (tree op = gimple_op (stmt, i))
analyze_expr (stmt, op);
}
/* The point of the instruction limit is to prevent excessive
code growth, so this is a size-based estimate even though
the optimization is aimed at speed. */
li.num_insns += estimate_num_insns (stmt, &eni_size_weights);
}
return true;
}
/* Analyze all the blocks in the function, looking for useful version checks.
Return true if we found one. */
bool
loop_versioning::analyze_blocks ()
{
AUTO_DUMP_SCOPE ("analyze_blocks",
dump_user_location_t::from_function_decl (m_fn->decl));
/* For now we don't try to version the whole function, although
versioning at that level could be useful in some cases. */
get_loop_info (get_loop (m_fn, 0)).rejected_p = true;
class loop *loop;
FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
{
loop_info &linfo = get_loop_info (loop);
/* Ignore cold loops. */
if (!optimize_loop_for_speed_p (loop))
linfo.rejected_p = true;
/* See whether an inner loop prevents versioning of this loop. */
if (!linfo.rejected_p)
for (class loop *inner = loop->inner; inner; inner = inner->next)
if (get_loop_info (inner).rejected_p)
{
linfo.rejected_p = true;
break;
}
/* If versioning the loop is still a possibility, examine the
statements in the loop to look for versioning opportunities. */
if (!linfo.rejected_p)
{
void *start_point = obstack_alloc (&m_obstack, 0);
for (basic_block bb = linfo.block_list; bb;
bb = m_next_block_in_loop[bb->index])
if (!analyze_block (bb))
{
linfo.rejected_p = true;
break;
}
if (!linfo.rejected_p)
{
/* Process any queued address fragments, now that we have
complete grouping information. */
address_info *address;
unsigned int i;
FOR_EACH_VEC_ELT (m_address_list, i, address)
analyze_address_fragment (*address);
}
m_address_table.empty ();
m_address_list.truncate (0);
obstack_free (&m_obstack, start_point);
}
}
return m_num_conditions != 0;
}
/* Use the ranges in VRS to remove impossible versioning conditions from
LOOP. */
void
loop_versioning::prune_loop_conditions (class loop *loop, vr_values *vrs)
{
loop_info &li = get_loop_info (loop);
int to_remove = -1;
bitmap_iterator bi;
unsigned int i;
EXECUTE_IF_SET_IN_BITMAP (&li.unity_names, 0, i, bi)
{
tree name = ssa_name (i);
const value_range_equiv *vr = vrs->get_value_range (name);
if (vr && !vr->may_contain_p (build_one_cst (TREE_TYPE (name))))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, find_loop_location (loop),
"%T can never be 1 in this loop\n", name);
if (to_remove >= 0)
bitmap_clear_bit (&li.unity_names, to_remove);
to_remove = i;
m_num_conditions -= 1;
}
}
if (to_remove >= 0)
bitmap_clear_bit (&li.unity_names, to_remove);
}
/* Remove any scheduled loop version conditions that will never be true.
Return true if any remain. */
bool
loop_versioning::prune_conditions ()
{
AUTO_DUMP_SCOPE ("prune_loop_conditions",
dump_user_location_t::from_function_decl (m_fn->decl));
calculate_dominance_info (CDI_DOMINATORS);
lv_dom_walker dom_walker (*this);
dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (m_fn));
return m_num_conditions != 0;
}
/* Merge the version checks for INNER into immediately-enclosing loop
OUTER. */
void
loop_versioning::merge_loop_info (class loop *outer, class loop *inner)
{
loop_info &inner_li = get_loop_info (inner);
loop_info &outer_li = get_loop_info (outer);
if (dump_enabled_p ())
{
bitmap_iterator bi;
unsigned int i;
EXECUTE_IF_SET_IN_BITMAP (&inner_li.unity_names, 0, i, bi)
if (!bitmap_bit_p (&outer_li.unity_names, i))
dump_printf_loc (MSG_NOTE, find_loop_location (inner),
"hoisting check that %T == 1 to outer loop\n",
ssa_name (i));
}
bitmap_ior_into (&outer_li.unity_names, &inner_li.unity_names);
if (loop_depth (outer_li.outermost) < loop_depth (inner_li.outermost))
outer_li.outermost = inner_li.outermost;
}
/* Add LOOP to the queue of loops to version. */
void
loop_versioning::add_loop_to_queue (class loop *loop)
{
loop_info &li = get_loop_info (loop);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, find_loop_location (loop),
"queuing this loop for versioning\n");
m_loops_to_version.safe_push (loop);
/* Don't try to version superloops. */
li.rejected_p = true;
}
/* Decide whether the cost model would allow us to version LOOP,
either directly or as part of a parent loop, and return true if so.
This does not imply that the loop is actually worth versioning in its
own right, just that it would be valid to version it if something
benefited.
We have already made this decision for all inner loops of LOOP. */
bool
loop_versioning::decide_whether_loop_is_versionable (class loop *loop)
{
loop_info &li = get_loop_info (loop);
if (li.rejected_p)
return false;
/* Examine the decisions made for inner loops. */
for (class loop *inner = loop->inner; inner; inner = inner->next)
{
loop_info &inner_li = get_loop_info (inner);
if (inner_li.rejected_p)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, find_loop_location (loop),
"not versioning this loop because one of its"
" inner loops should not be versioned\n");
return false;
}
if (inner_li.worth_versioning_p ())
li.subloops_benefit_p = true;
/* Accumulate the number of instructions from subloops that are not
the innermost, or that don't benefit from versioning. Only the
instructions from innermost loops that benefit from versioning
should be weighed against loop-versioning-max-inner-insns;
everything else should be weighed against
loop-versioning-max-outer-insns. */
if (!inner_li.worth_versioning_p () || inner->inner)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, find_loop_location (loop),
"counting %d instructions from this loop"
" against its parent loop\n", inner_li.num_insns);
li.num_insns += inner_li.num_insns;
}
}
/* Enforce the size limits. */
if (li.worth_versioning_p ())
{
unsigned int max_num_insns = max_insns_for_loop (loop);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, find_loop_location (loop),
"this loop has %d instructions, against"
" a versioning limit of %d\n",
li.num_insns, max_num_insns);
if (li.num_insns > max_num_insns)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION
| MSG_PRIORITY_USER_FACING,
find_loop_location (loop),
"this loop is too big to version");
return false;
}
}
/* Hoist all version checks from subloops to this loop. */
for (class loop *subloop = loop->inner; subloop; subloop = subloop->next)
merge_loop_info (loop, subloop);
return true;
}
/* Decide which loops to version and add them to the versioning queue.
Return true if there are any loops to version. */
bool
loop_versioning::make_versioning_decisions ()
{
AUTO_DUMP_SCOPE ("make_versioning_decisions",
dump_user_location_t::from_function_decl (m_fn->decl));
class loop *loop;
FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
{
loop_info &linfo = get_loop_info (loop);
if (decide_whether_loop_is_versionable (loop))
{
/* Commit to versioning LOOP directly if we can't hoist the
version checks any further. */
if (linfo.worth_versioning_p ()
&& (loop_depth (loop) == 1 || linfo.outermost == loop))
add_loop_to_queue (loop);
}
else
{
/* We can't version this loop, so individually version any
subloops that would benefit and haven't been versioned yet. */
linfo.rejected_p = true;
for (class loop *subloop = loop->inner; subloop;
subloop = subloop->next)
if (get_loop_info (subloop).worth_versioning_p ())
add_loop_to_queue (subloop);
}
}
return !m_loops_to_version.is_empty ();
}
/* Attempt to implement loop versioning for LOOP, using the information
cached in the associated loop_info. Return true on success. */
bool
loop_versioning::version_loop (class loop *loop)
{
loop_info &li = get_loop_info (loop);
/* Build up a condition that selects the original loop instead of
the simplified loop. */
tree cond = boolean_false_node;
bitmap_iterator bi;
unsigned int i;
EXECUTE_IF_SET_IN_BITMAP (&li.unity_names, 0, i, bi)
{
tree name = ssa_name (i);
tree ne_one = fold_build2 (NE_EXPR, boolean_type_node, name,
build_one_cst (TREE_TYPE (name)));
cond = fold_build2 (TRUTH_OR_EXPR, boolean_type_node, cond, ne_one);
}
/* Convert the condition into a suitable gcond. */
gimple_seq stmts = NULL;
cond = force_gimple_operand_1 (cond, &stmts, is_gimple_condexpr, NULL_TREE);
/* Version the loop. */
initialize_original_copy_tables ();
basic_block cond_bb;
li.optimized_loop = loop_version (loop, cond, &cond_bb,
profile_probability::unlikely (),
profile_probability::likely (),
profile_probability::unlikely (),
profile_probability::likely (), true);
free_original_copy_tables ();
if (!li.optimized_loop)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, find_loop_location (loop),
"tried but failed to version this loop for when"
" certain strides are 1\n");
return false;
}
if (dump_enabled_p ())
dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, find_loop_location (loop),
"versioned this loop for when certain strides are 1\n");
/* Insert the statements that feed COND. */
if (stmts)
{
gimple_stmt_iterator gsi = gsi_last_bb (cond_bb);
gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
}
return true;
}
/* Attempt to version all loops in the versioning queue. */
void
loop_versioning::implement_versioning_decisions ()
{
/* No AUTO_DUMP_SCOPE here since all messages are top-level and
user-facing at this point. */
bool any_succeeded_p = false;
class loop *loop;
unsigned int i;
FOR_EACH_VEC_ELT (m_loops_to_version, i, loop)
if (version_loop (loop))
any_succeeded_p = true;
if (!any_succeeded_p)
return;
update_ssa (TODO_update_ssa);
/* Simplify the new loop, which is used when COND is false. */
FOR_EACH_VEC_ELT (m_loops_to_version, i, loop)
{
loop_info &linfo = get_loop_info (loop);
if (linfo.optimized_loop)
name_prop (linfo).substitute_and_fold (linfo.optimized_loop->header);
}
}
/* Run the pass and return a set of TODO_* flags. */
unsigned int
loop_versioning::run ()
{
gcc_assert (scev_initialized_p ());
if (analyze_blocks ()
&& prune_conditions ()
&& make_versioning_decisions ())
implement_versioning_decisions ();
return 0;
}
/* Loop versioning pass. */
const pass_data pass_data_loop_versioning =
{
GIMPLE_PASS, /* type */
"lversion", /* name */
OPTGROUP_LOOP, /* optinfo_flags */
TV_LOOP_VERSIONING, /* tv_id */
PROP_cfg, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
0, /* todo_flags_finish */
};
class pass_loop_versioning : public gimple_opt_pass
{
public:
pass_loop_versioning (gcc::context *ctxt)
: gimple_opt_pass (pass_data_loop_versioning, ctxt)
{}
/* opt_pass methods: */
virtual bool gate (function *) { return flag_version_loops_for_strides; }
virtual unsigned int execute (function *);
};
unsigned int
pass_loop_versioning::execute (function *fn)
{
if (number_of_loops (fn) <= 1)
return 0;
return loop_versioning (fn).run ();
}
} // anon namespace
gimple_opt_pass *
make_pass_loop_versioning (gcc::context *ctxt)
{
return new pass_loop_versioning (ctxt);
}
|
/*
Servo253.cpp - Servo library for Arduino & Wiring
Modified to operate using Timer2. Jon Nakane, 2009 April
Based on Hernando Barragan's original C implementation
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
version by Jon Nakane (jnakane@physics.ubc.ca) to try to convert to Timer2 to avoid
conflicts with Timer3 and the PWM outputs. There was substantial jitter when both the PWM outputs
and servo motors were activated.
*/
#include "WProgram.h"
extern "C" {
// #include <stdio.h>
// #include <inttypes.h>
// #include <avr/interrupt.h>
// #include <avr/pgmspace.h>
// #include <stdio.h>
// #include <stdarg.h>
// #include <math.h>
// #include "WConstants.h"
extern void pinMode(uint8_t, uint8_t);
extern uint8_t digitalRead(uint8_t);
extern void digitalWrite(uint8_t, uint8_t);
extern void timer2Init(void);
extern void timer2SetPrescaler(uint8_t);
extern void timerAttach(uint8_t, void(*)(void));
extern void timerDetach(uint8_t);
}
#include "Servo253.h"
// USEFUL DEFINITIONS //////////////////////////////////////////////////////////
/*
ideally
62500 steps in one sec
62.5 steps in one ms
1250 steps in 20 ms = servo period
56.25 min amount of servo steps
131.25 max amount of servo steps
*/
// in reality
//#define SERVO_MINIMUM 10
//#define SERVO_MAXIMUM 40
//#define SERVO_PERIOD 2600
//#define SERVO_MINIMUM 40
//#define SERVO_MAXIMUM 158
//#define SERVO_PERIOD 1300
#define SERVO_MINIMUM 10
#define SERVO_MAXIMUM 40
#define SERVO_PERIOD 500
// Initialize Class Variables //////////////////////////////////////////////////
Servo253* Servo253::_servos[8];
uint8_t Servo253::_count = 0;
int8_t Servo253::_current = -1;
uint16_t Servo253::_positionTicks = 0;
// Constructors ////////////////////////////////////////////////////////////////
Servo253::Servo253()
{
_index = 0;
_duty = SERVO_MINIMUM;
}
// Public Methods //////////////////////////////////////////////////////////////
uint8_t Servo253::attach(int pin)
{
// if list is already full, return a failure
if(8 < _count){
return 0;
}
// record pin number, set pin to output
pinMode(_pin = pin, OUTPUT);
// if already in list, return a success
if(this == _servos[_index]){
return 1;
}
// if first servo, ready the list
if(0 == _count){
for(uint8_t i = 0; i < 8; ++i){
_servos[i] = NULL;
}
}
// find empty slot, add servo to list
for(uint8_t i = 0; i < 8; ++i){
if(NULL == _servos[i]){
_servos[i] = this;
_index = i;
++_count;
break;
}
}
// init servos if this is the first
if(1 == _count){
start();
}
// return a success
return 1;
}
void Servo253::detach()
{
// if already in list
if(this == _servos[_index]){
// remove from list
_servos[_index] = NULL;
// adjust count and end timer if this was last servo
if(0 < _count){
--_count;
if(0 == _count){
end();
}
}
}
}
void Servo253::write(int angle)
{
// scale position
// position is scaled according to the max and min of servo position
uint16_t position = (uint16_t)(SERVO_MINIMUM + (((float)angle / 180) * (SERVO_MAXIMUM - SERVO_MINIMUM)));
// bind to limits
position = max(position, SERVO_MINIMUM);
position = min(position, SERVO_MAXIMUM);
// set position
_duty = position;
}
uint8_t Servo253::read()
{
return (uint8_t)(((float)(_duty - SERVO_MINIMUM) / (SERVO_MAXIMUM - SERVO_MINIMUM)) * 180);
}
uint8_t Servo253::attached()
{
if(this == _servos[_index]){
return 1;
}
return 0;
}
// Private Methods /////////////////////////////////////////////////////////////
void Servo253::end()
{
//digitalWrite(48, LOW);
// disable the timer2 output compare interrupt
TIMSK &= ~_BV(OCIE2);
timerDetach(TIMER2OUTCOMPARE_INT);
}
void Servo253::start()
{
//digitalWrite(48, HIGH);
timer2Init();
// disble timer2 output compare interrupt
TIMSK &= ~_BV(OCIE2);
// set the prescaler for timer2
timer2SetPrescaler(TIMER_CLK_DIV1024);
//timer2SetPrescaler(TIMER_CLK_DIV256);
// attach the software PWM service routine to timer2 output compare
timerAttach(TIMER2OUTCOMPARE_INT, service);
///TIMER2_OVF_vect
// update output compare register
OCR2 += SERVO_PERIOD;
// enable the timer2 output compare interrupt
TIMSK |= _BV(OCIE2);
// reset position ticks
_positionTicks = 0;
// reset current servo
_current = -1;
}
void Servo253::service()
{
uint16_t ticks;
// turn off current servo, if not "non servo"
if(0 <= _current){
digitalWrite(_servos[_current]->_pin, LOW);
}
// advance to next servo
while(_current < 7){
if(NULL != _servos[++_current]){
break;
}
}
// if current is not a servo
if(NULL == _servos[_current]){
// reset and wait out the period
_current = -1;
ticks = SERVO_PERIOD - _positionTicks;
}else{
// turn on new servo
digitalWrite(_servos[_current]->_pin, HIGH);
// schedule ttl
ticks = _servos[_current]->_duty;
}
// schedule next interrupt
OCR2 += ticks;
// keep track of this period
_positionTicks += ticks;
if(_positionTicks >= SERVO_PERIOD){
_positionTicks = 0;
}
}
|
#include "catch.hpp"
#include "Chip8.hpp"
#include <iostream>
TEST_CASE("OPCODE 00E0", "[opcode]")
{
Chip8 chip8;
chip8.opcode = 0x00E0;
memset(chip8.video, 0xFF, sizeof(chip8.video));
chip8.ExecuteOpcode();
bool allZero = true;
for (int i = 0; i < CHIP8_VIDEO_WIDTH * CHIP8_VIDEO_HEIGHT; ++i)
if (chip8.video[i] != 0) {
allZero = false;
break;
}
REQUIRE(allZero == true);
}
TEST_CASE("OPCODE 00EE", "[opcode]")
{
Chip8 chip8;
chip8.opcode = 0x00EE;
chip8.PC = 0x240;
chip8.SP = 3;
chip8.stack[3] = 0x220;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x220);
REQUIRE(chip8.SP == 2);
}
TEST_CASE("OPCODE 1NNN", "[opcode]")
{
Chip8 chip8;
chip8.opcode = 0x1234;
chip8.PC = 0x0300;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0234);
}
TEST_CASE("OPCODE 2NNN", "[opcode]")
{
Chip8 chip8;
chip8.opcode = 0x2345;
chip8.PC = 0x0200;
chip8.SP = 2;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0345);
REQUIRE(chip8.SP == 3);
REQUIRE(chip8.stack[chip8.SP] == 0x0200);
}
TEST_CASE("OPCODE 3XKK", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0x3;
chip8.opcode = 0x3201;
chip8.PC = 0x0300;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0300);
chip8.V[2] = 0x1;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0302);
}
TEST_CASE("OPCODE 4XKK", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0x3;
chip8.opcode = 0x4201;
chip8.PC = 0x0300;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0302);
chip8.V[2] = 0x1;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0302);
}
TEST_CASE("OPCODE 5XY0", "[opcode]")
{
Chip8 chip8;
chip8.V[3] = 3;
chip8.V[4] = 4;
chip8.opcode = 0x5340;
chip8.PC = 0x0300;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0300);
chip8.V[3] = 4;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0302);
}
TEST_CASE("OPCODE 6XKK", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.opcode = 0x62AA;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0xAA);
}
TEST_CASE("OPCODE 7XKK", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.opcode = 0x72A0;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0xA0 + 2);
}
TEST_CASE("OPCODE 8XY0", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.V[3] = 3;
chip8.opcode = 0x8230;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == chip8.V[3]);
}
TEST_CASE("OPCODE 8XY1", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0xAA;
chip8.V[3] = 0x55;
chip8.opcode = 0x8231;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0xFF);
}
TEST_CASE("OPCODE 8XY2", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0xAA;
chip8.V[3] = 0x55;
chip8.opcode = 0x8232;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0x00);
}
TEST_CASE("OPCODE 8XY3", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0x94;
chip8.V[3] = 0xD6;
chip8.opcode = 0x8233;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0x42);
}
TEST_CASE("OPCODE 8XY4", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.V[3] = 3;
chip8.opcode = 0x8234;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 5);
REQUIRE(chip8.V[0xF] == 0);
chip8.V[2] = 0xDE;
chip8.V[3] = 0xAD;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0x8B);
REQUIRE(chip8.V[0xF] == 1);
}
TEST_CASE("OPCODE 8XY5", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.V[3] = 3;
chip8.opcode = 0x8235;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0xFF);
REQUIRE(chip8.V[0xF] == 0);
chip8.V[2] = 3;
chip8.V[3] = 2;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 1);
REQUIRE(chip8.V[0xF] == 1);
}
TEST_CASE("OPCODE 8XY6", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 5;
chip8.opcode = 0x8206;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 2);
REQUIRE(chip8.V[0xF] == 1);
chip8.V[2] = 6;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 3);
REQUIRE(chip8.V[0xF] == 0);
}
TEST_CASE("OPCODE 8XY7", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.V[3] = 3;
chip8.opcode = 0x8237;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 1);
REQUIRE(chip8.V[0xF] == 1);
chip8.V[2] = 3;
chip8.V[3] = 2;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0xFF);
REQUIRE(chip8.V[0xF] == 0);
}
TEST_CASE("OPCODE 8XYE", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.opcode = 0x820E;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 4);
REQUIRE(chip8.V[0xF] == 0);
chip8.V[2] = 0xA0;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0x40);
REQUIRE(chip8.V[0xF] == 1);
}
TEST_CASE("OPCODE 9XY0", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 2;
chip8.V[3] = 2;
chip8.PC = 0x0300;
chip8.opcode = 0x9230;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0300);
chip8.V[3] = 3;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0302);
}
TEST_CASE("OPCODE ANNN", "[opcode]")
{
Chip8 chip8;
chip8.I = 0x0100;
chip8.opcode = 0xA123;
chip8.ExecuteOpcode();
REQUIRE(chip8.I == 0x0123);
}
TEST_CASE("OPCODE BNNN", "[opcode]")
{
Chip8 chip8;
chip8.PC = 0x0300;
chip8.V[0] = 0x20;
chip8.opcode = 0xB400;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0420);
}
TEST_CASE("OPCODE DXYN", "[opcode]")
{
// Draw a "1" sprite and check the video memory
uint8_t spriteAddress = CHIP8_FONTSET_START + 5;
uint8_t posX = 0x2;
uint8_t posY = 0x3;
Chip8 chip8;
chip8.V[2] = posX;
chip8.V[3] = posY;
chip8.I = spriteAddress;
chip8.opcode = 0xD235;
chip8.ExecuteOpcode();
for (uint8_t i = posY; i < posY + 5; ++i) {
uint8_t videoByte = 0;
for (uint8_t j = posX; j < posX + 8; ++j) {
videoByte =
(videoByte << 1) | chip8.video[i * CHIP8_VIDEO_WIDTH + j];
}
REQUIRE(videoByte == chip8.memory[spriteAddress + (i - posY)]);
}
REQUIRE(chip8.V[0xF] == 0);
chip8.ExecuteOpcode();
REQUIRE(chip8.V[0xF] == 1);
}
TEST_CASE("OPCODE EX9E", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 1;
chip8.PC = 0x0300;
chip8.opcode = 0xE29E;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0300);
chip8.keypad[1] = 1;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0302);
}
TEST_CASE("OPCODE EXA1", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 1;
chip8.keypad[1] = 1;
chip8.PC = 0x0300;
chip8.opcode = 0xE2A1;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0300);
chip8.keypad[1] = 0;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0302);
}
TEST_CASE("OPCODE FX07", "[opcode]")
{
Chip8 chip8;
chip8.delayTimer = 0x66;
chip8.opcode = 0xF207;
chip8.ExecuteOpcode();
REQUIRE(chip8.V[2] == 0x66);
}
TEST_CASE("OPCODE FX0A", "[opcode]")
{
Chip8 chip8;
chip8.PC = 0x0302;
chip8.opcode = 0xF20A;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0300);
chip8.keypad[0xA] = 1;
chip8.keypad[0xF] = 1;
chip8.ExecuteOpcode();
REQUIRE(chip8.PC == 0x0300);
REQUIRE(chip8.V[2] == 0x0A);
}
TEST_CASE("OPCODE FX15", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0x66;
chip8.opcode = 0xF215;
chip8.ExecuteOpcode();
REQUIRE(chip8.delayTimer == 0x66);
}
TEST_CASE("OPCODE FX18", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0x66;
chip8.opcode = 0xF218;
chip8.ExecuteOpcode();
REQUIRE(chip8.soundTimer == 0x66);
}
TEST_CASE("OPCODE FX1E", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0x02;
chip8.I = 0x0100;
chip8.opcode = 0xF21E;
chip8.ExecuteOpcode();
REQUIRE(chip8.I == 0x0102);
}
TEST_CASE("OPCODE FX29", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 0x02;
chip8.opcode = 0xF229;
chip8.ExecuteOpcode();
REQUIRE(chip8.I == CHIP8_FONTSET_START + 10);
}
TEST_CASE("OPCODE FX33", "[opcode]")
{
Chip8 chip8;
chip8.V[2] = 123;
chip8.I = 0x0400;
chip8.opcode = 0xF233;
chip8.ExecuteOpcode();
REQUIRE(chip8.memory[chip8.I] == 1);
REQUIRE(chip8.memory[chip8.I + 1] == 2);
REQUIRE(chip8.memory[chip8.I + 2] == 3);
}
TEST_CASE("OPCODE FX55", "[opcode]")
{
Chip8 chip8;
chip8.V[0] = 0xDE;
chip8.V[1] = 0xAD;
chip8.V[2] = 0xBE;
chip8.V[3] = 0xEF;
chip8.I = 0x0300;
chip8.opcode = 0xF355;
chip8.ExecuteOpcode();
REQUIRE(chip8.I == 0x0304);
REQUIRE(chip8.memory[0x0300] == 0xDE);
REQUIRE(chip8.memory[0x0301] == 0xAD);
REQUIRE(chip8.memory[0x0302] == 0xBE);
REQUIRE(chip8.memory[0x0303] == 0xEF);
}
TEST_CASE("OPCODE FX65", "[opcode]")
{
Chip8 chip8;
chip8.memory[0x0300] = 0xDE;
chip8.memory[0x0301] = 0xAD;
chip8.memory[0x0302] = 0xBE;
chip8.memory[0x0303] = 0xEF;
chip8.I = 0x0300;
chip8.opcode = 0xF365;
chip8.ExecuteOpcode();
REQUIRE(chip8.I == 0x0304);
REQUIRE(chip8.V[0] == 0xDE);
REQUIRE(chip8.V[1] == 0xAD);
REQUIRE(chip8.V[2] == 0xBE);
REQUIRE(chip8.V[3] == 0xEF);
}
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/leak_detection/leak_detection_request.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "components/password_manager/core/browser/leak_detection/leak_detection_api.pb.h"
#include "components/password_manager/core/browser/leak_detection/leak_detection_delegate_interface.h"
#include "components/password_manager/core/browser/leak_detection/single_lookup_response.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace password_manager {
namespace {
constexpr char kAccessToken[] = "access_token";
constexpr char kUsernameHash[] = "ABC";
constexpr char kEncryptedPayload[] = "dfughidsgfr56";
using ::testing::Eq;
using ::testing::IsNull;
class LeakDetectionRequestTest : public testing::Test {
public:
~LeakDetectionRequestTest() override = default;
base::test::TaskEnvironment& task_env() { return task_env_; }
base::HistogramTester& histogram_tester() { return histogram_tester_; }
network::TestURLLoaderFactory* test_url_loader_factory() {
return &test_url_loader_factory_;
}
LeakDetectionRequest& request() { return request_; }
private:
base::test::TaskEnvironment task_env_;
base::HistogramTester histogram_tester_;
network::TestURLLoaderFactory test_url_loader_factory_;
LeakDetectionRequest request_;
};
TEST_F(LeakDetectionRequestTest, ServerError) {
test_url_loader_factory()->AddResponse(
LeakDetectionRequest::kLookupSingleLeakEndpoint, "",
net::HTTP_INTERNAL_SERVER_ERROR);
base::MockCallback<LeakDetectionRequest::LookupSingleLeakCallback> callback;
request().LookupSingleLeak(test_url_loader_factory(), kAccessToken,
{kUsernameHash, kEncryptedPayload},
callback.Get());
EXPECT_CALL(callback,
Run(IsNull(), Eq(LeakDetectionError::kInvalidServerResponse)));
task_env().RunUntilIdle();
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.LookupSingleLeakResponseResult",
LeakDetectionRequest::LeakLookupResponseResult::kFetchError, 1);
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.HttpResponseCode",
net::HTTP_INTERNAL_SERVER_ERROR, 1);
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.NetErrorCode",
-net::ERR_HTTP_RESPONSE_CODE_FAILURE, 1);
}
TEST_F(LeakDetectionRequestTest, QuotaLimit) {
test_url_loader_factory()->AddResponse(
LeakDetectionRequest::kLookupSingleLeakEndpoint, "",
net::HTTP_TOO_MANY_REQUESTS);
base::MockCallback<LeakDetectionRequest::LookupSingleLeakCallback> callback;
request().LookupSingleLeak(test_url_loader_factory(), kAccessToken,
{kUsernameHash, kEncryptedPayload},
callback.Get());
EXPECT_CALL(callback, Run(IsNull(), Eq(LeakDetectionError::kQuotaLimit)));
task_env().RunUntilIdle();
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.LookupSingleLeakResponseResult",
LeakDetectionRequest::LeakLookupResponseResult::kFetchError, 1);
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.HttpResponseCode",
net::HTTP_TOO_MANY_REQUESTS, 1);
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.NetErrorCode",
-net::ERR_HTTP_RESPONSE_CODE_FAILURE, 1);
}
TEST_F(LeakDetectionRequestTest, MalformedServerResponse) {
static constexpr base::StringPiece kMalformedResponse = "\x01\x02\x03";
test_url_loader_factory()->AddResponse(
LeakDetectionRequest::kLookupSingleLeakEndpoint,
std::string(kMalformedResponse));
base::MockCallback<LeakDetectionRequest::LookupSingleLeakCallback> callback;
request().LookupSingleLeak(test_url_loader_factory(), kAccessToken,
{kUsernameHash, kEncryptedPayload},
callback.Get());
EXPECT_CALL(callback,
Run(IsNull(), Eq(LeakDetectionError::kInvalidServerResponse)));
task_env().RunUntilIdle();
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.LookupSingleLeakResponseResult",
LeakDetectionRequest::LeakLookupResponseResult::kParseError, 1);
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.SingleLeakResponseSize",
kMalformedResponse.size(), 1);
}
TEST_F(LeakDetectionRequestTest, WellformedServerResponse) {
google::internal::identity::passwords::leak::check::v1::
LookupSingleLeakResponse response;
std::string response_string = response.SerializeAsString();
test_url_loader_factory()->AddResponse(
LeakDetectionRequest::kLookupSingleLeakEndpoint, response_string);
base::MockCallback<LeakDetectionRequest::LookupSingleLeakCallback> callback;
request().LookupSingleLeak(test_url_loader_factory(), kAccessToken,
{kUsernameHash, kEncryptedPayload},
callback.Get());
EXPECT_CALL(callback,
Run(testing::Pointee(SingleLookupResponse()), Eq(base::nullopt)));
task_env().RunUntilIdle();
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.LookupSingleLeakResponseResult",
LeakDetectionRequest::LeakLookupResponseResult::kSuccess, 1);
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.SingleLeakResponseSize",
response_string.size(), 1);
histogram_tester().ExpectUniqueSample(
"PasswordManager.LeakDetection.SingleLeakResponsePrefixes",
response.encrypted_leak_match_prefix().size(), 1);
}
} // namespace
} // namespace password_manager
|
/**
* @Author: Marcel Ruhf <marcelruhf>
* @Email: m.ruhf@protonmail.ch
* @Project: SoccerRL
* @Filename: RobotTracker.hpp
* @License: Licensed under the Apache 2.0 license (see LICENSE.md)
* @Copyright: Copyright (c) 2017 Marcel Ruhf
*/
#ifndef SOCCERRL_TRACKER_ROBOTTRACKER_HPP_
#define SOCCERRL_TRACKER_ROBOTTRACKER_HPP_
#include <vector>
#include <opencv2/core/mat.hpp>
#include <opencv2/core/types.hpp>
#include "MarkerFinder.hpp"
namespace mr
{
class RobotTracker
{
private:
MarkerFinder marker;
boost::optional<std::vector<cv::Point2f>> markerCorners;
boost::optional<cv::Vec3d> rvec;
boost::optional<cv::Vec3d> tvec;
public:
void preprocess(cv::Mat);
boost::optional<cv::Point2f> getCentrePoint();
boost::optional<cv::Vec3d> getRotationVector();
boost::optional<cv::Vec3d> getTranslationVector();
};
} // namespace mr
#endif // SOCCERRL_TRACKER_ROBOTTRACKER_HPP_
|
#include <QApplication>
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#else
#include <QUrl>
#endif
#include <QTextDocument> // for Qt::mightBeRichText
#include <QAbstractItemView>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin URI
if(!uri.isValid() || uri.scheme() != QString("1credit"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("1credit://"))
{
uri.replace(0, 11, "1credit:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item (global clipboard)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
// Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
}
}
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "1CRedit.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "1credit.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=1CRedit\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#elif defined(Q_OS_MAC)
// based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{
// loop through the list of startup items and try to find the bitcoin app
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = NULL;
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
// found
CFRelease(currentItemURL);
return item;
}
if(currentItemURL) {
CFRelease(currentItemURL);
}
}
return NULL;
}
bool GetStartOnSystemStartup()
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
return !!foundItem; // return boolified object
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
if(fAutoStart && !foundItem) {
// add bitcoin app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
}
else if(!fAutoStart && foundItem) {
// remove item
LSSharedFileListItemRemove(loginItems, foundItem);
}
return true;
}
#else
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("1CRedit-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" 1credit-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("1CRedit-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
|
/*-
* Copyright (c) 2020-current, Terry Mathew Poulin <BigBoss1964@gmail.com>
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the
* use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must
* not claim that you wrote the original software. If you use this
* software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must
* not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include <sxe/gl/BufferObjectPool.hpp>
#include <glbinding/gl20/gl.h>
#include <sxe/logging.hpp>
namespace sxe { namespace gl {
const BufferObjectPool::string_type BufferObjectPool::TAG = "BufferObjectPool";
BufferObjectPool::BufferObjectPool(size_type unit, target_type target, usage_type usage)
: MemoryPool(unit)
, mTarget(target)
, mUsage(usage)
{
}
BufferObjectPool::BufferObjectPool(size_type unit)
: BufferObjectPool(unit, gl20::GL_ARRAY_BUFFER, gl20::GL_STATIC_DRAW)
{
}
BufferObjectPool::~BufferObjectPool()
{
}
BufferObjectPool::buffer_ptr BufferObjectPool::create()
{
Log::xtrace(TAG, "create()");
return std::make_shared<BufferObject>(mTarget, mUsage);
}
} }
|
/*ckwg +5
* Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "vgfNamespace.h"
#include <qtUtil.h>
#include <QIcon>
//-----------------------------------------------------------------------------
QIcon vgf::itemTypeIcon(vgf::ItemType type, int size)
{
switch (type)
{
// TODO
default:
return QIcon();
}
}
|
// Modifications copyright (C) 2017, Baidu.com, Inc.
// Copyright 2017 The Apache Software Foundation
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "runtime/pull_load_task_mgr.h"
#include <gtest/gtest.h>
#include "common/status.h"
#include "gen_cpp/BackendService_types.h"
#include "gen_cpp/Types_types.h"
#include "util/cpu_info.h"
namespace palo {
class PullLoadTaskMgrTest : public testing::Test {
public:
PullLoadTaskMgrTest() {
}
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(PullLoadTaskMgrTest, Normal) {
PullLoadTaskMgr mgr("./test/var/pull_task");
auto st = mgr.init();
ASSERT_TRUE(st.ok());
// register one task
TUniqueId id;
id.__set_hi(101);
id.__set_lo(102);
st = mgr.deregister_task(id);
ASSERT_TRUE(st.ok());
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::CANCELLED, result.task_info.etl_state);
}
st = mgr.register_task(id, 2);
ASSERT_TRUE(st.ok());
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::RUNNING, result.task_info.etl_state);
}
// report sub-task info
{
TPullLoadSubTaskInfo sub_task_info;
sub_task_info.id = id;
sub_task_info.sub_task_id = 1;
sub_task_info.file_map.emplace("http://abc.com/1", 100);
st = mgr.report_sub_task_info(sub_task_info);
ASSERT_TRUE(st.ok());
}
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::RUNNING, result.task_info.etl_state);
}
{
TPullLoadSubTaskInfo sub_task_info;
sub_task_info.id = id;
sub_task_info.sub_task_id = 2;
sub_task_info.file_map.emplace("http://abc.com/2", 200);
st = mgr.report_sub_task_info(sub_task_info);
ASSERT_TRUE(st.ok());
}
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::FINISHED, result.task_info.etl_state);
}
}
TEST_F(PullLoadTaskMgrTest, LoadTask) {
PullLoadTaskMgr mgr("./test/var/pull_task");
auto st = mgr.init();
ASSERT_TRUE(st.ok());
// register one task
TUniqueId id;
id.__set_hi(101);
id.__set_lo(102);
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::FINISHED, result.task_info.etl_state);
}
}
TEST_F(PullLoadTaskMgrTest, Deregister) {
PullLoadTaskMgr mgr("./test/var/pull_task");
auto st = mgr.init();
ASSERT_TRUE(st.ok());
// register one task
TUniqueId id;
id.__set_hi(102);
id.__set_lo(103);
st = mgr.register_task(id, 2);
ASSERT_TRUE(st.ok());
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::RUNNING, result.task_info.etl_state);
}
// report sub-task info
{
TPullLoadSubTaskInfo sub_task_info;
sub_task_info.id = id;
sub_task_info.sub_task_id = 1;
sub_task_info.file_map.emplace("http://abc.com/1", 100);
st = mgr.report_sub_task_info(sub_task_info);
ASSERT_TRUE(st.ok());
}
{
st = mgr.deregister_task(id);
ASSERT_TRUE(st.ok());
}
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::CANCELLED, result.task_info.etl_state);
}
}
TEST_F(PullLoadTaskMgrTest, Deregister2) {
PullLoadTaskMgr mgr("./test/var/pull_task");
auto st = mgr.init();
ASSERT_TRUE(st.ok());
// register one task
TUniqueId id;
id.__set_hi(103);
id.__set_lo(104);
st = mgr.register_task(id, 1);
ASSERT_TRUE(st.ok());
// report sub-task info
{
TPullLoadSubTaskInfo sub_task_info;
sub_task_info.id = id;
sub_task_info.sub_task_id = 1;
sub_task_info.file_map.emplace("http://abc.com/1", 100);
st = mgr.report_sub_task_info(sub_task_info);
ASSERT_TRUE(st.ok());
}
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::FINISHED, result.task_info.etl_state);
}
{
st = mgr.deregister_task(id);
ASSERT_TRUE(st.ok());
}
// Fetch
{
TFetchPullLoadTaskInfoResult result;
st = mgr.fetch_task_info(id, &result);
ASSERT_TRUE(st.ok());
ASSERT_EQ(TEtlState::CANCELLED, result.task_info.etl_state);
}
}
}
int main(int argc, char** argv) {
// init_glog("be-test");
palo::CpuInfo::init();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#ifndef CAFFE_DATA_LAYERS_HPP_
#define CAFFE_DATA_LAYERS_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/blocking_queue.hpp"
namespace caffe {
/**
* @brief Provides base for data layers that feed blobs to the Net.
*
* TODO(dox): thorough documentation for Forward and proto params.
*/
template <typename Dtype>
class BaseDataLayer : public Layer<Dtype> {
public:
explicit BaseDataLayer(const LayerParameter& param);
// LayerSetUp: implements common data layer setup functionality, and calls
// DataLayerSetUp to do special data layer setup for individual layer types.
// This method may not be overridden except by the BasePrefetchingDataLayer.
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
// Data layers should be shared by multiple solvers in parallel
virtual inline bool ShareInParallel() const { return true; }
virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {}
// Data layers have no bottoms, so reshaping is trivial.
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {}
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {}
protected:
TransformationParameter transform_param_;
shared_ptr<DataTransformer<Dtype> > data_transformer_;
bool output_labels_;
};
template <typename Dtype>
class Batch {
public:
Blob<Dtype> data_, label_;
};
template <typename Dtype>
class BasePrefetchingDataLayer :
public BaseDataLayer<Dtype>, public InternalThread {
public:
explicit BasePrefetchingDataLayer(const LayerParameter& param);
// LayerSetUp: implements common data layer setup functionality, and calls
// DataLayerSetUp to do special data layer setup for individual layer types.
// This method may not be overridden.
void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
// Prefetches batches (asynchronously if to GPU memory)
static const int PREFETCH_COUNT = 6;
protected:
virtual void InternalThreadEntry();
virtual void load_batch(Batch<Dtype>* batch) = 0;
Batch<Dtype> prefetch_[PREFETCH_COUNT];
BlockingQueue<Batch<Dtype>*> prefetch_free_;
BlockingQueue<Batch<Dtype>*> prefetch_full_;
Blob<Dtype> transformed_data_;
};
} // namespace caffe
#endif // CAFFE_DATA_LAYERS_HPP_
|
#include "widgets.hpp"
namespace rack {
Widget *gHoveredWidget = NULL;
Widget *gDraggedWidget = NULL;
Widget *gDragHoveredWidget = NULL;
Widget *gFocusedWidget = NULL;
Scene *gScene = NULL;
} // namespace rack
|
#include "denhac/data/Order.h"
#include "denhac/ProductManager.h"
Item::Item() {
itemId = 0;
productId = 0;
quantity = 0;
vended = 0;
skip = false;
}
Item::Item(uint32_t itemId, uint32_t productId, uint8_t quantity, uint8_t vended) {
this->itemId = itemId;
this->productId = productId;
this->quantity = quantity;
this->vended = vended;
this->skip = false;
}
void Item::reset() {
itemId = 0;
productId = 0;
quantity = 0;
vended = 0;
skip = false;
}
Order::Order() {
orderId = 0;
status = OrderStatus::UNKNOWN;
paid = 0;
total = 0;
numItems = 0;
}
// TODO Is there any point in having total here if we recalculate it every time we add an item?
Order::Order(uint32_t orderId, OrderStatus status, uint32_t paid, uint32_t total) {
this->orderId = orderId;
this->status = status;
this->paid = paid;
this->total = total;
this->numItems = 0;
}
Order::Order(const Order& order) {
this->orderId = order.orderId;
this->status = order.status;
this->paid = order.paid;
this->total = order.total;
this->numItems = order.numItems;
for (uint8_t i = 0; i < numItems; i++)
{
this->items[i] = order.items[i];
}
}
void Order::operator = (const Order& order) {
this->orderId = order.orderId;
this->status = order.status;
this->paid = order.paid;
this->total = order.total;
this->numItems = order.numItems;
for (uint8_t i = 0; i < numItems; i++)
{
this->items[i] = order.items[i];
}
}
void Order::add(const Item& item) {
if(numItems == 8) {
return;
}
this->items[numItems] = item;
numItems++;
recalculateTotal();
}
void Order::add(const Product& product) {
if(! product.valid) {
return;
}
for (uint8_t i = 0; i < numItems; i++)
{
Item* item = &(items[i]);
if(item->productId == product.id) {
if(item->quantity + 1 <= product.stockAvailable) {
(item->quantity)++;
recalculateTotal();
}
return;
}
}
Item item(0, product.id, 1, 0);
this->add(item);
}
uint8_t Order::getNumItems() {
return numItems;
}
Item& Order::getItem(uint8_t itemNum) {
return items[itemNum];
}
void Order::vendedItem(uint8_t itemNum) {
items[itemNum].vended++;
}
void Order::recalculateTotal() {
uint32_t newTotal = 0;
for (uint8_t i = 0; i < numItems; i++)
{
Item* item = &(items[i]);
Product product = ProductManager::get(item->productId);
newTotal += item->quantity * product.price;
}
this->total = newTotal;
}
void Order::reset() {
for (uint8_t i = 0; i < numItems; i++)
{
items[i].reset();
}
numItems = 0;
orderId = 0;
status = OrderStatus::UNKNOWN;
paid = 0;
total = 0;
}
|
/**
* @cond doxygen-libsbml-internal
*
* @file PiecewiseValueMathCheck.cpp
* @brief Ensures types returned by branches of a piecewise are consistent.
* @author Sarah Keating
*
* $Id: PiecewiseValueMathCheck.cpp 12784 2011-02-08 07:37:42Z mhucka $
* $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/branches/libsbml-5/src/sbml/validator/constraints/PiecewiseValueMathCheck.cpp $
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2009-2011 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ---------------------------------------------------------------------- -->*/
#include <sbml/Model.h>
#include <sbml/Compartment.h>
#include <sbml/Species.h>
#include <sbml/Parameter.h>
#include <sbml/UnitDefinition.h>
#include <sbml/Event.h>
#include <sbml/Reaction.h>
#include <sbml/EventAssignment.h>
#include <sbml/SpeciesReference.h>
#include <sbml/Rule.h>
#include <sbml/math/FormulaFormatter.h>
#include <sbml/units/UnitFormulaFormatter.h>
#include "PiecewiseValueMathCheck.h"
/** @cond doxygen-ignored */
using namespace std;
/** @endcond */
LIBSBML_CPP_NAMESPACE_BEGIN
static const char* PREAMBLE =
"The types of values within 'piecewise' operators should all be "
"consistent: the set of expressions that make up the first arguments of "
"the 'piece' and 'otherwise' operators within the same 'piecewise' "
"operator should all return values of the same type. (References: L2V2 "
"Section 3.5.8.)";
/**
* Creates a new Constraint with the given id.
*/
PiecewiseValueMathCheck::PiecewiseValueMathCheck (unsigned int id, Validator& v) : MathMLBase(id, v)
{
}
/**
* Destroys this Constraint.
*/
PiecewiseValueMathCheck::~PiecewiseValueMathCheck ()
{
}
/**
* @return the preamble to use when logging constraint violations.
*/
const char*
PiecewiseValueMathCheck::getPreamble ()
{
return PREAMBLE;
}
/**
* Checks the MathML of the ASTnode
* is appropriate for the function being performed
*
* If an inconsistency is found, an error message is logged.
*/
void
PiecewiseValueMathCheck::checkMath (const Model& m, const ASTNode& node, const SBase & sb)
{
ASTNodeType_t type = node.getType();
switch (type)
{
case AST_FUNCTION_PIECEWISE:
checkPiecewiseArgs(m, node, sb);
break;
case AST_FUNCTION:
checkFunction(m, node, sb);
break;
default:
checkChildren(m, node, sb);
break;
}
}
/**
* Checks that the arguments of the branches of a piecewise are consistent
*
* If not, an error message is logged.
*/
void
PiecewiseValueMathCheck::checkPiecewiseArgs (const Model& m, const ASTNode& node,
const SBase & sb)
{
unsigned int numChildren = node.getNumChildren();
/* arguments must return consistent types */
for (unsigned int n = 0; n < numChildren; n += 2)
{
if (returnsNumeric(m, node.getChild(n)) &&
!returnsNumeric(m, node.getLeftChild()))
{
logMathConflict(node, sb);
}
else if (node.getChild(n)->isBoolean() &&
!node.getLeftChild()->isBoolean())
{
logMathConflict(node, sb);
}
}
}
/**
* @return the error message to use when logging constraint violations.
* This method is called by logFailure.
*
* Returns a message that the given id and its corresponding object are
* in conflict with an object previously defined.
*/
const string
PiecewiseValueMathCheck::getMessage (const ASTNode& node, const SBase& object)
{
ostringstream msg;
//msg << getPreamble();
char * left = SBML_formulaToString(node.getLeftChild());
msg << "\nThe piecewise formula ";
msg << "in the " << getFieldname() << " element of the " << getTypename(object);
msg << " returns arguments" ;
msg << " which have different value types from the first element '";
msg << left << "'.";
safe_free(left);
return msg.str();
}
LIBSBML_CPP_NAMESPACE_END
/** @endcond */
|
#include "mod_manager.h"
#include "meow_hash_x64_aesni.h"
#include "anno/random_game_functions.h"
#include "xml_operations.h"
#include "absl/strings/str_cat.h"
#include "spdlog/spdlog.h"
#define ZSTD_STATIC_LINKING_ONLY /* ZSTD_compressContinue, ZSTD_compressBlock */
#include "fse.h"
#include "zstd.h"
#include "zstd_errors.h" /* ZSTD_getErrorCode */
// Prevent preprocess errors with boringssl
#undef X509_NAME
#undef X509_CERT_PAIR
#undef X509_EXTENSIONS
#include "openssl/sha.h"
#include <Windows.h>
#include <fstream>
#include <optional>
#include <sstream>
constexpr static auto PATCH_OP_VERSION = "1.17";
Mod& ModManager::Create(const fs::path& root)
{
spdlog::info("Loading mod {}", root.stem().string());
auto& mod = this->mods_.emplace_back(root);
return mod;
}
static bool IsModEnabled(fs::path path)
{
// If mod folder name starts with '-', we don't enable it.
return path.stem().wstring().find(L'-') != 0;
}
void ModManager::LoadMods()
{
this->mods_.clear();
this->file_cache_.clear();
this->modded_patchable_files_.clear();
auto mods_directory = ModManager::GetModsDirectory();
if (mods_directory.empty()) {
return;
}
// We have a mods directory
// Now create a mod for each of these
std::vector<fs::path> mod_roots;
for (auto&& root : fs::directory_iterator(mods_directory)) {
if (root.is_directory()) {
if (IsModEnabled(root.path())) {
this->Create(root.path());
} else {
spdlog::info("Disabled mod {}", root.path().stem().string());
}
}
}
if (this->mods_.empty()) {
spdlog::info("No mods found in {}", mods_directory.string());
}
}
const std::vector<std::string>& ModManager::GetPythonScripts() const
{
return python_scripts_;
}
void ModManager::CollectPatchableFiles()
{
for (const auto& mod : mods_) {
mod.ForEachFile([this](const fs::path& game_path, const fs::path& file_path) {
if (IsPatchableFile(game_path)) {
modded_patchable_files_[game_path].emplace_back(file_path);
} else {
if (IsPythonStartScript(file_path)) {
auto mods_directory = ModManager::GetModsDirectory();
std::string start_script = "console.startScript('mods\\"
+ fs::relative(file_path, mods_directory).string()
+ "')";
spdlog::info("Loading ptyhon script {}", start_script);
python_scripts_.emplace_back(start_script);
} else {
auto hFile = CreateFileW(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
LARGE_INTEGER lFileSize;
GetFileSizeEx(hFile, &lFileSize);
CloseHandle(hFile);
file_cache_[game_path] = {
static_cast<size_t>(lFileSize.QuadPart), false, {}, file_path};
}
}
}
});
}
}
void ModManager::StartWatchingFiles()
{
//
if (this->watch_file_thread_.joinable()) {
return;
}
this->watch_file_thread_ = std::thread([this]() {
const auto cache_directory = ModManager::GetModsDirectory();
if (cache_directory.empty()) {
return;
}
HANDLE hDir = CreateFileW(cache_directory.wstring().c_str(), FILE_LIST_DIRECTORY,
FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
watch_file_ov_.OffsetHigh = 0;
watch_file_ov_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
while (TRUE) {
DWORD BytesReturned;
DWORD bytesRet = 0;
FILE_NOTIFY_INFORMATION Buffer[1024];
memset(Buffer, 0, sizeof(Buffer));
ReadDirectoryChangesW(hDir, Buffer, sizeof(Buffer), true,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE
| FILE_NOTIFY_CHANGE_CREATION,
&bytesRet, &watch_file_ov_, NULL);
WaitForSingleObject(watch_file_ov_.hEvent, INFINITE);
if (shuttding_down_.load()) {
return;
}
bool need_recreate_mods = false;
BYTE* pBase = (BYTE*)Buffer;
for (;;) {
FILE_NOTIFY_INFORMATION& info = (FILE_NOTIFY_INFORMATION&)*pBase;
std::wstring filename(info.FileName);
if (filename.find(L".cache") == 0
|| filename.find(L"start_script.py") != std::wstring::npos) {
if (!info.NextEntryOffset) {
break;
}
continue;
}
/* switch (info->Action) {
case FILE_ACTION_ADDED:
break;
case FILE_ACTION_MODIFIED:
break;
case FILE_ACTION_REMOVED:
break;
case FILE_ACTION_RENAMED_NEW_NAME:
break;
case FILE_ACTION_RENAMED_OLD_NAME:
break;
}*/
need_recreate_mods = true;
if (!info.NextEntryOffset) {
break;
}
pBase += info.NextEntryOffset;
}
if (need_recreate_mods) {
if (!this->reload_mods_thread_.joinable()) {
this->reload_mods_thread_ = std::thread([this]() {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
{
std::lock_guard<std::mutex> lk(mods_ready_mx_);
mods_ready_.store(false);
}
spdlog::info("Reloading mods");
LoadMods();
GameFilesReady();
spdlog::info("Waiting for mods to finish");
WaitModsReady();
spdlog::info("Triggering game reload");
anno::ToolOneDataHelper::ReloadData();
auto tool_one_helper =
*(uint64_t*)GetAddress(anno::SOME_GLOBAL_STRUCT_TOOL_ONE_HELPER_MAYBE);
auto magic_wait_time = *(uint64_t*)(tool_one_helper + 0x160);
magic_wait_time = magic_wait_time;
*(uint64_t*)(tool_one_helper + 0x160) -=
3000; // Remove stupid 5 second wait for reload
// magic_wait_time
this->reload_mods_thread_.detach();
this->reload_mods_thread_ = {};
});
} else {
mods_change_wile_reload_.store(true);
}
}
}
});
}
void ModManager::WaitModsReady() const
{
//
std::unique_lock<std::mutex> lk(this->mods_ready_mx_);
this->mods_ready_cv_.wait(lk, [this] { return this->mods_ready_.load(); });
}
Mod& ModManager::GetModContainingFile(const fs::path& file)
{
for (auto& mod : mods_) {
if (file.lexically_normal().generic_string().find(mod.Path().lexically_normal().generic_string()) == 0) {
return mod;
}
}
static Mod null_mod;
assert(false);
return null_mod;
}
void ModManager::ReadCache()
{
const auto cache_directory = ModManager::GetCacheDirectory();
for (auto&& modded_file : modded_patchable_files_) {
auto [game_path, on_disk_files] = modded_file;
fs::create_directories(cache_directory / game_path);
auto json_path = cache_directory / game_path;
json_path += ".json";
if (fs::exists(json_path)) {
std::ifstream ifs(json_path);
try {
const auto& data = nlohmann::json::parse(ifs);
std::vector<std::string> layer_order = data["layers"]["order"];
std::string patch_op_version = data.at("version").get<std::string>();
if (PATCH_OP_VERSION == patch_op_version) {
spdlog::debug("Loading from cache {} vs {}",
patch_op_version, PATCH_OP_VERSION);
std::vector<CacheLayer> cache_layers;
for (auto&& layer : layer_order) {
cache_layers.emplace_back(data["layers"].at(layer).get<CacheLayer>());
}
modded_file_cache_info_[game_path] = std::move(cache_layers);
} else {
spdlog::debug("Skipping cache because Patch Op Version mismatch {} vs {}",
patch_op_version, PATCH_OP_VERSION);
}
} catch (const nlohmann::json::exception&) {
}
}
}
}
void ModManager::WriteCacheInfo(const fs::path& game_path)
{
const auto cache_directory = ModManager::GetCacheDirectory();
auto json_path = cache_directory / game_path;
json_path += ".json";
std::ofstream ofs(json_path);
nlohmann::json j;
std::vector<std::string> order;
for (auto& layer : modded_file_cache_info_[game_path]) {
order.push_back(layer.output_hash);
j["layers"][layer.output_hash] = layer;
}
j["layers"]["order"] = order;
j["version"] = PATCH_OP_VERSION;
ofs << j;
ofs.close();
// Let's clean up old cache files
for (auto file : fs::directory_iterator(cache_directory / game_path)) {
const auto file_name = file.path().filename();
auto it = std::find_if(begin(modded_file_cache_info_[game_path]),
end(modded_file_cache_info_[game_path]),
[file_name](const auto& x) { return file_name == x.layer_file; });
//
if (it == end(modded_file_cache_info_[game_path])) {
fs::remove(file);
}
}
}
std::optional<std::string> ModManager::CheckCacheLayer(const fs::path& game_path,
const std::string& input_hash,
const std::string& patch_hash)
{
if (input_hash.empty()) {
return {};
}
for (auto&& cache : modded_file_cache_info_[game_path]) {
if (cache.input_hash == input_hash && cache.patch_hash == patch_hash) {
return cache.output_hash;
}
}
return {};
}
std::string ModManager::ReadCacheLayer(const fs::path& game_path, const std::string& input_hash)
{
const auto cache_directory = ModManager::GetCacheDirectory();
for (auto&& cache : modded_file_cache_info_[game_path]) {
if (cache.output_hash == input_hash) {
const auto cache_file = cache.layer_file;
const auto cache_file_path = (cache_directory / game_path / cache_file);
std::ifstream file(cache_file_path, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::string buffer;
buffer.resize(size);
if (file.read(buffer.data(), size)) {
std::string output;
size_t rSize = ZSTD_getFrameContentSize(buffer.data(), buffer.size());
output.resize(rSize);
size_t dSize =
ZSTD_decompress(output.data(), output.size(), buffer.data(), buffer.size());
output.resize(dSize);
return output;
}
}
}
return "";
}
std::string ModManager::PushCacheLayer(const fs::path& game_path,
const std::string& last_valid_cache,
const std::string& patch_file_hash, const std::string& buf,
const std::string& mod_name)
{
spdlog::debug("PushCacheLayer {} {} {} {}", game_path.string(), last_valid_cache, patch_file_hash,
mod_name);
CacheLayer layer;
layer.input_hash = last_valid_cache;
layer.output_hash = GetDataHash(buf);
layer.patch_hash = patch_file_hash;
layer.layer_file = layer.output_hash;
layer.mod_name = mod_name;
auto& cache = modded_file_cache_info_[game_path];
auto it = find_if(begin(cache), end(cache), [&last_valid_cache](const auto& x) {
return x.output_hash == last_valid_cache;
});
if (it == end(cache)) {
cache.clear();
} else {
std::advance(it, 1);
cache.erase(it, end(cache));
}
const auto cache_directory = ModManager::GetCacheDirectory();
fs::create_directories(cache_directory / game_path);
std::ofstream ofs((cache_directory / game_path / layer.layer_file), std::ofstream::binary);
size_t const cBuffSize = ZSTD_compressBound(buf.size());
std::string CompressedBuffer;
CompressedBuffer.resize(cBuffSize);
size_t const cSize =
ZSTD_compress(CompressedBuffer.data(), CompressedBuffer.size(), buf.data(), buf.size(), 1);
CompressedBuffer.resize(cSize);
ofs.write(CompressedBuffer.data(), CompressedBuffer.size());
ofs.close();
cache.push_back(layer);
return layer.output_hash;
}
void ModManager::EnsureDummy()
{
static auto dummy_path = ModManager::GetDummyPath();
if (!fs::exists(dummy_path)) {
fs::create_directories(ModManager::GetCacheDirectory());
std::fstream fs;
fs.open(dummy_path, std::ios::out);
fs.close();
}
}
void ModManager::GameFilesReady()
{
if (this->mods_ready_.load() || patching_file_thread_.joinable()) {
spdlog::debug("Skip patching, we are either doing it already or are done");
return;
}
sort(begin(mods_), end(mods_), [](const auto& l, const auto& r) {
return stricmp(l.Name().c_str(), r.Name().c_str()) < 0;
});
ModManager::EnsureDummy();
patching_file_thread_ = std::thread([this]() {
spdlog::info("Start applying xml operations");
const auto cache_directory = ModManager::GetCacheDirectory();
CollectPatchableFiles();
ReadCache();
for (auto&& modded_file : modded_patchable_files_) {
if (shuttding_down_.load()) {
return;
}
auto&& [game_path, on_disk_files] = modded_file;
auto game_file = ReadGameFile(game_path);
if (game_file.empty()) {
for (auto& on_disk_file : on_disk_files) {
spdlog::error("Failed to get original game file {} {}", game_path.string(),
on_disk_file.string());
}
continue;
}
std::shared_ptr<pugi::xml_document> game_xml = nullptr;
auto game_file_hash = GetDataHash(game_file);
std::string last_valid_cache = "";
std::string next_input_hash = game_file_hash;
for (auto&& on_disk_file : on_disk_files) {
if (shuttding_down_.load()) {
return;
}
auto patch_file_hash = GetFileHash(on_disk_file);
const auto output_hash =
CheckCacheLayer(game_path, next_input_hash, patch_file_hash);
if (output_hash) {
// Cache hit
last_valid_cache = *output_hash;
next_input_hash = *output_hash;
} else {
next_input_hash = "";
if (!game_xml) {
std::string cache_data = "";
if (last_valid_cache.empty()) {
cache_data = game_file;
} else {
cache_data = ReadCacheLayer(game_path, last_valid_cache);
}
game_xml = std::make_shared<pugi::xml_document>();
auto parse_result =
game_xml->load_buffer(cache_data.data(), cache_data.size());
if (!parse_result) {
spdlog::error("Failed to parse cache {}: {}", on_disk_file.string(),
parse_result.description());
}
}
// Cache miss
auto &mod = GetModContainingFile(on_disk_file);
auto operations = XmlOperation::GetXmlOperationsFromFile(
on_disk_file, mod.Name(), game_path, on_disk_file);
for (auto&& operation : operations) {
operation.Apply(game_xml);
}
struct xml_string_writer : pugi::xml_writer {
std::string result;
virtual void write(const void* data, size_t size)
{
absl::StrAppend(&result, std::string_view{(const char*)data, size});
}
};
xml_string_writer writer;
writer.result.reserve(100 * 1024 * 1024);
game_xml->print(writer);
std::string& buf = writer.result;
if (last_valid_cache.empty()) {
last_valid_cache = game_file_hash;
}
last_valid_cache = PushCacheLayer(game_path, last_valid_cache, patch_file_hash,
buf, on_disk_file.string());
file_cache_[game_path] = {buf.size(), true, buf};
}
}
if (!game_xml) {
auto cache_data = ReadCacheLayer(game_path, last_valid_cache);
file_cache_[game_path] = {cache_data.size(), true, cache_data};
}
WriteCacheInfo(game_path);
game_xml = nullptr;
}
StartWatchingFiles();
{
std::lock_guard<std::mutex> lk(mods_ready_mx_);
mods_ready_.store(true);
}
spdlog::info("Finished applying xml operations");
mods_ready_cv_.notify_all();
patching_file_thread_.detach();
patching_file_thread_ = {};
});
}
bool ModManager::IsFileModded(const fs::path& path) const
{
for (const auto& mod : mods_) {
if (mod.HasFile(path.lexically_normal())) {
return true;
}
}
return false;
}
const ModManager::File& ModManager::GetModdedFileInfo(const fs::path& path) const
{
// If we are currently patching files
// wait for it to finish
WaitModsReady();
{
std::scoped_lock lk{file_cache_mutex_};
if (file_cache_.count(path) > 0) {
return file_cache_.at(path);
}
}
// File not in cache, yet?
throw std::logic_error("GetModdedFileInfo shouldn't be called on a file that is not modded");
}
ModManager::~ModManager()
{
Shutdown();
}
void ModManager::Shutdown()
{
shuttding_down_.store(true);
//
// Trigger watch abort
if (watch_file_thread_.joinable()) {
std::thread thread = {};
std::swap(thread, watch_file_thread_);
SetEvent(watch_file_ov_.hEvent);
thread.join();
thread = {};
}
if (patching_file_thread_.joinable()) {
std::thread thread = {};
std::swap(thread, patching_file_thread_);
thread.join();
thread = {};
}
}
fs::path ModManager::GetModsDirectory()
{
fs::path mods_directory;
HMODULE module;
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPWSTR)&ModManager::GetModsDirectory, &module)) {
WCHAR path[0x7FFF] = {}; // Support for long paths, in theory
GetModuleFileNameW(module, path, sizeof(path));
fs::path dll_file(path);
try {
auto mods_parent = fs::canonical(dll_file.parent_path() / ".." / "..");
mods_directory = mods_parent / "mods";
if (!fs::exists(mods_directory)) {
fs::create_directories(mods_directory);
}
mods_directory = fs::canonical(dll_file.parent_path() / ".." / ".." / "mods");
} catch (const fs::filesystem_error& e) {
spdlog::error("Failed to get current module directory {}", e.what());
return {};
}
} else {
spdlog::error("Failed to get current module directory {}", GetLastError());
return {};
}
return mods_directory;
}
fs::path ModManager::GetCacheDirectory()
{
return ModManager::GetModsDirectory() / ".cache";
}
fs::path ModManager::GetDummyPath()
{
return ModManager::GetCacheDirectory() / ".dummy";
}
bool ModManager::IsPythonStartScript(const fs::path& file) const
{
const auto filename = file.filename();
return filename == "start_script.py";
}
bool ModManager::IsPatchableFile(const fs::path& file) const
{
// We can only patch xml files at the moment
// Other files have to be replaced entirely
const auto extension = file.extension();
return extension == ".xml";
}
std::string ModManager::GetFileHash(const fs::path& path) const
{
std::ifstream file(path, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::string buffer;
buffer.resize(size);
if (file.read(buffer.data(), size)) {
return GetDataHash(buffer);
}
throw new std::runtime_error("Failed to read file");
return {};
}
std::string ModManager::GetDataHash(const std::string& data) const
{
int regs[4];
__cpuid(regs, 1);
int have_aes_ni = (regs[2] >> 25) & 1;
if (have_aes_ni) {
meow_u128 Hash = MeowHash(MeowDefaultSeed, data.size(), (char*)data.data());
std::string result;
for (auto& n : Hash.m128i_i8) {
absl::StrAppend(&result, absl::Hex(n, absl::kZeroPad2));
}
return result;
} else {
uint8_t digest[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const uint8_t*>(data.data()), data.size(), digest);
std::string result;
for (auto& n : digest) {
absl::StrAppend(&result, absl::Hex(n, absl::kZeroPad2));
}
return result;
}
}
std::string ModManager::ReadGameFile(fs::path path)
{
std::string output;
char* buffer = nullptr;
size_t output_data_size = 0;
if (anno::ReadFileFromContainer(*(uintptr_t*)GetAddress(anno::SOME_GLOBAL_STRUCTURE_ARCHIVE),
path.wstring().c_str(), &buffer, &output_data_size)) {
buffer = buffer;
output = {buffer, output_data_size};
// TODO(alexander): Move to anno api
static auto game_free = (decltype(free)*)(GetProcAddress(
GetModuleHandleA("api-ms-win-crt-heap-l1-1-0.dll"), "free"));
game_free(buffer);
}
return output;
}
fs::path ModManager::MapAliasedPath(fs::path path)
{
if (path == L"data/config/game/asset/assets.xml") {
return L"data/config/export/main/asset/assets.xml";
}
if (path == L"data/config/game/asset/properties.xml") {
return L"data/config/export/main/asset/properties.xml";
}
if (path == L"data/config/game/asset/templates.xml") {
return L"data/config/export/main/asset/templates.xml";
}
return path;
}
|
// Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimNode_DigitalControl_HWLoop.hxx"
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimNode_DigitalControl_HWLoop
//
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimNode_DigitalControl_HWLoop
//
SimNode_DigitalControl_HWLoop::
SimNode_DigitalControl_HWLoop ()
: ::schema::simxml::ResourcesGeneral::SimNode ()
{
}
SimNode_DigitalControl_HWLoop::
SimNode_DigitalControl_HWLoop (const RefId_type& RefId)
: ::schema::simxml::ResourcesGeneral::SimNode (RefId)
{
}
SimNode_DigitalControl_HWLoop::
SimNode_DigitalControl_HWLoop (const SimNode_DigitalControl_HWLoop& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::ResourcesGeneral::SimNode (x, f, c)
{
}
SimNode_DigitalControl_HWLoop::
SimNode_DigitalControl_HWLoop (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::ResourcesGeneral::SimNode (e, f, c)
{
}
SimNode_DigitalControl_HWLoop* SimNode_DigitalControl_HWLoop::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimNode_DigitalControl_HWLoop (*this, f, c);
}
SimNode_DigitalControl_HWLoop::
~SimNode_DigitalControl_HWLoop ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
|
#include "Common.hpp"
class Test_Base_Variant : public ::testing::Test {};
class TestRefObject1 : public RefObject {};
TEST_F(Test_Base_Variant, SetAndGet)
{
//* [ ] default
Ref<Variant> v0 = makeVariant();
ASSERT_EQ(VariantType::Null, v0->type());
//* [ ] Bool
{
Ref<Variant> var = makeVariant(true);
ASSERT_EQ(VariantType::Bool, var->type());
ASSERT_EQ(true, var->get<bool>());
}
//* [ ] Char
{
Ref<Variant> var = makeVariant(u'A');
ASSERT_EQ(VariantType::Char, var->type());
ASSERT_EQ(u'A', var->get<Char>());
}
//* [ ] Int8
{
Ref<Variant> var = makeVariant((int8_t)5);
ASSERT_EQ(VariantType::Int8, var->type());
ASSERT_EQ(5, var->get<int8_t>());
}
//* [ ] Int16
{
Ref<Variant> var = makeVariant((int16_t)5);
ASSERT_EQ(VariantType::Int16, var->type());
ASSERT_EQ(5, var->get<int16_t>());
}
//* [ ] Int32
{
Ref<Variant> var = makeVariant((int32_t)5);
ASSERT_EQ(VariantType::Int32, var->type());
ASSERT_EQ(5, var->get<int32_t>());
}
//* [ ] Int64
{
Ref<Variant> var = makeVariant((int64_t)5);
ASSERT_EQ(VariantType::Int64, var->type());
ASSERT_EQ(5, var->get<int64_t>());
}
//* [ ] UInt8
{
Ref<Variant> var = makeVariant((uint8_t)5);
ASSERT_EQ(VariantType::UInt8, var->type());
ASSERT_EQ(5, var->get<uint8_t>());
}
//* [ ] UInt16
{
Ref<Variant> var = makeVariant((uint16_t)5);
ASSERT_EQ(VariantType::UInt16, var->type());
ASSERT_EQ(5, var->get<uint16_t>());
}
//* [ ] UInt32
{
Ref<Variant> var = makeVariant((uint32_t)5);
ASSERT_EQ(VariantType::UInt32, var->type());
ASSERT_EQ(5, var->get<uint32_t>());
}
//* [ ] UInt64
{
Ref<Variant> var = makeVariant((uint64_t)5);
ASSERT_EQ(VariantType::UInt64, var->type());
ASSERT_EQ(5, var->get<uint64_t>());
}
//* [ ] Float
{
Ref<Variant> var = makeVariant((float)5);
ASSERT_EQ(VariantType::Float, var->type());
ASSERT_EQ(true, Math::nearEqual(5.0f, var->get<float>()));
}
//* [ ] Double
{
Ref<Variant> var = makeVariant((double)5);
ASSERT_EQ(VariantType::Double, var->type());
ASSERT_EQ(true, Math::nearEqual(5.0, var->get<double>()));
}
//* [ ] String (Char*)
{
Ref<Variant> var = makeVariant(u"str");
ASSERT_EQ(VariantType::String, var->type());
ASSERT_EQ(u"str", var->get<String>());
}
//* [ ] String (String)
{
Ref<Variant> var = makeVariant(String(u"str"));
ASSERT_EQ(VariantType::String, var->type());
ASSERT_EQ(u"str", var->get<String>());
}
//* [ ] RefObject (RefObject*)
{
auto ref = makeRef<TestRefObject1>();
Ref<Variant> var = makeVariant(ref.get());
ASSERT_EQ(VariantType::RefObject, var->type());
ASSERT_EQ(ref.get(), var->getObject<TestRefObject1>());
}
//* [ ] RefObject (Ref<RefObject>)
{
auto ref = makeRef<TestRefObject1>();
Ref<Variant> var = makeVariant(ref);
ASSERT_EQ(VariantType::RefObject, var->type());
ASSERT_EQ(ref, var->getObject<TestRefObject1>());
}
//* [ ] List
{
auto ref = makeRef<List<Ref<Variant>>>();
ref->add(makeVariant(1));
Ref<Variant> var = makeVariant(ref);
ASSERT_EQ(VariantType::List, var->type());
ASSERT_EQ(1, var->list().size());
}
}
//------------------------------------------------------------------------------
//## Variant serialization
TEST_F(Test_Base_Variant, Serialization)
{
String json = _T("{\"v_Int32\":100}");
struct Data
{
Ref<Variant> v_VarNull;
//Ref<Variant> v_Null; // TODO:
Ref<Variant> v_Bool;
//Ref<Variant> v_Char, // TODO:
Ref<Variant> v_Int8;
Ref<Variant> v_Int16;
Ref<Variant> v_Int32;
Ref<Variant> v_Int64;
Ref<Variant> v_UInt8;
Ref<Variant> v_UInt16;
Ref<Variant> v_UInt32;
Ref<Variant> v_UInt64;
Ref<Variant> v_Float;
Ref<Variant> v_Double;
Ref<Variant> v_String;
Ref<Variant> v_List;
void serialize(Archive& ar)
{
ar & LN_NVP(v_VarNull);
ar & LN_NVP(v_Bool);
ar & LN_NVP(v_Int8);
ar & LN_NVP(v_Int16);
ar & LN_NVP(v_Int32);
ar & LN_NVP(v_Int64);
ar & LN_NVP(v_UInt8);
ar & LN_NVP(v_UInt16);
ar & LN_NVP(v_UInt32);
ar & LN_NVP(v_UInt64);
ar & LN_NVP(v_Float);
ar & LN_NVP(v_Double);
ar & LN_NVP(v_String);
ar & LN_NVP(v_List);
}
};
//* [ ] Save
{
JsonTextOutputArchive ar;
Data data;
data.v_VarNull = nullptr;
data.v_Bool = makeVariant(true);
data.v_Int8 = makeVariant(1);
data.v_Int16 = makeVariant(2);
data.v_Int32 = makeVariant(3);
data.v_Int64 = makeVariant(4);
data.v_UInt8 = makeVariant(5);
data.v_UInt16 = makeVariant(6);
data.v_UInt32 = makeVariant(7);
data.v_UInt64 = makeVariant(8);
data.v_Float = makeVariant(1);
data.v_Double = makeVariant(1);
data.v_String = makeVariant(_T("11"));
data.v_List = makeVariant(List<int>({ 1, 2, 3 }));
ar.process(data);
json = ar.toString(JsonFormatting::None);
}
//* [ ] Load
{
JsonTextInputArchive ar(json);
Data data;
ar.process(data);
ASSERT_EQ(data.v_VarNull, nullptr);
ASSERT_EQ(true, data.v_Bool->get<bool>());
ASSERT_EQ(1, data.v_Int8->get<int8_t>());
ASSERT_EQ(2, data.v_Int16->get<int16_t>());
ASSERT_EQ(3, data.v_Int32->get<int32_t>());
ASSERT_EQ(4, data.v_Int64->get<int64_t>());
ASSERT_EQ(5, data.v_UInt8->get<uint8_t>());
ASSERT_EQ(6, data.v_UInt16->get<uint16_t>());
ASSERT_EQ(7, data.v_UInt32->get<uint32_t>());
ASSERT_EQ(8, data.v_UInt64->get<uint64_t>());
ASSERT_EQ(true, Math::nearEqual(1, data.v_Float->get<float>()));
ASSERT_EQ(true, Math::nearEqual(1, data.v_Double->get<double>()));
ASSERT_EQ(_T("11"), data.v_String->get<String>());
ASSERT_EQ(3, data.v_List->list().size());
ASSERT_EQ(1, data.v_List->list()[0]->get<int32_t>());
ASSERT_EQ(2, data.v_List->list()[1]->get<int32_t>());
ASSERT_EQ(3, data.v_List->list()[2]->get<int32_t>());
}
}
TEST_F(Test_Base_Variant, UseCase1)
{
class Command : public Object
{
public:
String code;
Ref<List<Ref<Variant>>> params;
void serialize(Archive& ar)
{
ar & LN_NVP(code);
ar & LN_NVP(params);
}
};
class Script : public Object
{
public:
String name;
Ref<List<Ref<Command>>> commandList;
void serialize(Archive& ar)
{
ar & LN_NVP(name);
ar & LN_NVP(commandList);
}
};
String json;
//- [ ] Save
{
auto script1 = makeObject<Script>();
script1->name = u"script1";
script1->commandList = makeList<Ref<Command>>();
auto c1 = makeObject<Command>();
c1->code = u"c1";
c1->params = makeList<Ref<Variant>>({ makeVariant(1), makeVariant(u"test1") });
script1->commandList->add(c1);
auto c2 = makeObject<Command>();
c2->code = u"c2";
c2->params = makeList<Ref<Variant>>({ makeVariant(2), makeVariant(u"test2") });
script1->commandList->add(c2);
JsonTextOutputArchive ar;
ar.process(script1);
json = ar.toString(JsonFormatting::None);
}
//- [ ] Load
{
auto script2 = makeObject<Script>();
JsonTextInputArchive ar(json);
ar.process(*script2);
ASSERT_EQ(u"script1", script2->name);
ASSERT_EQ(2, script2->commandList->size());
ASSERT_EQ(u"c1", script2->commandList[0]->code);
ASSERT_EQ(1, script2->commandList[0]->params[0]->get<int>());
ASSERT_EQ(u"test1", script2->commandList[0]->params[1]->get<String>());
ASSERT_EQ(u"c2", script2->commandList[1]->code);
ASSERT_EQ(2, script2->commandList[1]->params[0]->get<int>());
ASSERT_EQ(u"test2", script2->commandList[1]->params[1]->get<String>());
}
}
TEST_F(Test_Base_Variant, Value_Rect)
{
struct S { Ref<Variant> v; void serialize(Archive& ar) { ar & LN_NVP(v); } };
S s1 = { makeVariant(Rect(1, 2, 3, 4)) };
S s2;
// Note: struct は型情報を保存しないので、Rect の復元はできない。
//auto json = JsonSerializer::serialize(s1, JsonFormatting::None);
//JsonSerializer::deserialize(json, s2);
}
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/assistant/assistant_notification_controller_impl.h"
#include <map>
#include <memory>
#include <utility>
#include "ash/assistant/assistant_controller_impl.h"
#include "ash/assistant/model/assistant_notification_model_observer.h"
#include "ash/assistant/test/test_assistant_service.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "base/test/task_environment.h"
#include "chromeos/services/assistant/public/cpp/assistant_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/message_center/message_center.h"
namespace ash {
namespace {
using chromeos::assistant::AssistantNotification;
using chromeos::assistant::AssistantNotificationButton;
using chromeos::assistant::AssistantNotificationPriority;
using testing::_;
using testing::Eq;
using testing::Field;
using testing::Mock;
using testing::StrictMock;
// Constants.
constexpr bool kAnyBool = false;
// Matchers --------------------------------------------------------------------
MATCHER_P(IdIs, expected_id, "") {
if (arg.client_id != expected_id) {
*result_listener << "Received notification with a wrong id.\n"
<< "Expected:\n '" << expected_id << "'\n"
<< "Actual:\n '" << arg.client_id << "'\n";
return false;
}
return true;
}
// Builders --------------------------------------------------------------------
class AssistantNotificationBuilder {
public:
AssistantNotificationBuilder() = default;
AssistantNotificationBuilder(const AssistantNotificationBuilder& bldr) {
notification_ = bldr.notification_;
}
~AssistantNotificationBuilder() = default;
AssistantNotification Build() const { return notification_; }
AssistantNotificationBuilder& WithId(const std::string& id) {
notification_.client_id = id;
notification_.server_id = id;
return *this;
}
AssistantNotificationBuilder& WithActionUrl(const GURL& action_url) {
notification_.action_url = action_url;
return *this;
}
AssistantNotificationBuilder& WithButton(AssistantNotificationButton&& button,
int index = -1) {
if (index != -1) {
notification_.buttons.insert(notification_.buttons.begin() + index,
std::move(button));
} else {
notification_.buttons.push_back(std::move(button));
}
return *this;
}
AssistantNotificationBuilder& WithFromServer(bool from_server) {
notification_.from_server = from_server;
return *this;
}
AssistantNotificationBuilder& WithIsPinned(bool is_pinned) {
notification_.is_pinned = is_pinned;
return *this;
}
AssistantNotificationBuilder& WithPriority(
AssistantNotificationPriority priority) {
notification_.priority = priority;
return *this;
}
AssistantNotificationBuilder& WithRemoveOnClick(bool remove_on_click) {
notification_.remove_on_click = remove_on_click;
return *this;
}
AssistantNotificationBuilder& WithRenotify(bool renotify) {
notification_.renotify = renotify;
return *this;
}
AssistantNotificationBuilder& WithTimeout(
base::Optional<base::TimeDelta> timeout) {
notification_.expiry_time =
timeout.has_value()
? base::Optional<base::Time>(base::Time::Now() + timeout.value())
: base::nullopt;
return *this;
}
AssistantNotificationBuilder& WithTimeoutMs(int timeout_ms) {
return WithTimeout(base::TimeDelta::FromMilliseconds(timeout_ms));
}
private:
AssistantNotification notification_;
};
class AssistantNotificationButtonBuilder {
public:
AssistantNotificationButtonBuilder() = default;
AssistantNotificationButtonBuilder(
const AssistantNotificationButtonBuilder& bldr) {
button_ = bldr.button_;
}
~AssistantNotificationButtonBuilder() = default;
AssistantNotificationButton Build() const { return button_; }
AssistantNotificationButtonBuilder& WithLabel(const std::string& label) {
button_.label = label;
return *this;
}
AssistantNotificationButtonBuilder& WithActionUrl(const GURL& action_url) {
button_.action_url = action_url;
return *this;
}
AssistantNotificationButtonBuilder& WithRemoveNotificationOnClick(
bool remove_notification_on_click) {
button_.remove_notification_on_click = remove_notification_on_click;
return *this;
}
private:
AssistantNotificationButton button_;
};
// Mocks -----------------------------------------------------------------------
class AssistantNotificationModelObserverMock
: public AssistantNotificationModelObserver {
public:
AssistantNotificationModelObserverMock() = default;
~AssistantNotificationModelObserverMock() override = default;
MOCK_METHOD(void,
OnNotificationAdded,
(const AssistantNotification& notification),
(override));
MOCK_METHOD(void,
OnNotificationUpdated,
(const AssistantNotification& notification),
(override));
MOCK_METHOD(void,
OnNotificationRemoved,
(const AssistantNotification& notification, bool from_server),
(override));
MOCK_METHOD(void, OnAllNotificationsRemoved, (bool from_server), (override));
private:
DISALLOW_COPY_AND_ASSIGN(AssistantNotificationModelObserverMock);
};
class AssistantServiceMock : public TestAssistantService {
public:
MOCK_METHOD(void,
RetrieveNotification,
(const AssistantNotification& notification, int action_index),
(override));
};
// AssistantNotificationControllerTest -----------------------------------------
class AssistantNotificationControllerTest : public AshTestBase {
protected:
AssistantNotificationControllerTest()
: AshTestBase(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
~AssistantNotificationControllerTest() override = default;
void SetUp() override {
AshTestBase::SetUp();
controller_ =
Shell::Get()->assistant_controller()->notification_controller();
DCHECK(controller_);
}
AssistantNotificationControllerImpl& controller() { return *controller_; }
AssistantNotificationModelObserverMock& AddStrictObserverMock() {
observer_ =
std::make_unique<StrictMock<AssistantNotificationModelObserverMock>>();
controller().model()->AddObserver(observer_.get());
return *observer_;
}
void AddOrUpdateNotification(AssistantNotification&& notification) {
controller().AddOrUpdateNotification(std::move(notification));
}
void RemoveNotification(const std::string& id) {
controller().RemoveNotificationById(id, kAnyBool);
}
void ForwardTimeInMs(int time_in_ms) {
task_environment()->FastForwardBy(
base::TimeDelta::FromMilliseconds(time_in_ms));
}
private:
AssistantNotificationControllerImpl* controller_;
std::unique_ptr<AssistantNotificationModelObserverMock> observer_;
DISALLOW_COPY_AND_ASSIGN(AssistantNotificationControllerTest);
};
} // namespace
// Tests -----------------------------------------------------------------------
TEST_F(AssistantNotificationControllerTest,
ShouldInformObserverOfNewNotifications) {
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationAdded(IdIs("id")));
controller().AddOrUpdateNotification(
AssistantNotificationBuilder().WithId("id").Build());
}
TEST_F(AssistantNotificationControllerTest,
ShouldInformObserverOfUpdatedNotifications) {
const auto builder = AssistantNotificationBuilder().WithId("id");
controller().AddOrUpdateNotification(builder.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationUpdated(IdIs("id")));
controller().AddOrUpdateNotification(builder.Build());
}
TEST_F(AssistantNotificationControllerTest,
ShouldInformObserverOfRemovedNotifications) {
constexpr bool kFromServer = kAnyBool;
auto builder = AssistantNotificationBuilder().WithId("id");
controller().AddOrUpdateNotification(builder.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved(IdIs("id"), Eq(kFromServer)));
controller().RemoveNotificationById(builder.Build().client_id, kFromServer);
}
TEST_F(AssistantNotificationControllerTest,
ShouldInformObserverOfRemoveAllNotifications) {
constexpr bool kFromServer = !kAnyBool;
controller().AddOrUpdateNotification(
AssistantNotificationBuilder().WithId("id").Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnAllNotificationsRemoved(Eq(kFromServer)));
controller().RemoveAllNotifications(kFromServer);
}
TEST_F(AssistantNotificationControllerTest,
ShouldRemoveNotificationWhenItExpires) {
constexpr int kTimeoutMs = 1000;
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("id")
.WithTimeoutMs((kTimeoutMs))
.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved(IdIs("id"), _));
ForwardTimeInMs(kTimeoutMs);
}
TEST_F(AssistantNotificationControllerTest,
ShouldNotRemoveNotificationsTooSoon) {
constexpr int kTimeoutMs = 1000;
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("id")
.WithTimeoutMs(kTimeoutMs)
.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved).Times(0);
ForwardTimeInMs(kTimeoutMs - 1);
}
TEST_F(AssistantNotificationControllerTest,
ShouldUseFromServerFalseWhenNotificationExpires) {
constexpr int kTimeoutMs = 1000;
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("id")
.WithTimeoutMs(kTimeoutMs)
.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved(_, Eq(false)));
ForwardTimeInMs(kTimeoutMs);
}
TEST_F(AssistantNotificationControllerTest,
ShouldRemoveEachNotificationAsItExpires) {
constexpr int kFirstTimeoutMs = 1000;
constexpr int kSecondTimeoutMs = 1500;
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("first")
.WithTimeoutMs(kFirstTimeoutMs)
.Build());
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("second")
.WithTimeoutMs(kSecondTimeoutMs)
.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved(IdIs("first"), _));
ForwardTimeInMs(kFirstTimeoutMs);
EXPECT_CALL(observer, OnNotificationRemoved(IdIs("second"), _));
ForwardTimeInMs(kSecondTimeoutMs - kFirstTimeoutMs);
}
TEST_F(AssistantNotificationControllerTest,
ShouldSupport2NotificationsThatExpireAtTheSameTime) {
constexpr int kTimeoutMs = 1000;
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("first")
.WithTimeoutMs(kTimeoutMs)
.Build());
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("at-same-time")
.WithTimeoutMs(kTimeoutMs)
.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved(IdIs("first"), _));
EXPECT_CALL(observer, OnNotificationRemoved(IdIs("at-same-time"), _));
ForwardTimeInMs(kTimeoutMs);
}
TEST_F(AssistantNotificationControllerTest,
ShouldImmediateRemoveNotificationsThatAlreadyExpired) {
constexpr int kNegativeTimeoutMs = -1000;
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("expired")
.WithTimeoutMs(kNegativeTimeoutMs)
.Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved(IdIs("expired"), _));
}
TEST_F(AssistantNotificationControllerTest,
ShouldNotRemoveNotificationsThatWereManuallyRemoved) {
constexpr int kTimeoutMs = 1000;
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId("id")
.WithTimeoutMs(kTimeoutMs)
.Build());
RemoveNotification("id");
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved).Times(0);
ForwardTimeInMs(kTimeoutMs);
}
TEST_F(AssistantNotificationControllerTest,
ShouldSupportExpiryTimeSetInUpdate) {
constexpr int kTimeoutMs = 1000;
auto notification_bldr = AssistantNotificationBuilder().WithId("id");
AddOrUpdateNotification(notification_bldr.Build());
AddOrUpdateNotification(notification_bldr.WithTimeoutMs(kTimeoutMs).Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved);
ForwardTimeInMs(kTimeoutMs);
}
TEST_F(AssistantNotificationControllerTest,
ShouldNotRemoveNotificationIfExpiryTimeIsClearedInUpdate) {
constexpr int kTimeoutMs = 1000;
auto notification_bldr = AssistantNotificationBuilder().WithId("id");
AddOrUpdateNotification(notification_bldr.WithTimeoutMs(kTimeoutMs).Build());
AddOrUpdateNotification(notification_bldr.WithTimeout(base::nullopt).Build());
auto& observer = AddStrictObserverMock();
EXPECT_CALL(observer, OnNotificationRemoved).Times(0);
ForwardTimeInMs(kTimeoutMs);
}
TEST_F(AssistantNotificationControllerTest,
ShouldMaybeRemoveNotificationWhenClicking) {
constexpr char kId[] = "id";
auto notification_bldr =
AssistantNotificationBuilder().WithId(kId).WithActionUrl(
GURL("https://g.co/"));
AddOrUpdateNotification(notification_bldr.WithRemoveOnClick(false).Build());
auto& observer = AddStrictObserverMock();
auto* message_center = message_center::MessageCenter::Get();
EXPECT_CALL(observer, OnNotificationRemoved).Times(0);
message_center->ClickOnNotification(kId);
Mock::VerifyAndClearExpectations(&observer);
EXPECT_CALL(observer, OnNotificationUpdated(IdIs(kId)));
AddOrUpdateNotification(notification_bldr.WithRemoveOnClick(true).Build());
EXPECT_CALL(observer, OnNotificationRemoved(IdIs(kId), _));
message_center->ClickOnNotification(kId);
}
TEST_F(AssistantNotificationControllerTest,
ShouldMaybeRemoveNotificationWhenClickingButton) {
constexpr char kId[] = "id";
auto notification_bldr = AssistantNotificationBuilder().WithId(kId);
auto button_bldr =
AssistantNotificationButtonBuilder().WithActionUrl(GURL("https://g.co/"));
AddOrUpdateNotification(
notification_bldr
.WithButton(button_bldr.WithRemoveNotificationOnClick(false).Build())
.Build());
auto& observer = AddStrictObserverMock();
auto* message_center = message_center::MessageCenter::Get();
EXPECT_CALL(observer, OnNotificationRemoved).Times(0);
message_center->ClickOnNotificationButton(kId, /*index=*/0);
Mock::VerifyAndClearExpectations(&observer);
EXPECT_CALL(observer, OnNotificationUpdated(IdIs(kId)));
AddOrUpdateNotification(
notification_bldr
.WithButton(button_bldr.WithRemoveNotificationOnClick(true).Build(),
/*index=*/0)
.Build());
EXPECT_CALL(observer, OnNotificationRemoved(IdIs(kId), _));
message_center->ClickOnNotificationButton(kId, /*index=*/0);
}
TEST_F(AssistantNotificationControllerTest,
ShouldCorrectlyMapNotificationPriority) {
constexpr char kId[] = "id";
// Map of Assistant notification priorities to system notification priorities.
const std::map<AssistantNotificationPriority,
message_center::NotificationPriority>
priority_map = {{AssistantNotificationPriority::kLow,
message_center::NotificationPriority::LOW_PRIORITY},
{AssistantNotificationPriority::kDefault,
message_center::NotificationPriority::DEFAULT_PRIORITY},
{AssistantNotificationPriority::kHigh,
message_center::NotificationPriority::HIGH_PRIORITY}};
for (const auto& priority_pair : priority_map) {
// Create an Assistant notification.
AddOrUpdateNotification(AssistantNotificationBuilder()
.WithId(kId)
.WithPriority(priority_pair.first)
.Build());
// Verify expected system notification.
auto* system_notification =
message_center::MessageCenter::Get()->FindVisibleNotificationById(kId);
ASSERT_NE(nullptr, system_notification);
EXPECT_EQ(priority_pair.second, system_notification->priority());
}
}
TEST_F(AssistantNotificationControllerTest, ShouldPropagateIsPinned) {
constexpr char kId[] = "id";
// Create an Assistant notification w/ default pin behavior.
AddOrUpdateNotification(AssistantNotificationBuilder().WithId(kId).Build());
// Verify expected system notification.
auto* system_notification =
message_center::MessageCenter::Get()->FindVisibleNotificationById(kId);
ASSERT_NE(nullptr, system_notification);
EXPECT_FALSE(system_notification->pinned());
// Create an Assistant notification w/ explicitly disabled pin behavior.
AddOrUpdateNotification(
AssistantNotificationBuilder().WithId(kId).WithIsPinned(false).Build());
// Verify expected system notification.
system_notification =
message_center::MessageCenter::Get()->FindVisibleNotificationById(kId);
ASSERT_NE(nullptr, system_notification);
EXPECT_FALSE(system_notification->pinned());
// Create an Assistant notification w/ explicitly enabled pin behavior.
AddOrUpdateNotification(
AssistantNotificationBuilder().WithId(kId).WithIsPinned(true).Build());
// Verify expected system notification.
system_notification =
message_center::MessageCenter::Get()->FindVisibleNotificationById(kId);
ASSERT_NE(nullptr, system_notification);
EXPECT_TRUE(system_notification->pinned());
}
TEST_F(AssistantNotificationControllerTest, ShouldPropagateRenotify) {
constexpr char kId[] = "id";
// Create an Assistant notification w/ default renotify behavior.
AddOrUpdateNotification(AssistantNotificationBuilder().WithId(kId).Build());
// Verify expected system notification.
auto* system_notification =
message_center::MessageCenter::Get()->FindVisibleNotificationById(kId);
ASSERT_NE(nullptr, system_notification);
EXPECT_FALSE(system_notification->renotify());
// Create an Assistant notification w/ explicitly disabled renotify behavior.
AddOrUpdateNotification(
AssistantNotificationBuilder().WithId(kId).WithRenotify(false).Build());
// Verify expected system notification.
system_notification =
message_center::MessageCenter::Get()->FindVisibleNotificationById(kId);
ASSERT_NE(nullptr, system_notification);
EXPECT_FALSE(system_notification->renotify());
// Create an Assistant notification w/ explicitly enabled renotify behavior.
AddOrUpdateNotification(
AssistantNotificationBuilder().WithId(kId).WithRenotify(true).Build());
// Verify expected system notification.
system_notification =
message_center::MessageCenter::Get()->FindVisibleNotificationById(kId);
ASSERT_NE(nullptr, system_notification);
EXPECT_TRUE(system_notification->renotify());
}
TEST_F(AssistantNotificationControllerTest,
ShouldMaybeRetrieveNotificationPayload) {
constexpr char kId[] = "id";
// Mock the Assistant service.
StrictMock<AssistantServiceMock> service;
controller().SetAssistant(&service);
// Create an Assistant notification w/ default |from_server|.
AddOrUpdateNotification(AssistantNotificationBuilder().WithId(kId).Build());
// Click notification and verify we do *not* attempt to retrieve payload.
EXPECT_CALL(service, RetrieveNotification).Times(0);
message_center::MessageCenter::Get()->ClickOnNotification(kId);
Mock::VerifyAndClearExpectations(&service);
// Create an Assistant notification explicitly *not* |from_server|.
AddOrUpdateNotification(
AssistantNotificationBuilder().WithId(kId).WithFromServer(false).Build());
// Click notification and verify we do *not* attempt to retrieve payload.
EXPECT_CALL(service, RetrieveNotification).Times(0);
message_center::MessageCenter::Get()->ClickOnNotification(kId);
Mock::VerifyAndClearExpectations(&service);
// Create an Assistant notification explicitly |from_server|.
AddOrUpdateNotification(
AssistantNotificationBuilder().WithId(kId).WithFromServer(true).Build());
// Click notification and verify we *do* attempt to retrieve payload.
EXPECT_CALL(service, RetrieveNotification);
message_center::MessageCenter::Get()->ClickOnNotification(kId);
}
} // namespace ash
|
/* SPDX-License-Identifier: BSD-2-Clause-Patent
*
* SPDX-FileCopyrightText: 2019-2020 the prplMesh contributors (see AUTHORS.md)
*
* This code is subject to the terms of the BSD+Patent license.
* See LICENSE file for more details.
*/
#include <mapf/common/encryption.h>
#include <mapf/common/logger.h>
#include <arpa/inet.h>
static bool check(int &errors, bool check, const std::string &message)
{
if (check) {
MAPF_INFO(" OK ") << message;
} else {
MAPF_ERR("FAIL ") << message;
errors++;
}
return check;
}
int main()
{
mapf::Logger::Instance().LoggerInit("encryption_test");
int errors = 0;
MAPF_INFO("Start encryption test");
mapf::encryption::diffie_hellman m1;
mapf::encryption::diffie_hellman m2;
uint8_t key1[192];
uint8_t key2[192];
unsigned key1_length = sizeof(key1);
unsigned key2_length = sizeof(key2);
std::fill(key1, key1 + key1_length, 1);
std::fill(key2, key2 + key2_length, 2);
uint8_t mac[6] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66};
uint8_t authkey1[32];
uint8_t keywrapkey1[16];
wps_calculate_keys(m1, m2.pubkey(), m2.pubkey_length(), m1.nonce(), mac, m2.nonce(), authkey1,
keywrapkey1);
uint8_t authkey2[32];
uint8_t keywrapkey2[16];
wps_calculate_keys(m2, m1.pubkey(), m1.pubkey_length(), m1.nonce(), mac, m2.nonce(), authkey2,
keywrapkey2);
check(errors, std::equal(authkey1, authkey1 + sizeof(authkey1), authkey2),
"authkeys should be equal");
check(errors, std::equal(keywrapkey1, keywrapkey1 + sizeof(keywrapkey1), keywrapkey2),
"keywrapkeys should be equal");
/* size 16 and 816 yield a multiple of block size.
* The other sizes are just one more and one less of the block size
* since these are potentially interesting as they cross the natural
* boundary (16 in our case).
*/
std::vector<int> sizes = {15, 16, 17, 815, 816, 817};
for (auto size : sizes) {
LOG(INFO) << "Test encryption with plaintext size " << size;
uint8_t plaintext[size];
std::fill(plaintext, plaintext + sizeof(plaintext), 1);
// last 8 bytes are the KWA
int plaintextlen = sizeof(plaintext) - 8;
uint8_t *kwa = &plaintext[plaintextlen];
check(errors, mapf::encryption::kwa_compute(authkey1, plaintext, plaintextlen, kwa),
"KWA compute IN");
uint8_t iv[128];
mapf::encryption::create_iv(iv, sizeof(iv));
// maximum padding can be block size, which is 16 bytes, per PKCS#5 padding scheme
int cipherlen = sizeof(plaintext) + 16;
// Since we use the same buffer for decryption, leave additional block size
// for last block correctness check done by openssl EVP_DecryptUpdate() API.
int datalen = cipherlen + 16;
uint8_t data[datalen] = {0};
check(errors,
mapf::encryption::aes_encrypt(keywrapkey1, iv, plaintext, sizeof(plaintext), data,
cipherlen),
"AES encrypt");
check(errors, size_t(cipherlen) > sizeof(plaintext),
"ciphertext length > plaintext length");
check(errors, size_t(cipherlen) <= sizeof(plaintext) + 16,
"ciphertext length <= plaintext length + 16");
check(errors,
mapf::encryption::aes_decrypt(keywrapkey2, iv, data, cipherlen, data, datalen),
"AES decrypt");
check(errors, size_t(datalen) == sizeof(plaintext),
"Decrypted length should be equal to plaintext length");
check(errors, std::equal(data, data + sizeof(plaintext), plaintext),
"Decrypted cyphertext should be equal to plaintext");
uint8_t *kwa_in = &data[plaintextlen];
uint8_t kwa_out[8];
check(errors, mapf::encryption::kwa_compute(authkey2, data, plaintextlen, kwa_out),
"KWA compute OUT");
check(errors, std::equal(kwa_out, kwa_out + sizeof(kwa_out), kwa_in),
"KWA should be equal");
}
return errors;
}
|
/*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "ShutdownDialog.h"
#include "TaskbarWindow.h"
#include <AK/Debug.h>
#include <AK/LexicalPath.h>
#include <AK/QuickSort.h>
#include <LibCore/ConfigFile.h>
#include <LibCore/DirIterator.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Process.h>
#include <LibCore/StandardPaths.h>
#include <LibDesktop/AppFile.h>
#include <LibGUI/ActionGroup.h>
#include <LibGUI/Application.h>
#include <LibGUI/Menu.h>
#include <LibGUI/WindowManagerServerConnection.h>
#include <LibGUI/WindowServerConnection.h>
#include <WindowServer/Window.h>
#include <serenity.h>
#include <signal.h>
#include <spawn.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
static Vector<String> discover_apps_and_categories();
static NonnullRefPtr<GUI::Menu> build_system_menu();
int main(int argc, char** argv)
{
if (pledge("stdio recvfd sendfd proc exec rpath unix sigaction", nullptr) < 0) {
perror("pledge");
return 1;
}
auto app = GUI::Application::construct(argc, argv);
app->event_loop().register_signal(SIGCHLD, [](int) {
// Wait all available children
while (waitpid(-1, nullptr, WNOHANG) > 0)
;
});
// We need to obtain the WM connection here as well before the pledge shortening.
GUI::WindowManagerServerConnection::the();
if (pledge("stdio recvfd sendfd proc exec rpath", nullptr) < 0) {
perror("pledge");
return 1;
}
auto menu = build_system_menu();
menu->realize_menu_if_needed();
auto window = TaskbarWindow::construct(move(menu));
window->show();
window->make_window_manager(
WindowServer::WMEventMask::WindowStateChanges
| WindowServer::WMEventMask::WindowRemovals
| WindowServer::WMEventMask::WindowIconChanges
| WindowServer::WMEventMask::VirtualDesktopChanges);
return app->exec();
}
struct AppMetadata {
String executable;
String name;
String category;
GUI::Icon icon;
bool run_in_terminal;
};
Vector<AppMetadata> g_apps;
struct ThemeMetadata {
String name;
String path;
};
Color g_menu_selection_color;
Vector<ThemeMetadata> g_themes;
RefPtr<GUI::Menu> g_themes_menu;
GUI::ActionGroup g_themes_group;
Vector<String> discover_apps_and_categories()
{
HashTable<String> seen_app_categories;
Desktop::AppFile::for_each([&](auto af) {
if (access(af->executable().characters(), X_OK) == 0) {
g_apps.append({ af->executable(), af->name(), af->category(), af->icon(), af->run_in_terminal() });
seen_app_categories.set(af->category());
}
});
quick_sort(g_apps, [](auto& a, auto& b) { return a.name < b.name; });
Vector<String> sorted_app_categories;
for (auto& category : seen_app_categories) {
sorted_app_categories.append(category);
}
quick_sort(sorted_app_categories);
return sorted_app_categories;
}
NonnullRefPtr<GUI::Menu> build_system_menu()
{
const Vector<String> sorted_app_categories = discover_apps_and_categories();
auto system_menu = GUI::Menu::construct("\xE2\x9A\xA1"); // HIGH VOLTAGE SIGN
system_menu->add_action(GUI::Action::create("About SerenityOS", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/ladyball.png"), [](auto&) {
Core::Process::spawn("/bin/About"sv);
}));
system_menu->add_separator();
// First we construct all the necessary app category submenus.
auto category_icons = Core::ConfigFile::open("/res/icons/SystemMenu.ini");
HashMap<String, NonnullRefPtr<GUI::Menu>> app_category_menus;
Function<void(String const&)> create_category_menu;
create_category_menu = [&](String const& category) {
if (app_category_menus.contains(category))
return;
String parent_category, child_category = category;
for (ssize_t i = category.length() - 1; i >= 0; i--) {
if (category[i] == '/') {
parent_category = category.substring(0, i);
child_category = category.substring(i + 1);
}
}
GUI::Menu* parent_menu;
if (parent_category.is_empty()) {
parent_menu = system_menu;
} else {
parent_menu = app_category_menus.get(parent_category).value();
if (!parent_menu) {
create_category_menu(parent_category);
parent_menu = app_category_menus.get(parent_category).value();
VERIFY(parent_menu);
}
}
auto& category_menu = parent_menu->add_submenu(child_category);
auto category_icon_path = category_icons->read_entry("16x16", category);
if (!category_icon_path.is_empty()) {
auto icon = Gfx::Bitmap::try_load_from_file(category_icon_path);
category_menu.set_icon(icon);
}
app_category_menus.set(category, category_menu);
};
for (const auto& category : sorted_app_categories) {
if (category != "Settings"sv)
create_category_menu(category);
}
// Then we create and insert all the app menu items into the right place.
int app_identifier = 0;
for (const auto& app : g_apps) {
if (app.category == "Settings"sv) {
++app_identifier;
continue;
}
auto icon = app.icon.bitmap_for_size(16);
if constexpr (SYSTEM_MENU_DEBUG) {
if (icon)
dbgln("App {} has icon with size {}", app.name, icon->size());
}
auto parent_menu = app_category_menus.get(app.category).value_or(system_menu.ptr());
parent_menu->add_action(GUI::Action::create(app.name, icon, [app_identifier](auto&) {
dbgln("Activated app with ID {}", app_identifier);
auto& app = g_apps[app_identifier];
char const* argv[4] { nullptr, nullptr, nullptr, nullptr };
if (app.run_in_terminal) {
argv[0] = "/bin/Terminal";
argv[1] = "-e";
argv[2] = app.executable.characters();
} else {
argv[0] = app.executable.characters();
}
posix_spawn_file_actions_t spawn_actions;
posix_spawn_file_actions_init(&spawn_actions);
auto home_directory = Core::StandardPaths::home_directory();
posix_spawn_file_actions_addchdir(&spawn_actions, home_directory.characters());
pid_t child_pid;
if ((errno = posix_spawn(&child_pid, argv[0], &spawn_actions, nullptr, const_cast<char**>(argv), environ))) {
perror("posix_spawn");
} else {
if (disown(child_pid) < 0)
perror("disown");
}
posix_spawn_file_actions_destroy(&spawn_actions);
}));
++app_identifier;
}
system_menu->add_separator();
g_themes_group.set_exclusive(true);
g_themes_group.set_unchecking_allowed(false);
g_themes_menu = &system_menu->add_submenu("Themes");
g_themes_menu->set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/themes.png"));
{
Core::DirIterator dt("/res/themes", Core::DirIterator::SkipDots);
while (dt.has_next()) {
auto theme_name = dt.next_path();
auto theme_path = String::formatted("/res/themes/{}", theme_name);
g_themes.append({ LexicalPath::title(theme_name), theme_path });
}
quick_sort(g_themes, [](auto& a, auto& b) { return a.name < b.name; });
}
auto current_theme_name = GUI::WindowServerConnection::the().get_system_theme();
{
int theme_identifier = 0;
for (auto& theme : g_themes) {
auto action = GUI::Action::create_checkable(theme.name, [theme_identifier](auto&) {
auto& theme = g_themes[theme_identifier];
dbgln("Theme switched to {} at path {}", theme.name, theme.path);
auto success = GUI::WindowServerConnection::the().set_system_theme(theme.path, theme.name);
VERIFY(success);
});
if (theme.name == current_theme_name)
action->set_checked(true);
g_themes_group.add_action(action);
g_themes_menu->add_action(action);
++theme_identifier;
}
}
system_menu->add_action(GUI::Action::create("Settings", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-settings.png"), [](auto&) {
Core::Process::spawn("/bin/Settings"sv);
}));
system_menu->add_separator();
system_menu->add_action(GUI::Action::create("Help", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-help.png"), [](auto&) {
Core::Process::spawn("/bin/Help"sv);
}));
system_menu->add_action(GUI::Action::create("Run...", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/app-run.png"), [](auto&) {
posix_spawn_file_actions_t spawn_actions;
posix_spawn_file_actions_init(&spawn_actions);
auto home_directory = Core::StandardPaths::home_directory();
posix_spawn_file_actions_addchdir(&spawn_actions, home_directory.characters());
pid_t child_pid;
const char* argv[] = { "/bin/Run", nullptr };
if ((errno = posix_spawn(&child_pid, "/bin/Run", &spawn_actions, nullptr, const_cast<char**>(argv), environ))) {
perror("posix_spawn");
} else {
if (disown(child_pid) < 0)
perror("disown");
}
posix_spawn_file_actions_destroy(&spawn_actions);
}));
system_menu->add_separator();
system_menu->add_action(GUI::Action::create("Exit...", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/power.png"), [](auto&) {
auto command = ShutdownDialog::show();
if (command.size() == 0)
return;
pid_t child_pid;
if ((errno = posix_spawn(&child_pid, command[0], nullptr, nullptr, const_cast<char**>(command.data()), environ))) {
perror("posix_spawn");
} else {
if (disown(child_pid) < 0)
perror("disown");
}
}));
return system_menu;
}
|
//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This implements the SelectionDAG class.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/SelectionDAG.h"
#include "SDNodeDbgValue.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/FunctionLoweringInfo.h"
#include "llvm/CodeGen/ISDOpcodes.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/RuntimeLibcalls.h"
#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
#include "llvm/CodeGen/SelectionDAGNodes.h"
#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/MachineValueType.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Utils/SizeOpts.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
/// makeVTList - Return an instance of the SDVTList struct initialized with the
/// specified members.
static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
SDVTList Res = {VTs, NumVTs};
return Res;
}
// Default null implementations of the callbacks.
void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
void SelectionDAG::DAGNodeDeletedListener::anchor() {}
#define DEBUG_TYPE "selectiondag"
static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
cl::Hidden, cl::init(true),
cl::desc("Gang up loads and stores generated by inlining of memcpy"));
static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
cl::desc("Number limit for gluing ld/st of memcpy."),
cl::Hidden, cl::init(0));
static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
}
//===----------------------------------------------------------------------===//
// ConstantFPSDNode Class
//===----------------------------------------------------------------------===//
/// isExactlyValue - We don't rely on operator== working on double values, as
/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
/// As such, this method can be used to do an exact bit-for-bit comparison of
/// two floating point values.
bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
return getValueAPF().bitwiseIsEqual(V);
}
bool ConstantFPSDNode::isValueValidForType(EVT VT,
const APFloat& Val) {
assert(VT.isFloatingPoint() && "Can only convert between FP types");
// convert modifies in place, so make a copy.
APFloat Val2 = APFloat(Val);
bool losesInfo;
(void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
APFloat::rmNearestTiesToEven,
&losesInfo);
return !losesInfo;
}
//===----------------------------------------------------------------------===//
// ISD Namespace
//===----------------------------------------------------------------------===//
bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
auto *BV = dyn_cast<BuildVectorSDNode>(N);
if (!BV)
return false;
APInt SplatUndef;
unsigned SplatBitSize;
bool HasUndefs;
unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
EltSize) &&
EltSize == SplatBitSize;
}
// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
// specializations of the more general isConstantSplatVector()?
bool ISD::isBuildVectorAllOnes(const SDNode *N) {
// Look through a bit convert.
while (N->getOpcode() == ISD::BITCAST)
N = N->getOperand(0).getNode();
if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
unsigned i = 0, e = N->getNumOperands();
// Skip over all of the undef values.
while (i != e && N->getOperand(i).isUndef())
++i;
// Do not accept an all-undef vector.
if (i == e) return false;
// Do not accept build_vectors that aren't all constants or which have non-~0
// elements. We have to be a bit careful here, as the type of the constant
// may not be the same as the type of the vector elements due to type
// legalization (the elements are promoted to a legal type for the target and
// a vector of a type may be legal when the base element type is not).
// We only want to check enough bits to cover the vector elements, because
// we care if the resultant vector is all ones, not whether the individual
// constants are.
SDValue NotZero = N->getOperand(i);
unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
if (CN->getAPIntValue().countTrailingOnes() < EltSize)
return false;
} else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
return false;
} else
return false;
// Okay, we have at least one ~0 value, check to see if the rest match or are
// undefs. Even with the above element type twiddling, this should be OK, as
// the same type legalization should have applied to all the elements.
for (++i; i != e; ++i)
if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
return false;
return true;
}
bool ISD::isBuildVectorAllZeros(const SDNode *N) {
// Look through a bit convert.
while (N->getOpcode() == ISD::BITCAST)
N = N->getOperand(0).getNode();
if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
bool IsAllUndef = true;
for (const SDValue &Op : N->op_values()) {
if (Op.isUndef())
continue;
IsAllUndef = false;
// Do not accept build_vectors that aren't all constants or which have non-0
// elements. We have to be a bit careful here, as the type of the constant
// may not be the same as the type of the vector elements due to type
// legalization (the elements are promoted to a legal type for the target
// and a vector of a type may be legal when the base element type is not).
// We only want to check enough bits to cover the vector elements, because
// we care if the resultant vector is all zeros, not whether the individual
// constants are.
unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
if (CN->getAPIntValue().countTrailingZeros() < EltSize)
return false;
} else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
return false;
} else
return false;
}
// Do not accept an all-undef vector.
if (IsAllUndef)
return false;
return true;
}
bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
if (N->getOpcode() != ISD::BUILD_VECTOR)
return false;
for (const SDValue &Op : N->op_values()) {
if (Op.isUndef())
continue;
if (!isa<ConstantSDNode>(Op))
return false;
}
return true;
}
bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
if (N->getOpcode() != ISD::BUILD_VECTOR)
return false;
for (const SDValue &Op : N->op_values()) {
if (Op.isUndef())
continue;
if (!isa<ConstantFPSDNode>(Op))
return false;
}
return true;
}
bool ISD::allOperandsUndef(const SDNode *N) {
// Return false if the node has no operands.
// This is "logically inconsistent" with the definition of "all" but
// is probably the desired behavior.
if (N->getNumOperands() == 0)
return false;
return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
}
bool ISD::matchUnaryPredicate(SDValue Op,
std::function<bool(ConstantSDNode *)> Match,
bool AllowUndefs) {
// FIXME: Add support for scalar UNDEF cases?
if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
return Match(Cst);
// FIXME: Add support for vector UNDEF cases?
if (ISD::BUILD_VECTOR != Op.getOpcode())
return false;
EVT SVT = Op.getValueType().getScalarType();
for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
if (AllowUndefs && Op.getOperand(i).isUndef()) {
if (!Match(nullptr))
return false;
continue;
}
auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
return false;
}
return true;
}
bool ISD::matchBinaryPredicate(
SDValue LHS, SDValue RHS,
std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
bool AllowUndefs, bool AllowTypeMismatch) {
if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
return false;
// TODO: Add support for scalar UNDEF cases?
if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
return Match(LHSCst, RHSCst);
// TODO: Add support for vector UNDEF cases?
if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
ISD::BUILD_VECTOR != RHS.getOpcode())
return false;
EVT SVT = LHS.getValueType().getScalarType();
for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
SDValue LHSOp = LHS.getOperand(i);
SDValue RHSOp = RHS.getOperand(i);
bool LHSUndef = AllowUndefs && LHSOp.isUndef();
bool RHSUndef = AllowUndefs && RHSOp.isUndef();
auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
return false;
if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
LHSOp.getValueType() != RHSOp.getValueType()))
return false;
if (!Match(LHSCst, RHSCst))
return false;
}
return true;
}
ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
switch (ExtType) {
case ISD::EXTLOAD:
return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
case ISD::SEXTLOAD:
return ISD::SIGN_EXTEND;
case ISD::ZEXTLOAD:
return ISD::ZERO_EXTEND;
default:
break;
}
llvm_unreachable("Invalid LoadExtType");
}
ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
// To perform this operation, we just need to swap the L and G bits of the
// operation.
unsigned OldL = (Operation >> 2) & 1;
unsigned OldG = (Operation >> 1) & 1;
return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
(OldL << 1) | // New G bit
(OldG << 2)); // New L bit.
}
static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
unsigned Operation = Op;
if (isIntegerLike)
Operation ^= 7; // Flip L, G, E bits, but not U.
else
Operation ^= 15; // Flip all of the condition bits.
if (Operation > ISD::SETTRUE2)
Operation &= ~8; // Don't let N and U bits get set.
return ISD::CondCode(Operation);
}
ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
return getSetCCInverseImpl(Op, Type.isInteger());
}
ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
bool isIntegerLike) {
return getSetCCInverseImpl(Op, isIntegerLike);
}
/// For an integer comparison, return 1 if the comparison is a signed operation
/// and 2 if the result is an unsigned comparison. Return zero if the operation
/// does not depend on the sign of the input (setne and seteq).
static int isSignedOp(ISD::CondCode Opcode) {
switch (Opcode) {
default: llvm_unreachable("Illegal integer setcc operation!");
case ISD::SETEQ:
case ISD::SETNE: return 0;
case ISD::SETLT:
case ISD::SETLE:
case ISD::SETGT:
case ISD::SETGE: return 1;
case ISD::SETULT:
case ISD::SETULE:
case ISD::SETUGT:
case ISD::SETUGE: return 2;
}
}
ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
EVT Type) {
bool IsInteger = Type.isInteger();
if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
// Cannot fold a signed integer setcc with an unsigned integer setcc.
return ISD::SETCC_INVALID;
unsigned Op = Op1 | Op2; // Combine all of the condition bits.
// If the N and U bits get set, then the resultant comparison DOES suddenly
// care about orderedness, and it is true when ordered.
if (Op > ISD::SETTRUE2)
Op &= ~16; // Clear the U bit if the N bit is set.
// Canonicalize illegal integer setcc's.
if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
Op = ISD::SETNE;
return ISD::CondCode(Op);
}
ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
EVT Type) {
bool IsInteger = Type.isInteger();
if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
// Cannot fold a signed setcc with an unsigned setcc.
return ISD::SETCC_INVALID;
// Combine all of the condition bits.
ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
// Canonicalize illegal integer setcc's.
if (IsInteger) {
switch (Result) {
default: break;
case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
case ISD::SETOEQ: // SETEQ & SETU[LG]E
case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
}
}
return Result;
}
//===----------------------------------------------------------------------===//
// SDNode Profile Support
//===----------------------------------------------------------------------===//
/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
ID.AddInteger(OpC);
}
/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
/// solely with their pointer.
static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
ID.AddPointer(VTList.VTs);
}
/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
static void AddNodeIDOperands(FoldingSetNodeID &ID,
ArrayRef<SDValue> Ops) {
for (auto& Op : Ops) {
ID.AddPointer(Op.getNode());
ID.AddInteger(Op.getResNo());
}
}
/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
static void AddNodeIDOperands(FoldingSetNodeID &ID,
ArrayRef<SDUse> Ops) {
for (auto& Op : Ops) {
ID.AddPointer(Op.getNode());
ID.AddInteger(Op.getResNo());
}
}
static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
SDVTList VTList, ArrayRef<SDValue> OpList) {
AddNodeIDOpcode(ID, OpC);
AddNodeIDValueTypes(ID, VTList);
AddNodeIDOperands(ID, OpList);
}
/// If this is an SDNode with special info, add this info to the NodeID data.
static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
switch (N->getOpcode()) {
case ISD::TargetExternalSymbol:
case ISD::ExternalSymbol:
case ISD::MCSymbol:
llvm_unreachable("Should only be used on nodes with operands");
default: break; // Normal nodes don't need extra info.
case ISD::TargetConstant:
case ISD::Constant: {
const ConstantSDNode *C = cast<ConstantSDNode>(N);
ID.AddPointer(C->getConstantIntValue());
ID.AddBoolean(C->isOpaque());
break;
}
case ISD::TargetConstantFP:
case ISD::ConstantFP:
ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
break;
case ISD::TargetGlobalAddress:
case ISD::GlobalAddress:
case ISD::TargetGlobalTLSAddress:
case ISD::GlobalTLSAddress: {
const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
ID.AddPointer(GA->getGlobal());
ID.AddInteger(GA->getOffset());
ID.AddInteger(GA->getTargetFlags());
break;
}
case ISD::BasicBlock:
ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
break;
case ISD::Register:
ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
break;
case ISD::RegisterMask:
ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
break;
case ISD::SRCVALUE:
ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
break;
case ISD::FrameIndex:
case ISD::TargetFrameIndex:
ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
break;
case ISD::LIFETIME_START:
case ISD::LIFETIME_END:
if (cast<LifetimeSDNode>(N)->hasOffset()) {
ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
}
break;
case ISD::JumpTable:
case ISD::TargetJumpTable:
ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
break;
case ISD::ConstantPool:
case ISD::TargetConstantPool: {
const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
ID.AddInteger(CP->getAlign().value());
ID.AddInteger(CP->getOffset());
if (CP->isMachineConstantPoolEntry())
CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
else
ID.AddPointer(CP->getConstVal());
ID.AddInteger(CP->getTargetFlags());
break;
}
case ISD::TargetIndex: {
const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
ID.AddInteger(TI->getIndex());
ID.AddInteger(TI->getOffset());
ID.AddInteger(TI->getTargetFlags());
break;
}
case ISD::LOAD: {
const LoadSDNode *LD = cast<LoadSDNode>(N);
ID.AddInteger(LD->getMemoryVT().getRawBits());
ID.AddInteger(LD->getRawSubclassData());
ID.AddInteger(LD->getPointerInfo().getAddrSpace());
break;
}
case ISD::STORE: {
const StoreSDNode *ST = cast<StoreSDNode>(N);
ID.AddInteger(ST->getMemoryVT().getRawBits());
ID.AddInteger(ST->getRawSubclassData());
ID.AddInteger(ST->getPointerInfo().getAddrSpace());
break;
}
case ISD::MLOAD: {
const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
ID.AddInteger(MLD->getMemoryVT().getRawBits());
ID.AddInteger(MLD->getRawSubclassData());
ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
break;
}
case ISD::MSTORE: {
const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
ID.AddInteger(MST->getMemoryVT().getRawBits());
ID.AddInteger(MST->getRawSubclassData());
ID.AddInteger(MST->getPointerInfo().getAddrSpace());
break;
}
case ISD::MGATHER: {
const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
ID.AddInteger(MG->getMemoryVT().getRawBits());
ID.AddInteger(MG->getRawSubclassData());
ID.AddInteger(MG->getPointerInfo().getAddrSpace());
break;
}
case ISD::MSCATTER: {
const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
ID.AddInteger(MS->getMemoryVT().getRawBits());
ID.AddInteger(MS->getRawSubclassData());
ID.AddInteger(MS->getPointerInfo().getAddrSpace());
break;
}
case ISD::ATOMIC_CMP_SWAP:
case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
case ISD::ATOMIC_SWAP:
case ISD::ATOMIC_LOAD_ADD:
case ISD::ATOMIC_LOAD_SUB:
case ISD::ATOMIC_LOAD_AND:
case ISD::ATOMIC_LOAD_CLR:
case ISD::ATOMIC_LOAD_OR:
case ISD::ATOMIC_LOAD_XOR:
case ISD::ATOMIC_LOAD_NAND:
case ISD::ATOMIC_LOAD_MIN:
case ISD::ATOMIC_LOAD_MAX:
case ISD::ATOMIC_LOAD_UMIN:
case ISD::ATOMIC_LOAD_UMAX:
case ISD::ATOMIC_LOAD:
case ISD::ATOMIC_STORE: {
const AtomicSDNode *AT = cast<AtomicSDNode>(N);
ID.AddInteger(AT->getMemoryVT().getRawBits());
ID.AddInteger(AT->getRawSubclassData());
ID.AddInteger(AT->getPointerInfo().getAddrSpace());
break;
}
case ISD::PREFETCH: {
const MemSDNode *PF = cast<MemSDNode>(N);
ID.AddInteger(PF->getPointerInfo().getAddrSpace());
break;
}
case ISD::VECTOR_SHUFFLE: {
const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
i != e; ++i)
ID.AddInteger(SVN->getMaskElt(i));
break;
}
case ISD::TargetBlockAddress:
case ISD::BlockAddress: {
const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
ID.AddPointer(BA->getBlockAddress());
ID.AddInteger(BA->getOffset());
ID.AddInteger(BA->getTargetFlags());
break;
}
} // end switch (N->getOpcode())
// Target specific memory nodes could also have address spaces to check.
if (N->isTargetMemoryOpcode())
ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
}
/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
/// data.
static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
AddNodeIDOpcode(ID, N->getOpcode());
// Add the return value info.
AddNodeIDValueTypes(ID, N->getVTList());
// Add the operand info.
AddNodeIDOperands(ID, N->ops());
// Handle SDNode leafs with special info.
AddNodeIDCustom(ID, N);
}
//===----------------------------------------------------------------------===//
// SelectionDAG Class
//===----------------------------------------------------------------------===//
/// doNotCSE - Return true if CSE should not be performed for this node.
static bool doNotCSE(SDNode *N) {
if (N->getValueType(0) == MVT::Glue)
return true; // Never CSE anything that produces a flag.
switch (N->getOpcode()) {
default: break;
case ISD::HANDLENODE:
case ISD::EH_LABEL:
return true; // Never CSE these nodes.
}
// Check that remaining values produced are not flags.
for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
if (N->getValueType(i) == MVT::Glue)
return true; // Never CSE anything that produces a flag.
return false;
}
/// RemoveDeadNodes - This method deletes all unreachable nodes in the
/// SelectionDAG.
void SelectionDAG::RemoveDeadNodes() {
// Create a dummy node (which is not added to allnodes), that adds a reference
// to the root node, preventing it from being deleted.
HandleSDNode Dummy(getRoot());
SmallVector<SDNode*, 128> DeadNodes;
// Add all obviously-dead nodes to the DeadNodes worklist.
for (SDNode &Node : allnodes())
if (Node.use_empty())
DeadNodes.push_back(&Node);
RemoveDeadNodes(DeadNodes);
// If the root changed (e.g. it was a dead load, update the root).
setRoot(Dummy.getValue());
}
/// RemoveDeadNodes - This method deletes the unreachable nodes in the
/// given list, and any nodes that become unreachable as a result.
void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
// Process the worklist, deleting the nodes and adding their uses to the
// worklist.
while (!DeadNodes.empty()) {
SDNode *N = DeadNodes.pop_back_val();
// Skip to next node if we've already managed to delete the node. This could
// happen if replacing a node causes a node previously added to the node to
// be deleted.
if (N->getOpcode() == ISD::DELETED_NODE)
continue;
for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
DUL->NodeDeleted(N, nullptr);
// Take the node out of the appropriate CSE map.
RemoveNodeFromCSEMaps(N);
// Next, brutally remove the operand list. This is safe to do, as there are
// no cycles in the graph.
for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
SDUse &Use = *I++;
SDNode *Operand = Use.getNode();
Use.set(SDValue());
// Now that we removed this operand, see if there are no uses of it left.
if (Operand->use_empty())
DeadNodes.push_back(Operand);
}
DeallocateNode(N);
}
}
void SelectionDAG::RemoveDeadNode(SDNode *N){
SmallVector<SDNode*, 16> DeadNodes(1, N);
// Create a dummy node that adds a reference to the root node, preventing
// it from being deleted. (This matters if the root is an operand of the
// dead node.)
HandleSDNode Dummy(getRoot());
RemoveDeadNodes(DeadNodes);
}
void SelectionDAG::DeleteNode(SDNode *N) {
// First take this out of the appropriate CSE map.
RemoveNodeFromCSEMaps(N);
// Finally, remove uses due to operands of this node, remove from the
// AllNodes list, and delete the node.
DeleteNodeNotInCSEMaps(N);
}
void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
assert(N->getIterator() != AllNodes.begin() &&
"Cannot delete the entry node!");
assert(N->use_empty() && "Cannot delete a node that is not dead!");
// Drop all of the operands and decrement used node's use counts.
N->DropOperands();
DeallocateNode(N);
}
void SDDbgInfo::erase(const SDNode *Node) {
DbgValMapType::iterator I = DbgValMap.find(Node);
if (I == DbgValMap.end())
return;
for (auto &Val: I->second)
Val->setIsInvalidated();
DbgValMap.erase(I);
}
void SelectionDAG::DeallocateNode(SDNode *N) {
// If we have operands, deallocate them.
removeOperands(N);
NodeAllocator.Deallocate(AllNodes.remove(N));
// Set the opcode to DELETED_NODE to help catch bugs when node
// memory is reallocated.
// FIXME: There are places in SDag that have grown a dependency on the opcode
// value in the released node.
__asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
N->NodeType = ISD::DELETED_NODE;
// If any of the SDDbgValue nodes refer to this SDNode, invalidate
// them and forget about that node.
DbgInfo->erase(N);
}
#ifndef NDEBUG
/// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
static void VerifySDNode(SDNode *N) {
switch (N->getOpcode()) {
default:
break;
case ISD::BUILD_PAIR: {
EVT VT = N->getValueType(0);
assert(N->getNumValues() == 1 && "Too many results!");
assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
"Wrong return type!");
assert(N->getNumOperands() == 2 && "Wrong number of operands!");
assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
"Mismatched operand types!");
assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
"Wrong operand type!");
assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
"Wrong return type size");
break;
}
case ISD::BUILD_VECTOR: {
assert(N->getNumValues() == 1 && "Too many results!");
assert(N->getValueType(0).isVector() && "Wrong return type!");
assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
"Wrong number of operands!");
EVT EltVT = N->getValueType(0).getVectorElementType();
for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
assert((I->getValueType() == EltVT ||
(EltVT.isInteger() && I->getValueType().isInteger() &&
EltVT.bitsLE(I->getValueType()))) &&
"Wrong operand type!");
assert(I->getValueType() == N->getOperand(0).getValueType() &&
"Operands must all have the same type");
}
break;
}
}
}
#endif // NDEBUG
/// Insert a newly allocated node into the DAG.
///
/// Handles insertion into the all nodes list and CSE map, as well as
/// verification and other common operations when a new node is allocated.
void SelectionDAG::InsertNode(SDNode *N) {
AllNodes.push_back(N);
#ifndef NDEBUG
N->PersistentId = NextPersistentId++;
VerifySDNode(N);
#endif
for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
DUL->NodeInserted(N);
}
/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
/// correspond to it. This is useful when we're about to delete or repurpose
/// the node. We don't want future request for structurally identical nodes
/// to return N anymore.
bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
bool Erased = false;
switch (N->getOpcode()) {
case ISD::HANDLENODE: return false; // noop.
case ISD::CONDCODE:
assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
"Cond code doesn't exist!");
Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
break;
case ISD::ExternalSymbol:
Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
break;
case ISD::TargetExternalSymbol: {
ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
ESN->getSymbol(), ESN->getTargetFlags()));
break;
}
case ISD::MCSymbol: {
auto *MCSN = cast<MCSymbolSDNode>(N);
Erased = MCSymbols.erase(MCSN->getMCSymbol());
break;
}
case ISD::VALUETYPE: {
EVT VT = cast<VTSDNode>(N)->getVT();
if (VT.isExtended()) {
Erased = ExtendedValueTypeNodes.erase(VT);
} else {
Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
}
break;
}
default:
// Remove it from the CSE Map.
assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
Erased = CSEMap.RemoveNode(N);
break;
}
#ifndef NDEBUG
// Verify that the node was actually in one of the CSE maps, unless it has a
// flag result (which cannot be CSE'd) or is one of the special cases that are
// not subject to CSE.
if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
!N->isMachineOpcode() && !doNotCSE(N)) {
N->dump(this);
dbgs() << "\n";
llvm_unreachable("Node is not in map!");
}
#endif
return Erased;
}
/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
/// maps and modified in place. Add it back to the CSE maps, unless an identical
/// node already exists, in which case transfer all its users to the existing
/// node. This transfer can potentially trigger recursive merging.
void
SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
// For node types that aren't CSE'd, just act as if no identical node
// already exists.
if (!doNotCSE(N)) {
SDNode *Existing = CSEMap.GetOrInsertNode(N);
if (Existing != N) {
// If there was already an existing matching node, use ReplaceAllUsesWith
// to replace the dead one with the existing one. This can cause
// recursive merging of other unrelated nodes down the line.
ReplaceAllUsesWith(N, Existing);
// N is now dead. Inform the listeners and delete it.
for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
DUL->NodeDeleted(N, Existing);
DeleteNodeNotInCSEMaps(N);
return;
}
}
// If the node doesn't already exist, we updated it. Inform listeners.
for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
DUL->NodeUpdated(N);
}
/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
/// were replaced with those specified. If this node is never memoized,
/// return null, otherwise return a pointer to the slot it would take. If a
/// node already exists with these operands, the slot will be non-null.
SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
void *&InsertPos) {
if (doNotCSE(N))
return nullptr;
SDValue Ops[] = { Op };
FoldingSetNodeID ID;
AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
AddNodeIDCustom(ID, N);
SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
if (Node)
Node->intersectFlagsWith(N->getFlags());
return Node;
}
/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
/// were replaced with those specified. If this node is never memoized,
/// return null, otherwise return a pointer to the slot it would take. If a
/// node already exists with these operands, the slot will be non-null.
SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
SDValue Op1, SDValue Op2,
void *&InsertPos) {
if (doNotCSE(N))
return nullptr;
SDValue Ops[] = { Op1, Op2 };
FoldingSetNodeID ID;
AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
AddNodeIDCustom(ID, N);
SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
if (Node)
Node->intersectFlagsWith(N->getFlags());
return Node;
}
/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
/// were replaced with those specified. If this node is never memoized,
/// return null, otherwise return a pointer to the slot it would take. If a
/// node already exists with these operands, the slot will be non-null.
SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
void *&InsertPos) {
if (doNotCSE(N))
return nullptr;
FoldingSetNodeID ID;
AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
AddNodeIDCustom(ID, N);
SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
if (Node)
Node->intersectFlagsWith(N->getFlags());
return Node;
}
Align SelectionDAG::getEVTAlign(EVT VT) const {
Type *Ty = VT == MVT::iPTR ?
PointerType::get(Type::getInt8Ty(*getContext()), 0) :
VT.getTypeForEVT(*getContext());
return getDataLayout().getABITypeAlign(Ty);
}
// EntryNode could meaningfully have debug info if we can find it...
SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
: TM(tm), OptLevel(OL),
EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
Root(getEntryNode()) {
InsertNode(&EntryNode);
DbgInfo = new SDDbgInfo();
}
void SelectionDAG::init(MachineFunction &NewMF,
OptimizationRemarkEmitter &NewORE,
Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
LegacyDivergenceAnalysis * Divergence,
ProfileSummaryInfo *PSIin,
BlockFrequencyInfo *BFIin) {
MF = &NewMF;
SDAGISelPass = PassPtr;
ORE = &NewORE;
TLI = getSubtarget().getTargetLowering();
TSI = getSubtarget().getSelectionDAGInfo();
LibInfo = LibraryInfo;
Context = &MF->getFunction().getContext();
DA = Divergence;
PSI = PSIin;
BFI = BFIin;
}
SelectionDAG::~SelectionDAG() {
assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
allnodes_clear();
OperandRecycler.clear(OperandAllocator);
delete DbgInfo;
}
bool SelectionDAG::shouldOptForSize() const {
return MF->getFunction().hasOptSize() ||
llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
}
void SelectionDAG::allnodes_clear() {
assert(&*AllNodes.begin() == &EntryNode);
AllNodes.remove(AllNodes.begin());
while (!AllNodes.empty())
DeallocateNode(&AllNodes.front());
#ifndef NDEBUG
NextPersistentId = 0;
#endif
}
SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
void *&InsertPos) {
SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
if (N) {
switch (N->getOpcode()) {
default: break;
case ISD::Constant:
case ISD::ConstantFP:
llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
"debug location. Use another overload.");
}
}
return N;
}
SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
const SDLoc &DL, void *&InsertPos) {
SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
if (N) {
switch (N->getOpcode()) {
case ISD::Constant:
case ISD::ConstantFP:
// Erase debug location from the node if the node is used at several
// different places. Do not propagate one location to all uses as it
// will cause a worse single stepping debugging experience.
if (N->getDebugLoc() != DL.getDebugLoc())
N->setDebugLoc(DebugLoc());
break;
default:
// When the node's point of use is located earlier in the instruction
// sequence than its prior point of use, update its debug info to the
// earlier location.
if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
N->setDebugLoc(DL.getDebugLoc());
break;
}
}
return N;
}
void SelectionDAG::clear() {
allnodes_clear();
OperandRecycler.clear(OperandAllocator);
OperandAllocator.Reset();
CSEMap.clear();
ExtendedValueTypeNodes.clear();
ExternalSymbols.clear();
TargetExternalSymbols.clear();
MCSymbols.clear();
SDCallSiteDbgInfo.clear();
std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
static_cast<CondCodeSDNode*>(nullptr));
std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
static_cast<SDNode*>(nullptr));
EntryNode.UseList = nullptr;
InsertNode(&EntryNode);
Root = getEntryNode();
DbgInfo->clear();
}
SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
return VT.bitsGT(Op.getValueType())
? getNode(ISD::FP_EXTEND, DL, VT, Op)
: getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
}
std::pair<SDValue, SDValue>
SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
const SDLoc &DL, EVT VT) {
assert(!VT.bitsEq(Op.getValueType()) &&
"Strict no-op FP extend/round not allowed.");
SDValue Res =
VT.bitsGT(Op.getValueType())
? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
: getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
{Chain, Op, getIntPtrConstant(0, DL)});
return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
}
SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
return VT.bitsGT(Op.getValueType()) ?
getNode(ISD::ANY_EXTEND, DL, VT, Op) :
getNode(ISD::TRUNCATE, DL, VT, Op);
}
SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
return VT.bitsGT(Op.getValueType()) ?
getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
getNode(ISD::TRUNCATE, DL, VT, Op);
}
SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
return VT.bitsGT(Op.getValueType()) ?
getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
getNode(ISD::TRUNCATE, DL, VT, Op);
}
SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
EVT OpVT) {
if (VT.bitsLE(Op.getValueType()))
return getNode(ISD::TRUNCATE, SL, VT, Op);
TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
}
SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
EVT OpVT = Op.getValueType();
assert(VT.isInteger() && OpVT.isInteger() &&
"Cannot getZeroExtendInReg FP types");
assert(VT.isVector() == OpVT.isVector() &&
"getZeroExtendInReg type should be vector iff the operand "
"type is vector!");
assert((!VT.isVector() ||
VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
"Vector element counts must match in getZeroExtendInReg");
assert(VT.bitsLE(OpVT) && "Not extending!");
if (OpVT == VT)
return Op;
APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
VT.getScalarSizeInBits());
return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
}
SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
// Only unsigned pointer semantics are supported right now. In the future this
// might delegate to TLI to check pointer signedness.
return getZExtOrTrunc(Op, DL, VT);
}
SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
// Only unsigned pointer semantics are supported right now. In the future this
// might delegate to TLI to check pointer signedness.
return getZeroExtendInReg(Op, DL, VT);
}
/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
EVT EltVT = VT.getScalarType();
SDValue NegOne =
getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
return getNode(ISD::XOR, DL, VT, Val, NegOne);
}
SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
return getNode(ISD::XOR, DL, VT, Val, TrueValue);
}
SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
EVT OpVT) {
if (!V)
return getConstant(0, DL, VT);
switch (TLI->getBooleanContents(OpVT)) {
case TargetLowering::ZeroOrOneBooleanContent:
case TargetLowering::UndefinedBooleanContent:
return getConstant(1, DL, VT);
case TargetLowering::ZeroOrNegativeOneBooleanContent:
return getAllOnesConstant(DL, VT);
}
llvm_unreachable("Unexpected boolean content enum!");
}
SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
bool isT, bool isO) {
EVT EltVT = VT.getScalarType();
assert((EltVT.getSizeInBits() >= 64 ||
(uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
"getConstant with a uint64_t value that doesn't fit in the type!");
return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
}
SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
bool isT, bool isO) {
return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
}
SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
EVT VT, bool isT, bool isO) {
assert(VT.isInteger() && "Cannot create FP integer constant!");
EVT EltVT = VT.getScalarType();
const ConstantInt *Elt = &Val;
// In some cases the vector type is legal but the element type is illegal and
// needs to be promoted, for example v8i8 on ARM. In this case, promote the
// inserted value (the type does not need to match the vector element type).
// Any extra bits introduced will be truncated away.
if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
TargetLowering::TypePromoteInteger) {
EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
Elt = ConstantInt::get(*getContext(), NewVal);
}
// In other cases the element type is illegal and needs to be expanded, for
// example v2i64 on MIPS32. In this case, find the nearest legal type, split
// the value into n parts and use a vector type with n-times the elements.
// Then bitcast to the type requested.
// Legalizing constants too early makes the DAGCombiner's job harder so we
// only legalize if the DAG tells us we must produce legal types.
else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
TLI->getTypeAction(*getContext(), EltVT) ==
TargetLowering::TypeExpandInteger) {
const APInt &NewVal = Elt->getValue();
EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
// Check the temporary vector is the correct size. If this fails then
// getTypeToTransformTo() probably returned a type whose size (in bits)
// isn't a power-of-2 factor of the requested type size.
assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
SmallVector<SDValue, 2> EltParts;
for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
.zextOrTrunc(ViaEltSizeInBits), DL,
ViaEltVT, isT, isO));
}
// EltParts is currently in little endian order. If we actually want
// big-endian order then reverse it now.
if (getDataLayout().isBigEndian())
std::reverse(EltParts.begin(), EltParts.end());
// The elements must be reversed when the element order is different
// to the endianness of the elements (because the BITCAST is itself a
// vector shuffle in this situation). However, we do not need any code to
// perform this reversal because getConstant() is producing a vector
// splat.
// This situation occurs in MIPS MSA.
SmallVector<SDValue, 8> Ops;
for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
return V;
}
assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
"APInt size does not match type size!");
unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
ID.AddPointer(Elt);
ID.AddBoolean(isO);
void *IP = nullptr;
SDNode *N = nullptr;
if ((N = FindNodeOrInsertPos(ID, DL, IP)))
if (!VT.isVector())
return SDValue(N, 0);
if (!N) {
N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
CSEMap.InsertNode(N, IP);
InsertNode(N);
NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
}
SDValue Result(N, 0);
if (VT.isScalableVector())
Result = getSplatVector(VT, DL, Result);
else if (VT.isVector())
Result = getSplatBuildVector(VT, DL, Result);
return Result;
}
SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
bool isTarget) {
return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
}
SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
const SDLoc &DL, bool LegalTypes) {
assert(VT.isInteger() && "Shift amount is not an integer type!");
EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
return getConstant(Val, DL, ShiftVT);
}
SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
bool isTarget) {
return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
}
SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
bool isTarget) {
return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
}
SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
EVT VT, bool isTarget) {
assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
EVT EltVT = VT.getScalarType();
// Do the map lookup using the actual bit pattern for the floating point
// value, so that we don't have problems with 0.0 comparing equal to -0.0, and
// we don't have issues with SNANs.
unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
ID.AddPointer(&V);
void *IP = nullptr;
SDNode *N = nullptr;
if ((N = FindNodeOrInsertPos(ID, DL, IP)))
if (!VT.isVector())
return SDValue(N, 0);
if (!N) {
N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
CSEMap.InsertNode(N, IP);
InsertNode(N);
}
SDValue Result(N, 0);
if (VT.isScalableVector())
Result = getSplatVector(VT, DL, Result);
else if (VT.isVector())
Result = getSplatBuildVector(VT, DL, Result);
NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
return Result;
}
SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
bool isTarget) {
EVT EltVT = VT.getScalarType();
if (EltVT == MVT::f32)
return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
else if (EltVT == MVT::f64)
return getConstantFP(APFloat(Val), DL, VT, isTarget);
else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
EltVT == MVT::f16 || EltVT == MVT::bf16) {
bool Ignored;
APFloat APF = APFloat(Val);
APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
&Ignored);
return getConstantFP(APF, DL, VT, isTarget);
} else
llvm_unreachable("Unsupported type in getConstantFP");
}
SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
EVT VT, int64_t Offset, bool isTargetGA,
unsigned TargetFlags) {
assert((TargetFlags == 0 || isTargetGA) &&
"Cannot set target flags on target-independent globals");
// Truncate (with sign-extension) the offset value to the pointer size.
unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
if (BitWidth < 64)
Offset = SignExtend64(Offset, BitWidth);
unsigned Opc;
if (GV->isThreadLocal())
Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
else
Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(VT), None);
ID.AddPointer(GV);
ID.AddInteger(Offset);
ID.AddInteger(TargetFlags);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
return SDValue(E, 0);
auto *N = newSDNode<GlobalAddressSDNode>(
Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(VT), None);
ID.AddInteger(FI);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
unsigned TargetFlags) {
assert((TargetFlags == 0 || isTarget) &&
"Cannot set target flags on target-independent jump tables");
unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(VT), None);
ID.AddInteger(JTI);
ID.AddInteger(TargetFlags);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
MaybeAlign Alignment, int Offset,
bool isTarget, unsigned TargetFlags) {
assert((TargetFlags == 0 || isTarget) &&
"Cannot set target flags on target-independent globals");
if (!Alignment)
Alignment = shouldOptForSize()
? getDataLayout().getABITypeAlign(C->getType())
: getDataLayout().getPrefTypeAlign(C->getType());
unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(VT), None);
ID.AddInteger(Alignment->value());
ID.AddInteger(Offset);
ID.AddPointer(C);
ID.AddInteger(TargetFlags);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
TargetFlags);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V = SDValue(N, 0);
NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
return V;
}
SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
MaybeAlign Alignment, int Offset,
bool isTarget, unsigned TargetFlags) {
assert((TargetFlags == 0 || isTarget) &&
"Cannot set target flags on target-independent globals");
if (!Alignment)
Alignment = getDataLayout().getPrefTypeAlign(C->getType());
unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(VT), None);
ID.AddInteger(Alignment->value());
ID.AddInteger(Offset);
C->addSelectionDAGCSEId(ID);
ID.AddInteger(TargetFlags);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
TargetFlags);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
unsigned TargetFlags) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
ID.AddInteger(Index);
ID.AddInteger(Offset);
ID.AddInteger(TargetFlags);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
ID.AddPointer(MBB);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<BasicBlockSDNode>(MBB);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getValueType(EVT VT) {
if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
ValueTypeNodes.size())
ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
SDNode *&N = VT.isExtended() ?
ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
if (N) return SDValue(N, 0);
N = newSDNode<VTSDNode>(VT);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
SDNode *&N = ExternalSymbols[Sym];
if (N) return SDValue(N, 0);
N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
SDNode *&N = MCSymbols[Sym];
if (N)
return SDValue(N, 0);
N = newSDNode<MCSymbolSDNode>(Sym, VT);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
unsigned TargetFlags) {
SDNode *&N =
TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
if (N) return SDValue(N, 0);
N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
if ((unsigned)Cond >= CondCodeNodes.size())
CondCodeNodes.resize(Cond+1);
if (!CondCodeNodes[Cond]) {
auto *N = newSDNode<CondCodeSDNode>(Cond);
CondCodeNodes[Cond] = N;
InsertNode(N);
}
return SDValue(CondCodeNodes[Cond], 0);
}
/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
/// point at N1 to point at N2 and indices that point at N2 to point at N1.
static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
std::swap(N1, N2);
ShuffleVectorSDNode::commuteMask(M);
}
SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
SDValue N2, ArrayRef<int> Mask) {
assert(VT.getVectorNumElements() == Mask.size() &&
"Must have the same number of vector elements as mask elements!");
assert(VT == N1.getValueType() && VT == N2.getValueType() &&
"Invalid VECTOR_SHUFFLE");
// Canonicalize shuffle undef, undef -> undef
if (N1.isUndef() && N2.isUndef())
return getUNDEF(VT);
// Validate that all indices in Mask are within the range of the elements
// input to the shuffle.
int NElts = Mask.size();
assert(llvm::all_of(Mask,
[&](int M) { return M < (NElts * 2) && M >= -1; }) &&
"Index out of range");
// Copy the mask so we can do any needed cleanup.
SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
// Canonicalize shuffle v, v -> v, undef
if (N1 == N2) {
N2 = getUNDEF(VT);
for (int i = 0; i != NElts; ++i)
if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
}
// Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
if (N1.isUndef())
commuteShuffle(N1, N2, MaskVec);
if (TLI->hasVectorBlend()) {
// If shuffling a splat, try to blend the splat instead. We do this here so
// that even when this arises during lowering we don't have to re-handle it.
auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
BitVector UndefElements;
SDValue Splat = BV->getSplatValue(&UndefElements);
if (!Splat)
return;
for (int i = 0; i < NElts; ++i) {
if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
continue;
// If this input comes from undef, mark it as such.
if (UndefElements[MaskVec[i] - Offset]) {
MaskVec[i] = -1;
continue;
}
// If we can blend a non-undef lane, use that instead.
if (!UndefElements[i])
MaskVec[i] = i + Offset;
}
};
if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
BlendSplat(N1BV, 0);
if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
BlendSplat(N2BV, NElts);
}
// Canonicalize all index into lhs, -> shuffle lhs, undef
// Canonicalize all index into rhs, -> shuffle rhs, undef
bool AllLHS = true, AllRHS = true;
bool N2Undef = N2.isUndef();
for (int i = 0; i != NElts; ++i) {
if (MaskVec[i] >= NElts) {
if (N2Undef)
MaskVec[i] = -1;
else
AllLHS = false;
} else if (MaskVec[i] >= 0) {
AllRHS = false;
}
}
if (AllLHS && AllRHS)
return getUNDEF(VT);
if (AllLHS && !N2Undef)
N2 = getUNDEF(VT);
if (AllRHS) {
N1 = getUNDEF(VT);
commuteShuffle(N1, N2, MaskVec);
}
// Reset our undef status after accounting for the mask.
N2Undef = N2.isUndef();
// Re-check whether both sides ended up undef.
if (N1.isUndef() && N2Undef)
return getUNDEF(VT);
// If Identity shuffle return that node.
bool Identity = true, AllSame = true;
for (int i = 0; i != NElts; ++i) {
if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
if (MaskVec[i] != MaskVec[0]) AllSame = false;
}
if (Identity && NElts)
return N1;
// Shuffling a constant splat doesn't change the result.
if (N2Undef) {
SDValue V = N1;
// Look through any bitcasts. We check that these don't change the number
// (and size) of elements and just changes their types.
while (V.getOpcode() == ISD::BITCAST)
V = V->getOperand(0);
// A splat should always show up as a build vector node.
if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
BitVector UndefElements;
SDValue Splat = BV->getSplatValue(&UndefElements);
// If this is a splat of an undef, shuffling it is also undef.
if (Splat && Splat.isUndef())
return getUNDEF(VT);
bool SameNumElts =
V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
// We only have a splat which can skip shuffles if there is a splatted
// value and no undef lanes rearranged by the shuffle.
if (Splat && UndefElements.none()) {
// Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
// number of elements match or the value splatted is a zero constant.
if (SameNumElts)
return N1;
if (auto *C = dyn_cast<ConstantSDNode>(Splat))
if (C->isNullValue())
return N1;
}
// If the shuffle itself creates a splat, build the vector directly.
if (AllSame && SameNumElts) {
EVT BuildVT = BV->getValueType(0);
const SDValue &Splatted = BV->getOperand(MaskVec[0]);
SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
// We may have jumped through bitcasts, so the type of the
// BUILD_VECTOR may not match the type of the shuffle.
if (BuildVT != VT)
NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
return NewBV;
}
}
}
FoldingSetNodeID ID;
SDValue Ops[2] = { N1, N2 };
AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
for (int i = 0; i != NElts; ++i)
ID.AddInteger(MaskVec[i]);
void* IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
return SDValue(E, 0);
// Allocate the mask array for the node out of the BumpPtrAllocator, since
// SDNode doesn't have access to it. This memory will be "leaked" when
// the node is deallocated, but recovered when the NodeAllocator is released.
int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
llvm::copy(MaskVec, MaskAlloc);
auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
dl.getDebugLoc(), MaskAlloc);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V = SDValue(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
EVT VT = SV.getValueType(0);
SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
ShuffleVectorSDNode::commuteMask(MaskVec);
SDValue Op0 = SV.getOperand(0);
SDValue Op1 = SV.getOperand(1);
return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
}
SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
ID.AddInteger(RegNo);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
ID.AddPointer(RegMask);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
MCSymbol *Label) {
return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
}
SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
SDValue Root, MCSymbol *Label) {
FoldingSetNodeID ID;
SDValue Ops[] = { Root };
AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
ID.AddPointer(Label);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N =
newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
int64_t Offset, bool isTarget,
unsigned TargetFlags) {
unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, getVTList(VT), None);
ID.AddPointer(BA);
ID.AddInteger(Offset);
ID.AddInteger(TargetFlags);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getSrcValue(const Value *V) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
ID.AddPointer(V);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<SrcValueSDNode>(V);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getMDNode(const MDNode *MD) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
ID.AddPointer(MD);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, IP))
return SDValue(E, 0);
auto *N = newSDNode<MDNodeSDNode>(MD);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
if (VT == V.getValueType())
return V;
return getNode(ISD::BITCAST, SDLoc(V), VT, V);
}
SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
unsigned SrcAS, unsigned DestAS) {
SDValue Ops[] = {Ptr};
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
ID.AddInteger(SrcAS);
ID.AddInteger(DestAS);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
return SDValue(E, 0);
auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
VT, SrcAS, DestAS);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getFreeze(SDValue V) {
return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
}
/// getShiftAmountOperand - Return the specified value casted to
/// the target's desired shift amount type.
SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
EVT OpTy = Op.getValueType();
EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
if (OpTy == ShTy || OpTy.isVector()) return Op;
return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
}
SDValue SelectionDAG::expandVAArg(SDNode *Node) {
SDLoc dl(Node);
const TargetLowering &TLI = getTargetLoweringInfo();
const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
EVT VT = Node->getValueType(0);
SDValue Tmp1 = Node->getOperand(0);
SDValue Tmp2 = Node->getOperand(1);
const MaybeAlign MA(Node->getConstantOperandVal(3));
SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
Tmp2, MachinePointerInfo(V));
SDValue VAList = VAListLoad;
if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
getConstant(MA->value() - 1, dl, VAList.getValueType()));
VAList =
getNode(ISD::AND, dl, VAList.getValueType(), VAList,
getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
}
// Increment the pointer, VAList, to the next vaarg
Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
getConstant(getDataLayout().getTypeAllocSize(
VT.getTypeForEVT(*getContext())),
dl, VAList.getValueType()));
// Store the incremented VAList to the legalized pointer
Tmp1 =
getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
// Load the actual argument out of the pointer VAList
return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
}
SDValue SelectionDAG::expandVACopy(SDNode *Node) {
SDLoc dl(Node);
const TargetLowering &TLI = getTargetLoweringInfo();
// This defaults to loading a pointer from the input and storing it to the
// output, returning the chain.
const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
SDValue Tmp1 =
getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
Node->getOperand(2), MachinePointerInfo(VS));
return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
MachinePointerInfo(VD));
}
Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
const DataLayout &DL = getDataLayout();
Type *Ty = VT.getTypeForEVT(*getContext());
Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
if (TLI->isTypeLegal(VT) || !VT.isVector())
return RedAlign;
const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
const Align StackAlign = TFI->getStackAlign();
// See if we can choose a smaller ABI alignment in cases where it's an
// illegal vector type that will get broken down.
if (RedAlign > StackAlign) {
EVT IntermediateVT;
MVT RegisterVT;
unsigned NumIntermediates;
TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
NumIntermediates, RegisterVT);
Ty = IntermediateVT.getTypeForEVT(*getContext());
Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
if (RedAlign2 < RedAlign)
RedAlign = RedAlign2;
}
return RedAlign;
}
SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
MachineFrameInfo &MFI = MF->getFrameInfo();
const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
int StackID = 0;
if (Bytes.isScalable())
StackID = TFI->getStackIDForScalableVectors();
int FrameIdx = MFI.CreateStackObject(Bytes, Alignment,
false, nullptr, StackID);
return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
}
SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
Type *Ty = VT.getTypeForEVT(*getContext());
Align StackAlign =
std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
return CreateStackTemporary(VT.getStoreSize(), StackAlign);
}
SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
TypeSize Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
Type *Ty1 = VT1.getTypeForEVT(*getContext());
Type *Ty2 = VT2.getTypeForEVT(*getContext());
const DataLayout &DL = getDataLayout();
Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
return CreateStackTemporary(Bytes, Align);
}
SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
ISD::CondCode Cond, const SDLoc &dl) {
EVT OpVT = N1.getValueType();
// These setcc operations always fold.
switch (Cond) {
default: break;
case ISD::SETFALSE:
case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
case ISD::SETTRUE:
case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
case ISD::SETOEQ:
case ISD::SETOGT:
case ISD::SETOGE:
case ISD::SETOLT:
case ISD::SETOLE:
case ISD::SETONE:
case ISD::SETO:
case ISD::SETUO:
case ISD::SETUEQ:
case ISD::SETUNE:
assert(!OpVT.isInteger() && "Illegal setcc for integer!");
break;
}
if (OpVT.isInteger()) {
// For EQ and NE, we can always pick a value for the undef to make the
// predicate pass or fail, so we can return undef.
// Matches behavior in llvm::ConstantFoldCompareInstruction.
// icmp eq/ne X, undef -> undef.
if ((N1.isUndef() || N2.isUndef()) &&
(Cond == ISD::SETEQ || Cond == ISD::SETNE))
return getUNDEF(VT);
// If both operands are undef, we can return undef for int comparison.
// icmp undef, undef -> undef.
if (N1.isUndef() && N2.isUndef())
return getUNDEF(VT);
// icmp X, X -> true/false
// icmp X, undef -> true/false because undef could be X.
if (N1 == N2)
return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
}
if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
const APInt &C2 = N2C->getAPIntValue();
if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
const APInt &C1 = N1C->getAPIntValue();
switch (Cond) {
default: llvm_unreachable("Unknown integer setcc!");
case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
}
}
}
auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
if (N1CFP && N2CFP) {
APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
switch (Cond) {
default: break;
case ISD::SETEQ: if (R==APFloat::cmpUnordered)
return getUNDEF(VT);
LLVM_FALLTHROUGH;
case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
OpVT);
case ISD::SETNE: if (R==APFloat::cmpUnordered)
return getUNDEF(VT);
LLVM_FALLTHROUGH;
case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
R==APFloat::cmpLessThan, dl, VT,
OpVT);
case ISD::SETLT: if (R==APFloat::cmpUnordered)
return getUNDEF(VT);
LLVM_FALLTHROUGH;
case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
OpVT);
case ISD::SETGT: if (R==APFloat::cmpUnordered)
return getUNDEF(VT);
LLVM_FALLTHROUGH;
case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
VT, OpVT);
case ISD::SETLE: if (R==APFloat::cmpUnordered)
return getUNDEF(VT);
LLVM_FALLTHROUGH;
case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
R==APFloat::cmpEqual, dl, VT,
OpVT);
case ISD::SETGE: if (R==APFloat::cmpUnordered)
return getUNDEF(VT);
LLVM_FALLTHROUGH;
case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
R==APFloat::cmpEqual, dl, VT, OpVT);
case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
OpVT);
case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
OpVT);
case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
R==APFloat::cmpEqual, dl, VT,
OpVT);
case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
OpVT);
case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
R==APFloat::cmpLessThan, dl, VT,
OpVT);
case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
R==APFloat::cmpUnordered, dl, VT,
OpVT);
case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
VT, OpVT);
case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
OpVT);
}
} else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
// Ensure that the constant occurs on the RHS.
ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
return SDValue();
return getSetCC(dl, VT, N2, N1, SwappedCond);
} else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
(OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
// If an operand is known to be a nan (or undef that could be a nan), we can
// fold it.
// Choosing NaN for the undef will always make unordered comparison succeed
// and ordered comparison fails.
// Matches behavior in llvm::ConstantFoldCompareInstruction.
switch (ISD::getUnorderedFlavor(Cond)) {
default:
llvm_unreachable("Unknown flavor!");
case 0: // Known false.
return getBoolConstant(false, dl, VT, OpVT);
case 1: // Known true.
return getBoolConstant(true, dl, VT, OpVT);
case 2: // Undefined.
return getUNDEF(VT);
}
}
// Could not fold it.
return SDValue();
}
/// See if the specified operand can be simplified with the knowledge that only
/// the bits specified by DemandedBits are used.
/// TODO: really we should be making this into the DAG equivalent of
/// SimplifyMultipleUseDemandedBits and not generate any new nodes.
SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
EVT VT = V.getValueType();
APInt DemandedElts = VT.isVector()
? APInt::getAllOnesValue(VT.getVectorNumElements())
: APInt(1, 1);
return GetDemandedBits(V, DemandedBits, DemandedElts);
}
/// See if the specified operand can be simplified with the knowledge that only
/// the bits specified by DemandedBits are used in the elements specified by
/// DemandedElts.
/// TODO: really we should be making this into the DAG equivalent of
/// SimplifyMultipleUseDemandedBits and not generate any new nodes.
SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
const APInt &DemandedElts) {
switch (V.getOpcode()) {
default:
return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
*this, 0);
case ISD::Constant: {
const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
APInt NewVal = CVal & DemandedBits;
if (NewVal != CVal)
return getConstant(NewVal, SDLoc(V), V.getValueType());
break;
}
case ISD::SRL:
// Only look at single-use SRLs.
if (!V.getNode()->hasOneUse())
break;
if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
// See if we can recursively simplify the LHS.
unsigned Amt = RHSC->getZExtValue();
// Watch out for shift count overflow though.
if (Amt >= DemandedBits.getBitWidth())
break;
APInt SrcDemandedBits = DemandedBits << Amt;
if (SDValue SimplifyLHS =
GetDemandedBits(V.getOperand(0), SrcDemandedBits))
return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
V.getOperand(1));
}
break;
}
return SDValue();
}
/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
/// use this predicate to simplify operations downstream.
bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
unsigned BitWidth = Op.getScalarValueSizeInBits();
return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
}
/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
/// this predicate to simplify operations downstream. Mask is known to be zero
/// for bits that V cannot have.
bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
unsigned Depth) const {
return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
}
/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
/// DemandedElts. We use this predicate to simplify operations downstream.
/// Mask is known to be zero for bits that V cannot have.
bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
const APInt &DemandedElts,
unsigned Depth) const {
return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
}
/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
unsigned Depth) const {
return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
}
/// isSplatValue - Return true if the vector V has the same value
/// across all DemandedElts. For scalable vectors it does not make
/// sense to specify which elements are demanded or undefined, therefore
/// they are simply ignored.
bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
APInt &UndefElts) {
EVT VT = V.getValueType();
assert(VT.isVector() && "Vector type expected");
if (!VT.isScalableVector() && !DemandedElts)
return false; // No demanded elts, better to assume we don't know anything.
// Deal with some common cases here that work for both fixed and scalable
// vector types.
switch (V.getOpcode()) {
case ISD::SPLAT_VECTOR:
return true;
case ISD::ADD:
case ISD::SUB:
case ISD::AND: {
APInt UndefLHS, UndefRHS;
SDValue LHS = V.getOperand(0);
SDValue RHS = V.getOperand(1);
if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
isSplatValue(RHS, DemandedElts, UndefRHS)) {
UndefElts = UndefLHS | UndefRHS;
return true;
}
break;
}
case ISD::TRUNCATE:
case ISD::SIGN_EXTEND:
case ISD::ZERO_EXTEND:
return isSplatValue(V.getOperand(0), DemandedElts, UndefElts);
}
// We don't support other cases than those above for scalable vectors at
// the moment.
if (VT.isScalableVector())
return false;
unsigned NumElts = VT.getVectorNumElements();
assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
UndefElts = APInt::getNullValue(NumElts);
switch (V.getOpcode()) {
case ISD::BUILD_VECTOR: {
SDValue Scl;
for (unsigned i = 0; i != NumElts; ++i) {
SDValue Op = V.getOperand(i);
if (Op.isUndef()) {
UndefElts.setBit(i);
continue;
}
if (!DemandedElts[i])
continue;
if (Scl && Scl != Op)
return false;
Scl = Op;
}
return true;
}
case ISD::VECTOR_SHUFFLE: {
// Check if this is a shuffle node doing a splat.
// TODO: Do we need to handle shuffle(splat, undef, mask)?
int SplatIndex = -1;
ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
for (int i = 0; i != (int)NumElts; ++i) {
int M = Mask[i];
if (M < 0) {
UndefElts.setBit(i);
continue;
}
if (!DemandedElts[i])
continue;
if (0 <= SplatIndex && SplatIndex != M)
return false;
SplatIndex = M;
}
return true;
}
case ISD::EXTRACT_SUBVECTOR: {
// Offset the demanded elts by the subvector index.
SDValue Src = V.getOperand(0);
uint64_t Idx = V.getConstantOperandVal(1);
unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
APInt UndefSrcElts;
APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts)) {
UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
return true;
}
break;
}
}
return false;
}
/// Helper wrapper to main isSplatValue function.
bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
EVT VT = V.getValueType();
assert(VT.isVector() && "Vector type expected");
APInt UndefElts;
APInt DemandedElts;
// For now we don't support this with scalable vectors.
if (!VT.isScalableVector())
DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
return isSplatValue(V, DemandedElts, UndefElts) &&
(AllowUndefs || !UndefElts);
}
SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
V = peekThroughExtractSubvectors(V);
EVT VT = V.getValueType();
unsigned Opcode = V.getOpcode();
switch (Opcode) {
default: {
APInt UndefElts;
APInt DemandedElts;
if (!VT.isScalableVector())
DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
if (isSplatValue(V, DemandedElts, UndefElts)) {
if (VT.isScalableVector()) {
// DemandedElts and UndefElts are ignored for scalable vectors, since
// the only supported cases are SPLAT_VECTOR nodes.
SplatIdx = 0;
} else {
// Handle case where all demanded elements are UNDEF.
if (DemandedElts.isSubsetOf(UndefElts)) {
SplatIdx = 0;
return getUNDEF(VT);
}
SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
}
return V;
}
break;
}
case ISD::SPLAT_VECTOR:
SplatIdx = 0;
return V;
case ISD::VECTOR_SHUFFLE: {
if (VT.isScalableVector())
return SDValue();
// Check if this is a shuffle node doing a splat.
// TODO - remove this and rely purely on SelectionDAG::isSplatValue,
// getTargetVShiftNode currently struggles without the splat source.
auto *SVN = cast<ShuffleVectorSDNode>(V);
if (!SVN->isSplat())
break;
int Idx = SVN->getSplatIndex();
int NumElts = V.getValueType().getVectorNumElements();
SplatIdx = Idx % NumElts;
return V.getOperand(Idx / NumElts);
}
}
return SDValue();
}
SDValue SelectionDAG::getSplatValue(SDValue V) {
int SplatIdx;
if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
SrcVector.getValueType().getScalarType(), SrcVector,
getVectorIdxConstant(SplatIdx, SDLoc(V)));
return SDValue();
}
const APInt *
SelectionDAG::getValidShiftAmountConstant(SDValue V,
const APInt &DemandedElts) const {
assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
V.getOpcode() == ISD::SRA) &&
"Unknown shift node");
unsigned BitWidth = V.getScalarValueSizeInBits();
if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
// Shifting more than the bitwidth is not valid.
const APInt &ShAmt = SA->getAPIntValue();
if (ShAmt.ult(BitWidth))
return &ShAmt;
}
return nullptr;
}
const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
SDValue V, const APInt &DemandedElts) const {
assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
V.getOpcode() == ISD::SRA) &&
"Unknown shift node");
if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
return ValidAmt;
unsigned BitWidth = V.getScalarValueSizeInBits();
auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
if (!BV)
return nullptr;
const APInt *MinShAmt = nullptr;
for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
if (!DemandedElts[i])
continue;
auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
if (!SA)
return nullptr;
// Shifting more than the bitwidth is not valid.
const APInt &ShAmt = SA->getAPIntValue();
if (ShAmt.uge(BitWidth))
return nullptr;
if (MinShAmt && MinShAmt->ule(ShAmt))
continue;
MinShAmt = &ShAmt;
}
return MinShAmt;
}
const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
SDValue V, const APInt &DemandedElts) const {
assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
V.getOpcode() == ISD::SRA) &&
"Unknown shift node");
if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
return ValidAmt;
unsigned BitWidth = V.getScalarValueSizeInBits();
auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
if (!BV)
return nullptr;
const APInt *MaxShAmt = nullptr;
for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
if (!DemandedElts[i])
continue;
auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
if (!SA)
return nullptr;
// Shifting more than the bitwidth is not valid.
const APInt &ShAmt = SA->getAPIntValue();
if (ShAmt.uge(BitWidth))
return nullptr;
if (MaxShAmt && MaxShAmt->uge(ShAmt))
continue;
MaxShAmt = &ShAmt;
}
return MaxShAmt;
}
/// Determine which bits of Op are known to be either zero or one and return
/// them in Known. For vectors, the known bits are those that are shared by
/// every vector element.
KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
EVT VT = Op.getValueType();
// TOOD: Until we have a plan for how to represent demanded elements for
// scalable vectors, we can just bail out for now.
if (Op.getValueType().isScalableVector()) {
unsigned BitWidth = Op.getScalarValueSizeInBits();
return KnownBits(BitWidth);
}
APInt DemandedElts = VT.isVector()
? APInt::getAllOnesValue(VT.getVectorNumElements())
: APInt(1, 1);
return computeKnownBits(Op, DemandedElts, Depth);
}
/// Determine which bits of Op are known to be either zero or one and return
/// them in Known. The DemandedElts argument allows us to only collect the known
/// bits that are shared by the requested vector elements.
KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
unsigned Depth) const {
unsigned BitWidth = Op.getScalarValueSizeInBits();
KnownBits Known(BitWidth); // Don't know anything.
// TOOD: Until we have a plan for how to represent demanded elements for
// scalable vectors, we can just bail out for now.
if (Op.getValueType().isScalableVector())
return Known;
if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
// We know all of the bits for a constant!
Known.One = C->getAPIntValue();
Known.Zero = ~Known.One;
return Known;
}
if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
// We know all of the bits for a constant fp!
Known.One = C->getValueAPF().bitcastToAPInt();
Known.Zero = ~Known.One;
return Known;
}
if (Depth >= MaxRecursionDepth)
return Known; // Limit search depth.
KnownBits Known2;
unsigned NumElts = DemandedElts.getBitWidth();
assert((!Op.getValueType().isVector() ||
NumElts == Op.getValueType().getVectorNumElements()) &&
"Unexpected vector size");
if (!DemandedElts)
return Known; // No demanded elts, better to assume we don't know anything.
unsigned Opcode = Op.getOpcode();
switch (Opcode) {
case ISD::BUILD_VECTOR:
// Collect the known bits that are shared by every demanded vector element.
Known.Zero.setAllBits(); Known.One.setAllBits();
for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
if (!DemandedElts[i])
continue;
SDValue SrcOp = Op.getOperand(i);
Known2 = computeKnownBits(SrcOp, Depth + 1);
// BUILD_VECTOR can implicitly truncate sources, we must handle this.
if (SrcOp.getValueSizeInBits() != BitWidth) {
assert(SrcOp.getValueSizeInBits() > BitWidth &&
"Expected BUILD_VECTOR implicit truncation");
Known2 = Known2.trunc(BitWidth);
}
// Known bits are the values that are shared by every demanded element.
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
}
break;
case ISD::VECTOR_SHUFFLE: {
// Collect the known bits that are shared by every vector element referenced
// by the shuffle.
APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
Known.Zero.setAllBits(); Known.One.setAllBits();
const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
for (unsigned i = 0; i != NumElts; ++i) {
if (!DemandedElts[i])
continue;
int M = SVN->getMaskElt(i);
if (M < 0) {
// For UNDEF elements, we don't know anything about the common state of
// the shuffle result.
Known.resetAll();
DemandedLHS.clearAllBits();
DemandedRHS.clearAllBits();
break;
}
if ((unsigned)M < NumElts)
DemandedLHS.setBit((unsigned)M % NumElts);
else
DemandedRHS.setBit((unsigned)M % NumElts);
}
// Known bits are the values that are shared by every demanded element.
if (!!DemandedLHS) {
SDValue LHS = Op.getOperand(0);
Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
}
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
if (!!DemandedRHS) {
SDValue RHS = Op.getOperand(1);
Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
}
break;
}
case ISD::CONCAT_VECTORS: {
// Split DemandedElts and test each of the demanded subvectors.
Known.Zero.setAllBits(); Known.One.setAllBits();
EVT SubVectorVT = Op.getOperand(0).getValueType();
unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
unsigned NumSubVectors = Op.getNumOperands();
for (unsigned i = 0; i != NumSubVectors; ++i) {
APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
DemandedSub = DemandedSub.trunc(NumSubVectorElts);
if (!!DemandedSub) {
SDValue Sub = Op.getOperand(i);
Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
}
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
}
break;
}
case ISD::INSERT_SUBVECTOR: {
// Demand any elements from the subvector and the remainder from the src its
// inserted into.
SDValue Src = Op.getOperand(0);
SDValue Sub = Op.getOperand(1);
uint64_t Idx = Op.getConstantOperandVal(2);
unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
APInt DemandedSrcElts = DemandedElts;
DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
Known.One.setAllBits();
Known.Zero.setAllBits();
if (!!DemandedSubElts) {
Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
if (Known.isUnknown())
break; // early-out.
}
if (!!DemandedSrcElts) {
Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
}
break;
}
case ISD::EXTRACT_SUBVECTOR: {
// Offset the demanded elts by the subvector index.
SDValue Src = Op.getOperand(0);
// Bail until we can represent demanded elements for scalable vectors.
if (Src.getValueType().isScalableVector())
break;
uint64_t Idx = Op.getConstantOperandVal(1);
unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
break;
}
case ISD::SCALAR_TO_VECTOR: {
// We know about scalar_to_vector as much as we know about it source,
// which becomes the first element of otherwise unknown vector.
if (DemandedElts != 1)
break;
SDValue N0 = Op.getOperand(0);
Known = computeKnownBits(N0, Depth + 1);
if (N0.getValueSizeInBits() != BitWidth)
Known = Known.trunc(BitWidth);
break;
}
case ISD::BITCAST: {
SDValue N0 = Op.getOperand(0);
EVT SubVT = N0.getValueType();
unsigned SubBitWidth = SubVT.getScalarSizeInBits();
// Ignore bitcasts from unsupported types.
if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
break;
// Fast handling of 'identity' bitcasts.
if (BitWidth == SubBitWidth) {
Known = computeKnownBits(N0, DemandedElts, Depth + 1);
break;
}
bool IsLE = getDataLayout().isLittleEndian();
// Bitcast 'small element' vector to 'large element' scalar/vector.
if ((BitWidth % SubBitWidth) == 0) {
assert(N0.getValueType().isVector() && "Expected bitcast from vector");
// Collect known bits for the (larger) output by collecting the known
// bits from each set of sub elements and shift these into place.
// We need to separately call computeKnownBits for each set of
// sub elements as the knownbits for each is likely to be different.
unsigned SubScale = BitWidth / SubBitWidth;
APInt SubDemandedElts(NumElts * SubScale, 0);
for (unsigned i = 0; i != NumElts; ++i)
if (DemandedElts[i])
SubDemandedElts.setBit(i * SubScale);
for (unsigned i = 0; i != SubScale; ++i) {
Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
Depth + 1);
unsigned Shifts = IsLE ? i : SubScale - 1 - i;
Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
}
}
// Bitcast 'large element' scalar/vector to 'small element' vector.
if ((SubBitWidth % BitWidth) == 0) {
assert(Op.getValueType().isVector() && "Expected bitcast to vector");
// Collect known bits for the (smaller) output by collecting the known
// bits from the overlapping larger input elements and extracting the
// sub sections we actually care about.
unsigned SubScale = SubBitWidth / BitWidth;
APInt SubDemandedElts(NumElts / SubScale, 0);
for (unsigned i = 0; i != NumElts; ++i)
if (DemandedElts[i])
SubDemandedElts.setBit(i / SubScale);
Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
Known.Zero.setAllBits(); Known.One.setAllBits();
for (unsigned i = 0; i != NumElts; ++i)
if (DemandedElts[i]) {
unsigned Shifts = IsLE ? i : NumElts - 1 - i;
unsigned Offset = (Shifts % SubScale) * BitWidth;
Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
}
}
break;
}
case ISD::AND:
Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known &= Known2;
break;
case ISD::OR:
Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known |= Known2;
break;
case ISD::XOR:
Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known ^= Known2;
break;
case ISD::MUL: {
Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If low bits are zero in either operand, output low known-0 bits.
// Also compute a conservative estimate for high known-0 bits.
// More trickiness is possible, but this is sufficient for the
// interesting case of alignment computation.
unsigned TrailZ = Known.countMinTrailingZeros() +
Known2.countMinTrailingZeros();
unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
Known2.countMinLeadingZeros(),
BitWidth) - BitWidth;
Known.resetAll();
Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
break;
}
case ISD::UDIV: {
// For the purposes of computing leading zeros we can conservatively
// treat a udiv as a logical right shift by the power of 2 known to
// be less than the denominator.
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
unsigned LeadZ = Known2.countMinLeadingZeros();
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
if (RHSMaxLeadingZeros != BitWidth)
LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Known.Zero.setHighBits(LeadZ);
break;
}
case ISD::SELECT:
case ISD::VSELECT:
Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
// Only known if known in both the LHS and RHS.
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
break;
case ISD::SELECT_CC:
Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
// Only known if known in both the LHS and RHS.
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
break;
case ISD::SMULO:
case ISD::UMULO:
case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
if (Op.getResNo() != 1)
break;
// The boolean result conforms to getBooleanContents.
// If we know the result of a setcc has the top bits zero, use this info.
// We know that we have an integer-based boolean since these operations
// are only available for integer.
if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
TargetLowering::ZeroOrOneBooleanContent &&
BitWidth > 1)
Known.Zero.setBitsFrom(1);
break;
case ISD::SETCC:
case ISD::STRICT_FSETCC:
case ISD::STRICT_FSETCCS: {
unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
// If we know the result of a setcc has the top bits zero, use this info.
if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
TargetLowering::ZeroOrOneBooleanContent &&
BitWidth > 1)
Known.Zero.setBitsFrom(1);
break;
}
case ISD::SHL:
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (const APInt *ShAmt = getValidShiftAmountConstant(Op, DemandedElts)) {
unsigned Shift = ShAmt->getZExtValue();
Known.Zero <<= Shift;
Known.One <<= Shift;
// Low bits are known zero.
Known.Zero.setLowBits(Shift);
break;
}
// No matter the shift amount, the trailing zeros will stay zero.
Known.Zero = APInt::getLowBitsSet(BitWidth, Known.countMinTrailingZeros());
Known.One.clearAllBits();
// Minimum shift low bits are known zero.
if (const APInt *ShMinAmt =
getValidMinimumShiftAmountConstant(Op, DemandedElts))
Known.Zero.setLowBits(ShMinAmt->getZExtValue());
break;
case ISD::SRL:
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (const APInt *ShAmt = getValidShiftAmountConstant(Op, DemandedElts)) {
unsigned Shift = ShAmt->getZExtValue();
Known.Zero.lshrInPlace(Shift);
Known.One.lshrInPlace(Shift);
// High bits are known zero.
Known.Zero.setHighBits(Shift);
break;
}
// No matter the shift amount, the leading zeros will stay zero.
Known.Zero = APInt::getHighBitsSet(BitWidth, Known.countMinLeadingZeros());
Known.One.clearAllBits();
// Minimum shift high bits are known zero.
if (const APInt *ShMinAmt =
getValidMinimumShiftAmountConstant(Op, DemandedElts))
Known.Zero.setHighBits(ShMinAmt->getZExtValue());
break;
case ISD::SRA:
if (const APInt *ShAmt = getValidShiftAmountConstant(Op, DemandedElts)) {
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
unsigned Shift = ShAmt->getZExtValue();
// Sign extend known zero/one bit (else is unknown).
Known.Zero.ashrInPlace(Shift);
Known.One.ashrInPlace(Shift);
}
break;
case ISD::FSHL:
case ISD::FSHR:
if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
unsigned Amt = C->getAPIntValue().urem(BitWidth);
// For fshl, 0-shift returns the 1st arg.
// For fshr, 0-shift returns the 2nd arg.
if (Amt == 0) {
Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
DemandedElts, Depth + 1);
break;
}
// fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
// fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
if (Opcode == ISD::FSHL) {
Known.One <<= Amt;
Known.Zero <<= Amt;
Known2.One.lshrInPlace(BitWidth - Amt);
Known2.Zero.lshrInPlace(BitWidth - Amt);
} else {
Known.One <<= BitWidth - Amt;
Known.Zero <<= BitWidth - Amt;
Known2.One.lshrInPlace(Amt);
Known2.Zero.lshrInPlace(Amt);
}
Known.One |= Known2.One;
Known.Zero |= Known2.Zero;
}
break;
case ISD::SIGN_EXTEND_INREG: {
EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
unsigned EBits = EVT.getScalarSizeInBits();
// Sign extension. Compute the demanded bits in the result that are not
// present in the input.
APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
APInt InSignMask = APInt::getSignMask(EBits);
APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
// If the sign extended bits are demanded, we know that the sign
// bit is demanded.
InSignMask = InSignMask.zext(BitWidth);
if (NewBits.getBoolValue())
InputDemandedBits |= InSignMask;
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known.One &= InputDemandedBits;
Known.Zero &= InputDemandedBits;
// If the sign bit of the input is known set or clear, then we know the
// top bits of the result.
if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
Known.Zero |= NewBits;
Known.One &= ~NewBits;
} else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
Known.One |= NewBits;
Known.Zero &= ~NewBits;
} else { // Input sign bit unknown
Known.Zero &= ~NewBits;
Known.One &= ~NewBits;
}
break;
}
case ISD::CTTZ:
case ISD::CTTZ_ZERO_UNDEF: {
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If we have a known 1, its position is our upper bound.
unsigned PossibleTZ = Known2.countMaxTrailingZeros();
unsigned LowBits = Log2_32(PossibleTZ) + 1;
Known.Zero.setBitsFrom(LowBits);
break;
}
case ISD::CTLZ:
case ISD::CTLZ_ZERO_UNDEF: {
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If we have a known 1, its position is our upper bound.
unsigned PossibleLZ = Known2.countMaxLeadingZeros();
unsigned LowBits = Log2_32(PossibleLZ) + 1;
Known.Zero.setBitsFrom(LowBits);
break;
}
case ISD::CTPOP: {
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If we know some of the bits are zero, they can't be one.
unsigned PossibleOnes = Known2.countMaxPopulation();
Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
break;
}
case ISD::LOAD: {
LoadSDNode *LD = cast<LoadSDNode>(Op);
const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
if (ISD::isNON_EXTLoad(LD) && Cst) {
// Determine any common known bits from the loaded constant pool value.
Type *CstTy = Cst->getType();
if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
// If its a vector splat, then we can (quickly) reuse the scalar path.
// NOTE: We assume all elements match and none are UNDEF.
if (CstTy->isVectorTy()) {
if (const Constant *Splat = Cst->getSplatValue()) {
Cst = Splat;
CstTy = Cst->getType();
}
}
// TODO - do we need to handle different bitwidths?
if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
// Iterate across all vector elements finding common known bits.
Known.One.setAllBits();
Known.Zero.setAllBits();
for (unsigned i = 0; i != NumElts; ++i) {
if (!DemandedElts[i])
continue;
if (Constant *Elt = Cst->getAggregateElement(i)) {
if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
const APInt &Value = CInt->getValue();
Known.One &= Value;
Known.Zero &= ~Value;
continue;
}
if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
APInt Value = CFP->getValueAPF().bitcastToAPInt();
Known.One &= Value;
Known.Zero &= ~Value;
continue;
}
}
Known.One.clearAllBits();
Known.Zero.clearAllBits();
break;
}
} else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
const APInt &Value = CInt->getValue();
Known.One = Value;
Known.Zero = ~Value;
} else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
APInt Value = CFP->getValueAPF().bitcastToAPInt();
Known.One = Value;
Known.Zero = ~Value;
}
}
}
} else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
// If this is a ZEXTLoad and we are looking at the loaded value.
EVT VT = LD->getMemoryVT();
unsigned MemBits = VT.getScalarSizeInBits();
Known.Zero.setBitsFrom(MemBits);
} else if (const MDNode *Ranges = LD->getRanges()) {
if (LD->getExtensionType() == ISD::NON_EXTLOAD)
computeKnownBitsFromRangeMetadata(*Ranges, Known);
}
break;
}
case ISD::ZERO_EXTEND_VECTOR_INREG: {
EVT InVT = Op.getOperand(0).getValueType();
APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
Known = Known.zext(BitWidth);
break;
}
case ISD::ZERO_EXTEND: {
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known = Known.zext(BitWidth);
break;
}
case ISD::SIGN_EXTEND_VECTOR_INREG: {
EVT InVT = Op.getOperand(0).getValueType();
APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
// If the sign bit is known to be zero or one, then sext will extend
// it to the top bits, else it will just zext.
Known = Known.sext(BitWidth);
break;
}
case ISD::SIGN_EXTEND: {
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If the sign bit is known to be zero or one, then sext will extend
// it to the top bits, else it will just zext.
Known = Known.sext(BitWidth);
break;
}
case ISD::ANY_EXTEND_VECTOR_INREG: {
EVT InVT = Op.getOperand(0).getValueType();
APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
Known = Known.anyext(BitWidth);
break;
}
case ISD::ANY_EXTEND: {
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known = Known.anyext(BitWidth);
break;
}
case ISD::TRUNCATE: {
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known = Known.trunc(BitWidth);
break;
}
case ISD::AssertZext: {
EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
Known = computeKnownBits(Op.getOperand(0), Depth+1);
Known.Zero |= (~InMask);
Known.One &= (~Known.Zero);
break;
}
case ISD::AssertAlign: {
unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
assert(LogOfAlign != 0);
// If a node is guaranteed to be aligned, set low zero bits accordingly as
// well as clearing one bits.
Known.Zero.setLowBits(LogOfAlign);
Known.One.clearLowBits(LogOfAlign);
break;
}
case ISD::FGETSIGN:
// All bits are zero except the low bit.
Known.Zero.setBitsFrom(1);
break;
case ISD::USUBO:
case ISD::SSUBO:
if (Op.getResNo() == 1) {
// If we know the result of a setcc has the top bits zero, use this info.
if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
TargetLowering::ZeroOrOneBooleanContent &&
BitWidth > 1)
Known.Zero.setBitsFrom(1);
break;
}
LLVM_FALLTHROUGH;
case ISD::SUB:
case ISD::SUBC: {
assert(Op.getResNo() == 0 &&
"We only compute knownbits for the difference here.");
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
Known, Known2);
break;
}
case ISD::UADDO:
case ISD::SADDO:
case ISD::ADDCARRY:
if (Op.getResNo() == 1) {
// If we know the result of a setcc has the top bits zero, use this info.
if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
TargetLowering::ZeroOrOneBooleanContent &&
BitWidth > 1)
Known.Zero.setBitsFrom(1);
break;
}
LLVM_FALLTHROUGH;
case ISD::ADD:
case ISD::ADDC:
case ISD::ADDE: {
assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
// With ADDE and ADDCARRY, a carry bit may be added in.
KnownBits Carry(1);
if (Opcode == ISD::ADDE)
// Can't track carry from glue, set carry to unknown.
Carry.resetAll();
else if (Opcode == ISD::ADDCARRY)
// TODO: Compute known bits for the carry operand. Not sure if it is worth
// the trouble (how often will we find a known carry bit). And I haven't
// tested this very much yet, but something like this might work:
// Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
// Carry = Carry.zextOrTrunc(1, false);
Carry.resetAll();
else
Carry.setAllZero();
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
break;
}
case ISD::SREM:
if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
const APInt &RA = Rem->getAPIntValue().abs();
if (RA.isPowerOf2()) {
APInt LowBits = RA - 1;
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// The low bits of the first operand are unchanged by the srem.
Known.Zero = Known2.Zero & LowBits;
Known.One = Known2.One & LowBits;
// If the first operand is non-negative or has all low bits zero, then
// the upper bits are all zero.
if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Known.Zero |= ~LowBits;
// If the first operand is negative and not all low bits are zero, then
// the upper bits are all one.
if (Known2.isNegative() && LowBits.intersects(Known2.One))
Known.One |= ~LowBits;
assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
}
}
break;
case ISD::UREM: {
if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
const APInt &RA = Rem->getAPIntValue();
if (RA.isPowerOf2()) {
APInt LowBits = (RA - 1);
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// The upper bits are all zero, the lower ones are unchanged.
Known.Zero = Known2.Zero | ~LowBits;
Known.One = Known2.One & LowBits;
break;
}
}
// Since the result is less than or equal to either operand, any leading
// zero bits in either operand must also exist in the result.
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
uint32_t Leaders =
std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Known.resetAll();
Known.Zero.setHighBits(Leaders);
break;
}
case ISD::EXTRACT_ELEMENT: {
Known = computeKnownBits(Op.getOperand(0), Depth+1);
const unsigned Index = Op.getConstantOperandVal(1);
const unsigned EltBitWidth = Op.getValueSizeInBits();
// Remove low part of known bits mask
Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
// Remove high part of known bit mask
Known = Known.trunc(EltBitWidth);
break;
}
case ISD::EXTRACT_VECTOR_ELT: {
SDValue InVec = Op.getOperand(0);
SDValue EltNo = Op.getOperand(1);
EVT VecVT = InVec.getValueType();
const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
const unsigned NumSrcElts = VecVT.getVectorNumElements();
// If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
// anything about the extended bits.
if (BitWidth > EltBitWidth)
Known = Known.trunc(EltBitWidth);
// If we know the element index, just demand that vector element, else for
// an unknown element index, ignore DemandedElts and demand them all.
APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
DemandedSrcElts =
APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
if (BitWidth > EltBitWidth)
Known = Known.anyext(BitWidth);
break;
}
case ISD::INSERT_VECTOR_ELT: {
// If we know the element index, split the demand between the
// source vector and the inserted element, otherwise assume we need
// the original demanded vector elements and the value.
SDValue InVec = Op.getOperand(0);
SDValue InVal = Op.getOperand(1);
SDValue EltNo = Op.getOperand(2);
bool DemandedVal = true;
APInt DemandedVecElts = DemandedElts;
auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
unsigned EltIdx = CEltNo->getZExtValue();
DemandedVal = !!DemandedElts[EltIdx];
DemandedVecElts.clearBit(EltIdx);
}
Known.One.setAllBits();
Known.Zero.setAllBits();
if (DemandedVal) {
Known2 = computeKnownBits(InVal, Depth + 1);
Known.One &= Known2.One.zextOrTrunc(BitWidth);
Known.Zero &= Known2.Zero.zextOrTrunc(BitWidth);
}
if (!!DemandedVecElts) {
Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
}
break;
}
case ISD::BITREVERSE: {
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known = Known2.reverseBits();
break;
}
case ISD::BSWAP: {
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known = Known2.byteSwap();
break;
}
case ISD::ABS: {
Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If the source's MSB is zero then we know the rest of the bits already.
if (Known2.isNonNegative()) {
Known.Zero = Known2.Zero;
Known.One = Known2.One;
break;
}
// We only know that the absolute values's MSB will be zero iff there is
// a set bit that isn't the sign bit (otherwise it could be INT_MIN).
Known2.One.clearSignBit();
if (Known2.One.getBoolValue()) {
Known.Zero = APInt::getSignMask(BitWidth);
break;
}
break;
}
case ISD::UMIN: {
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
// UMIN - we know that the result will have the maximum of the
// known zero leading bits of the inputs.
unsigned LeadZero = Known.countMinLeadingZeros();
LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
Known.Zero &= Known2.Zero;
Known.One &= Known2.One;
Known.Zero.setHighBits(LeadZero);
break;
}
case ISD::UMAX: {
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
// UMAX - we know that the result will have the maximum of the
// known one leading bits of the inputs.
unsigned LeadOne = Known.countMinLeadingOnes();
LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
Known.Zero &= Known2.Zero;
Known.One &= Known2.One;
Known.One.setHighBits(LeadOne);
break;
}
case ISD::SMIN:
case ISD::SMAX: {
// If we have a clamp pattern, we know that the number of sign bits will be
// the minimum of the clamp min/max range.
bool IsMax = (Opcode == ISD::SMAX);
ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
CstHigh =
isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
if (CstLow && CstHigh) {
if (!IsMax)
std::swap(CstLow, CstHigh);
const APInt &ValueLow = CstLow->getAPIntValue();
const APInt &ValueHigh = CstHigh->getAPIntValue();
if (ValueLow.sle(ValueHigh)) {
unsigned LowSignBits = ValueLow.getNumSignBits();
unsigned HighSignBits = ValueHigh.getNumSignBits();
unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
if (ValueLow.isNegative() && ValueHigh.isNegative()) {
Known.One.setHighBits(MinSignBits);
break;
}
if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
Known.Zero.setHighBits(MinSignBits);
break;
}
}
}
// Fallback - just get the shared known bits of the operands.
Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (Known.isUnknown()) break; // Early-out
Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
Known.Zero &= Known2.Zero;
Known.One &= Known2.One;
break;
}
case ISD::FrameIndex:
case ISD::TargetFrameIndex:
TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
Known, getMachineFunction());
break;
default:
if (Opcode < ISD::BUILTIN_OP_END)
break;
LLVM_FALLTHROUGH;
case ISD::INTRINSIC_WO_CHAIN:
case ISD::INTRINSIC_W_CHAIN:
case ISD::INTRINSIC_VOID:
// Allow the target to implement this method for its nodes.
TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
break;
}
assert(!Known.hasConflict() && "Bits known to be one AND zero?");
return Known;
}
SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
SDValue N1) const {
// X + 0 never overflow
if (isNullConstant(N1))
return OFK_Never;
KnownBits N1Known = computeKnownBits(N1);
if (N1Known.Zero.getBoolValue()) {
KnownBits N0Known = computeKnownBits(N0);
bool overflow;
(void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
if (!overflow)
return OFK_Never;
}
// mulhi + 1 never overflow
if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
(N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
return OFK_Never;
if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
KnownBits N0Known = computeKnownBits(N0);
if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
return OFK_Never;
}
return OFK_Sometime;
}
bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
EVT OpVT = Val.getValueType();
unsigned BitWidth = OpVT.getScalarSizeInBits();
// Is the constant a known power of 2?
if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
// A left-shift of a constant one will have exactly one bit set because
// shifting the bit off the end is undefined.
if (Val.getOpcode() == ISD::SHL) {
auto *C = isConstOrConstSplat(Val.getOperand(0));
if (C && C->getAPIntValue() == 1)
return true;
}
// Similarly, a logical right-shift of a constant sign-bit will have exactly
// one bit set.
if (Val.getOpcode() == ISD::SRL) {
auto *C = isConstOrConstSplat(Val.getOperand(0));
if (C && C->getAPIntValue().isSignMask())
return true;
}
// Are all operands of a build vector constant powers of two?
if (Val.getOpcode() == ISD::BUILD_VECTOR)
if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
return false;
}))
return true;
// More could be done here, though the above checks are enough
// to handle some common cases.
// Fall back to computeKnownBits to catch other known cases.
KnownBits Known = computeKnownBits(Val);
return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
}
unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
EVT VT = Op.getValueType();
// TODO: Assume we don't know anything for now.
if (VT.isScalableVector())
return 1;
APInt DemandedElts = VT.isVector()
? APInt::getAllOnesValue(VT.getVectorNumElements())
: APInt(1, 1);
return ComputeNumSignBits(Op, DemandedElts, Depth);
}
unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
unsigned Depth) const {
EVT VT = Op.getValueType();
assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
unsigned VTBits = VT.getScalarSizeInBits();
unsigned NumElts = DemandedElts.getBitWidth();
unsigned Tmp, Tmp2;
unsigned FirstAnswer = 1;
if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
const APInt &Val = C->getAPIntValue();
return Val.getNumSignBits();
}
if (Depth >= MaxRecursionDepth)
return 1; // Limit search depth.
if (!DemandedElts || VT.isScalableVector())
return 1; // No demanded elts, better to assume we don't know anything.
unsigned Opcode = Op.getOpcode();
switch (Opcode) {
default: break;
case ISD::AssertSext:
Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
return VTBits-Tmp+1;
case ISD::AssertZext:
Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
return VTBits-Tmp;
case ISD::BUILD_VECTOR:
Tmp = VTBits;
for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
if (!DemandedElts[i])
continue;
SDValue SrcOp = Op.getOperand(i);
Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
// BUILD_VECTOR can implicitly truncate sources, we must handle this.
if (SrcOp.getValueSizeInBits() != VTBits) {
assert(SrcOp.getValueSizeInBits() > VTBits &&
"Expected BUILD_VECTOR implicit truncation");
unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
}
Tmp = std::min(Tmp, Tmp2);
}
return Tmp;
case ISD::VECTOR_SHUFFLE: {
// Collect the minimum number of sign bits that are shared by every vector
// element referenced by the shuffle.
APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
for (unsigned i = 0; i != NumElts; ++i) {
int M = SVN->getMaskElt(i);
if (!DemandedElts[i])
continue;
// For UNDEF elements, we don't know anything about the common state of
// the shuffle result.
if (M < 0)
return 1;
if ((unsigned)M < NumElts)
DemandedLHS.setBit((unsigned)M % NumElts);
else
DemandedRHS.setBit((unsigned)M % NumElts);
}
Tmp = std::numeric_limits<unsigned>::max();
if (!!DemandedLHS)
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
if (!!DemandedRHS) {
Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
Tmp = std::min(Tmp, Tmp2);
}
// If we don't know anything, early out and try computeKnownBits fall-back.
if (Tmp == 1)
break;
assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
return Tmp;
}
case ISD::BITCAST: {
SDValue N0 = Op.getOperand(0);
EVT SrcVT = N0.getValueType();
unsigned SrcBits = SrcVT.getScalarSizeInBits();
// Ignore bitcasts from unsupported types..
if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
break;
// Fast handling of 'identity' bitcasts.
if (VTBits == SrcBits)
return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
bool IsLE = getDataLayout().isLittleEndian();
// Bitcast 'large element' scalar/vector to 'small element' vector.
if ((SrcBits % VTBits) == 0) {
assert(VT.isVector() && "Expected bitcast to vector");
unsigned Scale = SrcBits / VTBits;
APInt SrcDemandedElts(NumElts / Scale, 0);
for (unsigned i = 0; i != NumElts; ++i)
if (DemandedElts[i])
SrcDemandedElts.setBit(i / Scale);
// Fast case - sign splat can be simply split across the small elements.
Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
if (Tmp == SrcBits)
return VTBits;
// Slow case - determine how far the sign extends into each sub-element.
Tmp2 = VTBits;
for (unsigned i = 0; i != NumElts; ++i)
if (DemandedElts[i]) {
unsigned SubOffset = i % Scale;
SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
SubOffset = SubOffset * VTBits;
if (Tmp <= SubOffset)
return 1;
Tmp2 = std::min(Tmp2, Tmp - SubOffset);
}
return Tmp2;
}
break;
}
case ISD::SIGN_EXTEND:
Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
case ISD::SIGN_EXTEND_INREG:
// Max of the input and what this extends.
Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
Tmp = VTBits-Tmp+1;
Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
return std::max(Tmp, Tmp2);
case ISD::SIGN_EXTEND_VECTOR_INREG: {
SDValue Src = Op.getOperand(0);
EVT SrcVT = Src.getValueType();
APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
Tmp = VTBits - SrcVT.getScalarSizeInBits();
return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
}
case ISD::SRA:
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
// SRA X, C -> adds C sign bits.
if (const APInt *ShAmt =
getValidMinimumShiftAmountConstant(Op, DemandedElts))
Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
return Tmp;
case ISD::SHL:
if (const APInt *ShAmt =
getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
// shl destroys sign bits, ensure it doesn't shift out all sign bits.
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (ShAmt->ult(Tmp))
return Tmp - ShAmt->getZExtValue();
}
break;
case ISD::AND:
case ISD::OR:
case ISD::XOR: // NOT is handled here.
// Logical binary ops preserve the number of sign bits at the worst.
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
if (Tmp != 1) {
Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
FirstAnswer = std::min(Tmp, Tmp2);
// We computed what we know about the sign bits as our first
// answer. Now proceed to the generic code that uses
// computeKnownBits, and pick whichever answer is better.
}
break;
case ISD::SELECT:
case ISD::VSELECT:
Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
if (Tmp == 1) return 1; // Early out.
Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
return std::min(Tmp, Tmp2);
case ISD::SELECT_CC:
Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
if (Tmp == 1) return 1; // Early out.
Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
return std::min(Tmp, Tmp2);
case ISD::SMIN:
case ISD::SMAX: {
// If we have a clamp pattern, we know that the number of sign bits will be
// the minimum of the clamp min/max range.
bool IsMax = (Opcode == ISD::SMAX);
ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
CstHigh =
isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
if (CstLow && CstHigh) {
if (!IsMax)
std::swap(CstLow, CstHigh);
if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
Tmp = CstLow->getAPIntValue().getNumSignBits();
Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
return std::min(Tmp, Tmp2);
}
}
// Fallback - just get the minimum number of sign bits of the operands.
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (Tmp == 1)
return 1; // Early out.
Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
return std::min(Tmp, Tmp2);
}
case ISD::UMIN:
case ISD::UMAX:
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (Tmp == 1)
return 1; // Early out.
Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
return std::min(Tmp, Tmp2);
case ISD::SADDO:
case ISD::UADDO:
case ISD::SSUBO:
case ISD::USUBO:
case ISD::SMULO:
case ISD::UMULO:
if (Op.getResNo() != 1)
break;
// The boolean result conforms to getBooleanContents. Fall through.
// If setcc returns 0/-1, all bits are sign bits.
// We know that we have an integer-based boolean since these operations
// are only available for integer.
if (TLI->getBooleanContents(VT.isVector(), false) ==
TargetLowering::ZeroOrNegativeOneBooleanContent)
return VTBits;
break;
case ISD::SETCC:
case ISD::STRICT_FSETCC:
case ISD::STRICT_FSETCCS: {
unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
// If setcc returns 0/-1, all bits are sign bits.
if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
TargetLowering::ZeroOrNegativeOneBooleanContent)
return VTBits;
break;
}
case ISD::ROTL:
case ISD::ROTR:
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If we're rotating an 0/-1 value, then it stays an 0/-1 value.
if (Tmp == VTBits)
return VTBits;
if (ConstantSDNode *C =
isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
unsigned RotAmt = C->getAPIntValue().urem(VTBits);
// Handle rotate right by N like a rotate left by 32-N.
if (Opcode == ISD::ROTR)
RotAmt = (VTBits - RotAmt) % VTBits;
// If we aren't rotating out all of the known-in sign bits, return the
// number that are left. This handles rotl(sext(x), 1) for example.
if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
}
break;
case ISD::ADD:
case ISD::ADDC:
// Add can have at most one carry bit. Thus we know that the output
// is, at worst, one more bit than the inputs.
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (Tmp == 1) return 1; // Early out.
// Special case decrementing a value (ADD X, -1):
if (ConstantSDNode *CRHS =
isConstOrConstSplat(Op.getOperand(1), DemandedElts))
if (CRHS->isAllOnesValue()) {
KnownBits Known =
computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
// If the input is known to be 0 or 1, the output is 0/-1, which is all
// sign bits set.
if ((Known.Zero | 1).isAllOnesValue())
return VTBits;
// If we are subtracting one from a positive number, there is no carry
// out of the result.
if (Known.isNonNegative())
return Tmp;
}
Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
if (Tmp2 == 1) return 1; // Early out.
return std::min(Tmp, Tmp2) - 1;
case ISD::SUB:
Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
if (Tmp2 == 1) return 1; // Early out.
// Handle NEG.
if (ConstantSDNode *CLHS =
isConstOrConstSplat(Op.getOperand(0), DemandedElts))
if (CLHS->isNullValue()) {
KnownBits Known =
computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
// If the input is known to be 0 or 1, the output is 0/-1, which is all
// sign bits set.
if ((Known.Zero | 1).isAllOnesValue())
return VTBits;
// If the input is known to be positive (the sign bit is known clear),
// the output of the NEG has the same number of sign bits as the input.
if (Known.isNonNegative())
return Tmp2;
// Otherwise, we treat this like a SUB.
}
// Sub can have at most one carry bit. Thus we know that the output
// is, at worst, one more bit than the inputs.
Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
if (Tmp == 1) return 1; // Early out.
return std::min(Tmp, Tmp2) - 1;
case ISD::MUL: {
// The output of the Mul can be at most twice the valid bits in the inputs.
unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
if (SignBitsOp0 == 1)
break;
unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
if (SignBitsOp1 == 1)
break;
unsigned OutValidBits =
(VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
}
case ISD::TRUNCATE: {
// Check if the sign bits of source go down as far as the truncated value.
unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
if (NumSrcSignBits > (NumSrcBits - VTBits))
return NumSrcSignBits - (NumSrcBits - VTBits);
break;
}
case ISD::EXTRACT_ELEMENT: {
const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
const int BitWidth = Op.getValueSizeInBits();
const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
// Get reverse index (starting from 1), Op1 value indexes elements from
// little end. Sign starts at big end.
const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
// If the sign portion ends in our element the subtraction gives correct
// result. Otherwise it gives either negative or > bitwidth result
return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
}
case ISD::INSERT_VECTOR_ELT: {
// If we know the element index, split the demand between the
// source vector and the inserted element, otherwise assume we need
// the original demanded vector elements and the value.
SDValue InVec = Op.getOperand(0);
SDValue InVal = Op.getOperand(1);
SDValue EltNo = Op.getOperand(2);
bool DemandedVal = true;
APInt DemandedVecElts = DemandedElts;
auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
unsigned EltIdx = CEltNo->getZExtValue();
DemandedVal = !!DemandedElts[EltIdx];
DemandedVecElts.clearBit(EltIdx);
}
Tmp = std::numeric_limits<unsigned>::max();
if (DemandedVal) {
// TODO - handle implicit truncation of inserted elements.
if (InVal.getScalarValueSizeInBits() != VTBits)
break;
Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
Tmp = std::min(Tmp, Tmp2);
}
if (!!DemandedVecElts) {
Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
Tmp = std::min(Tmp, Tmp2);
}
assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
return Tmp;
}
case ISD::EXTRACT_VECTOR_ELT: {
SDValue InVec = Op.getOperand(0);
SDValue EltNo = Op.getOperand(1);
EVT VecVT = InVec.getValueType();
const unsigned BitWidth = Op.getValueSizeInBits();
const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
const unsigned NumSrcElts = VecVT.getVectorNumElements();
// If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
// anything about sign bits. But if the sizes match we can derive knowledge
// about sign bits from the vector operand.
if (BitWidth != EltBitWidth)
break;
// If we know the element index, just demand that vector element, else for
// an unknown element index, ignore DemandedElts and demand them all.
APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
DemandedSrcElts =
APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
}
case ISD::EXTRACT_SUBVECTOR: {
// Offset the demanded elts by the subvector index.
SDValue Src = Op.getOperand(0);
// Bail until we can represent demanded elements for scalable vectors.
if (Src.getValueType().isScalableVector())
break;
uint64_t Idx = Op.getConstantOperandVal(1);
unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
}
case ISD::CONCAT_VECTORS: {
// Determine the minimum number of sign bits across all demanded
// elts of the input vectors. Early out if the result is already 1.
Tmp = std::numeric_limits<unsigned>::max();
EVT SubVectorVT = Op.getOperand(0).getValueType();
unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
unsigned NumSubVectors = Op.getNumOperands();
for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
DemandedSub = DemandedSub.trunc(NumSubVectorElts);
if (!DemandedSub)
continue;
Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
Tmp = std::min(Tmp, Tmp2);
}
assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
return Tmp;
}
case ISD::INSERT_SUBVECTOR: {
// Demand any elements from the subvector and the remainder from the src its
// inserted into.
SDValue Src = Op.getOperand(0);
SDValue Sub = Op.getOperand(1);
uint64_t Idx = Op.getConstantOperandVal(2);
unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
APInt DemandedSrcElts = DemandedElts;
DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
Tmp = std::numeric_limits<unsigned>::max();
if (!!DemandedSubElts) {
Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
if (Tmp == 1)
return 1; // early-out
}
if (!!DemandedSrcElts) {
Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
Tmp = std::min(Tmp, Tmp2);
}
assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
return Tmp;
}
}
// If we are looking at the loaded value of the SDNode.
if (Op.getResNo() == 0) {
// Handle LOADX separately here. EXTLOAD case will fallthrough.
if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
unsigned ExtType = LD->getExtensionType();
switch (ExtType) {
default: break;
case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
Tmp = LD->getMemoryVT().getScalarSizeInBits();
return VTBits - Tmp + 1;
case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
Tmp = LD->getMemoryVT().getScalarSizeInBits();
return VTBits - Tmp;
case ISD::NON_EXTLOAD:
if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
// We only need to handle vectors - computeKnownBits should handle
// scalar cases.
Type *CstTy = Cst->getType();
if (CstTy->isVectorTy() &&
(NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
Tmp = VTBits;
for (unsigned i = 0; i != NumElts; ++i) {
if (!DemandedElts[i])
continue;
if (Constant *Elt = Cst->getAggregateElement(i)) {
if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
const APInt &Value = CInt->getValue();
Tmp = std::min(Tmp, Value.getNumSignBits());
continue;
}
if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
APInt Value = CFP->getValueAPF().bitcastToAPInt();
Tmp = std::min(Tmp, Value.getNumSignBits());
continue;
}
}
// Unknown type. Conservatively assume no bits match sign bit.
return 1;
}
return Tmp;
}
}
break;
}
}
}
// Allow the target to implement this method for its nodes.
if (Opcode >= ISD::BUILTIN_OP_END ||
Opcode == ISD::INTRINSIC_WO_CHAIN ||
Opcode == ISD::INTRINSIC_W_CHAIN ||
Opcode == ISD::INTRINSIC_VOID) {
unsigned NumBits =
TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
if (NumBits > 1)
FirstAnswer = std::max(FirstAnswer, NumBits);
}
// Finally, if we can prove that the top bits of the result are 0's or 1's,
// use this information.
KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
APInt Mask;
if (Known.isNonNegative()) { // sign bit is 0
Mask = Known.Zero;
} else if (Known.isNegative()) { // sign bit is 1;
Mask = Known.One;
} else {
// Nothing known.
return FirstAnswer;
}
// Okay, we know that the sign bit in Mask is set. Use CLO to determine
// the number of identical bits in the top of the input value.
Mask <<= Mask.getBitWidth()-VTBits;
return std::max(FirstAnswer, Mask.countLeadingOnes());
}
bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
!isa<ConstantSDNode>(Op.getOperand(1)))
return false;
if (Op.getOpcode() == ISD::OR &&
!MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
return false;
return true;
}
bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
// If we're told that NaNs won't happen, assume they won't.
if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
return true;
if (Depth >= MaxRecursionDepth)
return false; // Limit search depth.
// TODO: Handle vectors.
// If the value is a constant, we can obviously see if it is a NaN or not.
if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
return !C->getValueAPF().isNaN() ||
(SNaN && !C->getValueAPF().isSignaling());
}
unsigned Opcode = Op.getOpcode();
switch (Opcode) {
case ISD::FADD:
case ISD::FSUB:
case ISD::FMUL:
case ISD::FDIV:
case ISD::FREM:
case ISD::FSIN:
case ISD::FCOS: {
if (SNaN)
return true;
// TODO: Need isKnownNeverInfinity
return false;
}
case ISD::FCANONICALIZE:
case ISD::FEXP:
case ISD::FEXP2:
case ISD::FTRUNC:
case ISD::FFLOOR:
case ISD::FCEIL:
case ISD::FROUND:
case ISD::FROUNDEVEN:
case ISD::FRINT:
case ISD::FNEARBYINT: {
if (SNaN)
return true;
return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
}
case ISD::FABS:
case ISD::FNEG:
case ISD::FCOPYSIGN: {
return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
}
case ISD::SELECT:
return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
case ISD::FP_EXTEND:
case ISD::FP_ROUND: {
if (SNaN)
return true;
return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
}
case ISD::SINT_TO_FP:
case ISD::UINT_TO_FP:
return true;
case ISD::FMA:
case ISD::FMAD: {
if (SNaN)
return true;
return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
}
case ISD::FSQRT: // Need is known positive
case ISD::FLOG:
case ISD::FLOG2:
case ISD::FLOG10:
case ISD::FPOWI:
case ISD::FPOW: {
if (SNaN)
return true;
// TODO: Refine on operand
return false;
}
case ISD::FMINNUM:
case ISD::FMAXNUM: {
// Only one needs to be known not-nan, since it will be returned if the
// other ends up being one.
return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
}
case ISD::FMINNUM_IEEE:
case ISD::FMAXNUM_IEEE: {
if (SNaN)
return true;
// This can return a NaN if either operand is an sNaN, or if both operands
// are NaN.
return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
(isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
}
case ISD::FMINIMUM:
case ISD::FMAXIMUM: {
// TODO: Does this quiet or return the origina NaN as-is?
return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
}
case ISD::EXTRACT_VECTOR_ELT: {
return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
}
default:
if (Opcode >= ISD::BUILTIN_OP_END ||
Opcode == ISD::INTRINSIC_WO_CHAIN ||
Opcode == ISD::INTRINSIC_W_CHAIN ||
Opcode == ISD::INTRINSIC_VOID) {
return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
}
return false;
}
}
bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
assert(Op.getValueType().isFloatingPoint() &&
"Floating point type expected");
// If the value is a constant, we can obviously see if it is a zero or not.
// TODO: Add BuildVector support.
if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
return !C->isZero();
return false;
}
bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
assert(!Op.getValueType().isFloatingPoint() &&
"Floating point types unsupported - use isKnownNeverZeroFloat");
// If the value is a constant, we can obviously see if it is a zero or not.
if (ISD::matchUnaryPredicate(
Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
return true;
// TODO: Recognize more cases here.
switch (Op.getOpcode()) {
default: break;
case ISD::OR:
if (isKnownNeverZero(Op.getOperand(1)) ||
isKnownNeverZero(Op.getOperand(0)))
return true;
break;
}
return false;
}
bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
// Check the obvious case.
if (A == B) return true;
// For for negative and positive zero.
if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
if (CA->isZero() && CB->isZero()) return true;
// Otherwise they may not be equal.
return false;
}
// FIXME: unify with llvm::haveNoCommonBitsSet.
// FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
assert(A.getValueType() == B.getValueType() &&
"Values must have the same type");
return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
}
static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
ArrayRef<SDValue> Ops,
SelectionDAG &DAG) {
int NumOps = Ops.size();
assert(NumOps != 0 && "Can't build an empty vector!");
assert(!VT.isScalableVector() &&
"BUILD_VECTOR cannot be used with scalable types");
assert(VT.getVectorNumElements() == (unsigned)NumOps &&
"Incorrect element count in BUILD_VECTOR!");
// BUILD_VECTOR of UNDEFs is UNDEF.
if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
return DAG.getUNDEF(VT);
// BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
SDValue IdentitySrc;
bool IsIdentity = true;
for (int i = 0; i != NumOps; ++i) {
if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Ops[i].getOperand(0).getValueType() != VT ||
(IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
!isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
IsIdentity = false;
break;
}
IdentitySrc = Ops[i].getOperand(0);
}
if (IsIdentity)
return IdentitySrc;
return SDValue();
}
/// Try to simplify vector concatenation to an input value, undef, or build
/// vector.
static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
ArrayRef<SDValue> Ops,
SelectionDAG &DAG) {
assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
assert(llvm::all_of(Ops,
[Ops](SDValue Op) {
return Ops[0].getValueType() == Op.getValueType();
}) &&
"Concatenation of vectors with inconsistent value types!");
assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
VT.getVectorElementCount() &&
"Incorrect element count in vector concatenation!");
if (Ops.size() == 1)
return Ops[0];
// Concat of UNDEFs is UNDEF.
if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
return DAG.getUNDEF(VT);
// Scan the operands and look for extract operations from a single source
// that correspond to insertion at the same location via this concatenation:
// concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
SDValue IdentitySrc;
bool IsIdentity = true;
for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
SDValue Op = Ops[i];
unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
Op.getOperand(0).getValueType() != VT ||
(IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
Op.getConstantOperandVal(1) != IdentityIndex) {
IsIdentity = false;
break;
}
assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
"Unexpected identity source vector for concat of extracts");
IdentitySrc = Op.getOperand(0);
}
if (IsIdentity) {
assert(IdentitySrc && "Failed to set source vector of extracts");
return IdentitySrc;
}
// The code below this point is only designed to work for fixed width
// vectors, so we bail out for now.
if (VT.isScalableVector())
return SDValue();
// A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
// simplified to one big BUILD_VECTOR.
// FIXME: Add support for SCALAR_TO_VECTOR as well.
EVT SVT = VT.getScalarType();
SmallVector<SDValue, 16> Elts;
for (SDValue Op : Ops) {
EVT OpVT = Op.getValueType();
if (Op.isUndef())
Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
else if (Op.getOpcode() == ISD::BUILD_VECTOR)
Elts.append(Op->op_begin(), Op->op_end());
else
return SDValue();
}
// BUILD_VECTOR requires all inputs to be of the same type, find the
// maximum type and extend them all.
for (SDValue Op : Elts)
SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
if (SVT.bitsGT(VT.getScalarType()))
for (SDValue &Op : Elts)
Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
? DAG.getZExtOrTrunc(Op, DL, SVT)
: DAG.getSExtOrTrunc(Op, DL, SVT);
SDValue V = DAG.getBuildVector(VT, DL, Elts);
NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
return V;
}
/// Gets or creates the specified node.
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, getVTList(VT), None);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
return SDValue(E, 0);
auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
getVTList(VT));
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V = SDValue(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
SDValue Operand, const SDNodeFlags Flags) {
// Constant fold unary operations with an integer constant operand. Even
// opaque constant will be folded, because the folding of unary operations
// doesn't create new constants with different values. Nevertheless, the
// opaque flag is preserved during folding to prevent future folding with
// other constants.
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
const APInt &Val = C->getAPIntValue();
switch (Opcode) {
default: break;
case ISD::SIGN_EXTEND:
return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
C->isTargetOpcode(), C->isOpaque());
case ISD::TRUNCATE:
if (C->isOpaque())
break;
LLVM_FALLTHROUGH;
case ISD::ANY_EXTEND:
case ISD::ZERO_EXTEND:
return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
C->isTargetOpcode(), C->isOpaque());
case ISD::UINT_TO_FP:
case ISD::SINT_TO_FP: {
APFloat apf(EVTToAPFloatSemantics(VT),
APInt::getNullValue(VT.getSizeInBits()));
(void)apf.convertFromAPInt(Val,
Opcode==ISD::SINT_TO_FP,
APFloat::rmNearestTiesToEven);
return getConstantFP(apf, DL, VT);
}
case ISD::BITCAST:
if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
break;
case ISD::ABS:
return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
C->isOpaque());
case ISD::BITREVERSE:
return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
C->isOpaque());
case ISD::BSWAP:
return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
C->isOpaque());
case ISD::CTPOP:
return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
C->isOpaque());
case ISD::CTLZ:
case ISD::CTLZ_ZERO_UNDEF:
return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
C->isOpaque());
case ISD::CTTZ:
case ISD::CTTZ_ZERO_UNDEF:
return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
C->isOpaque());
case ISD::FP16_TO_FP: {
bool Ignored;
APFloat FPV(APFloat::IEEEhalf(),
(Val.getBitWidth() == 16) ? Val : Val.trunc(16));
// This can return overflow, underflow, or inexact; we don't care.
// FIXME need to be more flexible about rounding mode.
(void)FPV.convert(EVTToAPFloatSemantics(VT),
APFloat::rmNearestTiesToEven, &Ignored);
return getConstantFP(FPV, DL, VT);
}
}
}
// Constant fold unary operations with a floating point constant operand.
if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
APFloat V = C->getValueAPF(); // make copy
switch (Opcode) {
case ISD::FNEG:
V.changeSign();
return getConstantFP(V, DL, VT);
case ISD::FABS:
V.clearSign();
return getConstantFP(V, DL, VT);
case ISD::FCEIL: {
APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
if (fs == APFloat::opOK || fs == APFloat::opInexact)
return getConstantFP(V, DL, VT);
break;
}
case ISD::FTRUNC: {
APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
if (fs == APFloat::opOK || fs == APFloat::opInexact)
return getConstantFP(V, DL, VT);
break;
}
case ISD::FFLOOR: {
APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
if (fs == APFloat::opOK || fs == APFloat::opInexact)
return getConstantFP(V, DL, VT);
break;
}
case ISD::FP_EXTEND: {
bool ignored;
// This can return overflow, underflow, or inexact; we don't care.
// FIXME need to be more flexible about rounding mode.
(void)V.convert(EVTToAPFloatSemantics(VT),
APFloat::rmNearestTiesToEven, &ignored);
return getConstantFP(V, DL, VT);
}
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT: {
bool ignored;
APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
// FIXME need to be more flexible about rounding mode.
APFloat::opStatus s =
V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
break;
return getConstant(IntVal, DL, VT);
}
case ISD::BITCAST:
if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
break;
case ISD::FP_TO_FP16: {
bool Ignored;
// This can return overflow, underflow, or inexact; we don't care.
// FIXME need to be more flexible about rounding mode.
(void)V.convert(APFloat::IEEEhalf(),
APFloat::rmNearestTiesToEven, &Ignored);
return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
}
}
}
// Constant fold unary operations with a vector integer or float operand.
if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
if (BV->isConstant()) {
switch (Opcode) {
default:
// FIXME: Entirely reasonable to perform folding of other unary
// operations here as the need arises.
break;
case ISD::FNEG:
case ISD::FABS:
case ISD::FCEIL:
case ISD::FTRUNC:
case ISD::FFLOOR:
case ISD::FP_EXTEND:
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT:
case ISD::TRUNCATE:
case ISD::ANY_EXTEND:
case ISD::ZERO_EXTEND:
case ISD::SIGN_EXTEND:
case ISD::UINT_TO_FP:
case ISD::SINT_TO_FP:
case ISD::ABS:
case ISD::BITREVERSE:
case ISD::BSWAP:
case ISD::CTLZ:
case ISD::CTLZ_ZERO_UNDEF:
case ISD::CTTZ:
case ISD::CTTZ_ZERO_UNDEF:
case ISD::CTPOP: {
SDValue Ops = { Operand };
if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
return Fold;
}
}
}
}
unsigned OpOpcode = Operand.getNode()->getOpcode();
switch (Opcode) {
case ISD::FREEZE:
assert(VT == Operand.getValueType() && "Unexpected VT!");
break;
case ISD::TokenFactor:
case ISD::MERGE_VALUES:
case ISD::CONCAT_VECTORS:
return Operand; // Factor, merge or concat of one node? No need.
case ISD::BUILD_VECTOR: {
// Attempt to simplify BUILD_VECTOR.
SDValue Ops[] = {Operand};
if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
return V;
break;
}
case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
case ISD::FP_EXTEND:
assert(VT.isFloatingPoint() &&
Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
if (Operand.getValueType() == VT) return Operand; // noop conversion.
assert((!VT.isVector() ||
VT.getVectorNumElements() ==
Operand.getValueType().getVectorNumElements()) &&
"Vector element count mismatch!");
assert(Operand.getValueType().bitsLT(VT) &&
"Invalid fpext node, dst < src!");
if (Operand.isUndef())
return getUNDEF(VT);
break;
case ISD::FP_TO_SINT:
case ISD::FP_TO_UINT:
if (Operand.isUndef())
return getUNDEF(VT);
break;
case ISD::SINT_TO_FP:
case ISD::UINT_TO_FP:
// [us]itofp(undef) = 0, because the result value is bounded.
if (Operand.isUndef())
return getConstantFP(0.0, DL, VT);
break;
case ISD::SIGN_EXTEND:
assert(VT.isInteger() && Operand.getValueType().isInteger() &&
"Invalid SIGN_EXTEND!");
assert(VT.isVector() == Operand.getValueType().isVector() &&
"SIGN_EXTEND result type type should be vector iff the operand "
"type is vector!");
if (Operand.getValueType() == VT) return Operand; // noop extension
assert((!VT.isVector() ||
VT.getVectorElementCount() ==
Operand.getValueType().getVectorElementCount()) &&
"Vector element count mismatch!");
assert(Operand.getValueType().bitsLT(VT) &&
"Invalid sext node, dst < src!");
if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
else if (OpOpcode == ISD::UNDEF)
// sext(undef) = 0, because the top bits will all be the same.
return getConstant(0, DL, VT);
break;
case ISD::ZERO_EXTEND:
assert(VT.isInteger() && Operand.getValueType().isInteger() &&
"Invalid ZERO_EXTEND!");
assert(VT.isVector() == Operand.getValueType().isVector() &&
"ZERO_EXTEND result type type should be vector iff the operand "
"type is vector!");
if (Operand.getValueType() == VT) return Operand; // noop extension
assert((!VT.isVector() ||
VT.getVectorElementCount() ==
Operand.getValueType().getVectorElementCount()) &&
"Vector element count mismatch!");
assert(Operand.getValueType().bitsLT(VT) &&
"Invalid zext node, dst < src!");
if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
else if (OpOpcode == ISD::UNDEF)
// zext(undef) = 0, because the top bits will be zero.
return getConstant(0, DL, VT);
break;
case ISD::ANY_EXTEND:
assert(VT.isInteger() && Operand.getValueType().isInteger() &&
"Invalid ANY_EXTEND!");
assert(VT.isVector() == Operand.getValueType().isVector() &&
"ANY_EXTEND result type type should be vector iff the operand "
"type is vector!");
if (Operand.getValueType() == VT) return Operand; // noop extension
assert((!VT.isVector() ||
VT.getVectorElementCount() ==
Operand.getValueType().getVectorElementCount()) &&
"Vector element count mismatch!");
assert(Operand.getValueType().bitsLT(VT) &&
"Invalid anyext node, dst < src!");
if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
OpOpcode == ISD::ANY_EXTEND)
// (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
else if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
// (ext (trunc x)) -> x
if (OpOpcode == ISD::TRUNCATE) {
SDValue OpOp = Operand.getOperand(0);
if (OpOp.getValueType() == VT) {
transferDbgValues(Operand, OpOp);
return OpOp;
}
}
break;
case ISD::TRUNCATE:
assert(VT.isInteger() && Operand.getValueType().isInteger() &&
"Invalid TRUNCATE!");
assert(VT.isVector() == Operand.getValueType().isVector() &&
"TRUNCATE result type type should be vector iff the operand "
"type is vector!");
if (Operand.getValueType() == VT) return Operand; // noop truncate
assert((!VT.isVector() ||
VT.getVectorElementCount() ==
Operand.getValueType().getVectorElementCount()) &&
"Vector element count mismatch!");
assert(Operand.getValueType().bitsGT(VT) &&
"Invalid truncate node, src < dst!");
if (OpOpcode == ISD::TRUNCATE)
return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
OpOpcode == ISD::ANY_EXTEND) {
// If the source is smaller than the dest, we still need an extend.
if (Operand.getOperand(0).getValueType().getScalarType()
.bitsLT(VT.getScalarType()))
return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
if (Operand.getOperand(0).getValueType().bitsGT(VT))
return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
return Operand.getOperand(0);
}
if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
break;
case ISD::ANY_EXTEND_VECTOR_INREG:
case ISD::ZERO_EXTEND_VECTOR_INREG:
case ISD::SIGN_EXTEND_VECTOR_INREG:
assert(VT.isVector() && "This DAG node is restricted to vector types.");
assert(Operand.getValueType().bitsLE(VT) &&
"The input must be the same size or smaller than the result.");
assert(VT.getVectorNumElements() <
Operand.getValueType().getVectorNumElements() &&
"The destination vector type must have fewer lanes than the input.");
break;
case ISD::ABS:
assert(VT.isInteger() && VT == Operand.getValueType() &&
"Invalid ABS!");
if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
break;
case ISD::BSWAP:
assert(VT.isInteger() && VT == Operand.getValueType() &&
"Invalid BSWAP!");
assert((VT.getScalarSizeInBits() % 16 == 0) &&
"BSWAP types must be a multiple of 16 bits!");
if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
break;
case ISD::BITREVERSE:
assert(VT.isInteger() && VT == Operand.getValueType() &&
"Invalid BITREVERSE!");
if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
break;
case ISD::BITCAST:
// Basic sanity checking.
assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
"Cannot BITCAST between types of different sizes!");
if (VT == Operand.getValueType()) return Operand; // noop conversion.
if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
break;
case ISD::SCALAR_TO_VECTOR:
assert(VT.isVector() && !Operand.getValueType().isVector() &&
(VT.getVectorElementType() == Operand.getValueType() ||
(VT.getVectorElementType().isInteger() &&
Operand.getValueType().isInteger() &&
VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
"Illegal SCALAR_TO_VECTOR node!");
if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
// scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
isa<ConstantSDNode>(Operand.getOperand(1)) &&
Operand.getConstantOperandVal(1) == 0 &&
Operand.getOperand(0).getValueType() == VT)
return Operand.getOperand(0);
break;
case ISD::FNEG:
// Negation of an unknown bag of bits is still completely undefined.
if (OpOpcode == ISD::UNDEF)
return getUNDEF(VT);
if (OpOpcode == ISD::FNEG) // --X -> X
return Operand.getOperand(0);
break;
case ISD::FABS:
if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
break;
case ISD::VSCALE:
assert(VT == Operand.getValueType() && "Unexpected VT!");
break;
}
SDNode *N;
SDVTList VTs = getVTList(VT);
SDValue Ops[] = {Operand};
if (VT != MVT::Glue) { // Don't CSE flag producing nodes
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTs, Ops);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
E->intersectFlagsWith(Flags);
return SDValue(E, 0);
}
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
N->setFlags(Flags);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
} else {
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
createOperands(N, Ops);
}
InsertNode(N);
SDValue V = SDValue(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
const APInt &C2) {
switch (Opcode) {
case ISD::ADD: return C1 + C2;
case ISD::SUB: return C1 - C2;
case ISD::MUL: return C1 * C2;
case ISD::AND: return C1 & C2;
case ISD::OR: return C1 | C2;
case ISD::XOR: return C1 ^ C2;
case ISD::SHL: return C1 << C2;
case ISD::SRL: return C1.lshr(C2);
case ISD::SRA: return C1.ashr(C2);
case ISD::ROTL: return C1.rotl(C2);
case ISD::ROTR: return C1.rotr(C2);
case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
case ISD::SADDSAT: return C1.sadd_sat(C2);
case ISD::UADDSAT: return C1.uadd_sat(C2);
case ISD::SSUBSAT: return C1.ssub_sat(C2);
case ISD::USUBSAT: return C1.usub_sat(C2);
case ISD::UDIV:
if (!C2.getBoolValue())
break;
return C1.udiv(C2);
case ISD::UREM:
if (!C2.getBoolValue())
break;
return C1.urem(C2);
case ISD::SDIV:
if (!C2.getBoolValue())
break;
return C1.sdiv(C2);
case ISD::SREM:
if (!C2.getBoolValue())
break;
return C1.srem(C2);
}
return llvm::None;
}
SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
const GlobalAddressSDNode *GA,
const SDNode *N2) {
if (GA->getOpcode() != ISD::GlobalAddress)
return SDValue();
if (!TLI->isOffsetFoldingLegal(GA))
return SDValue();
auto *C2 = dyn_cast<ConstantSDNode>(N2);
if (!C2)
return SDValue();
int64_t Offset = C2->getSExtValue();
switch (Opcode) {
case ISD::ADD: break;
case ISD::SUB: Offset = -uint64_t(Offset); break;
default: return SDValue();
}
return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
GA->getOffset() + uint64_t(Offset));
}
bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
switch (Opcode) {
case ISD::SDIV:
case ISD::UDIV:
case ISD::SREM:
case ISD::UREM: {
// If a divisor is zero/undef or any element of a divisor vector is
// zero/undef, the whole op is undef.
assert(Ops.size() == 2 && "Div/rem should have 2 operands");
SDValue Divisor = Ops[1];
if (Divisor.isUndef() || isNullConstant(Divisor))
return true;
return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
llvm::any_of(Divisor->op_values(),
[](SDValue V) { return V.isUndef() ||
isNullConstant(V); });
// TODO: Handle signed overflow.
}
// TODO: Handle oversized shifts.
default:
return false;
}
}
SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
EVT VT, ArrayRef<SDValue> Ops) {
// If the opcode is a target-specific ISD node, there's nothing we can
// do here and the operand rules may not line up with the below, so
// bail early.
if (Opcode >= ISD::BUILTIN_OP_END)
return SDValue();
// For now, the array Ops should only contain two values.
// This enforcement will be removed once this function is merged with
// FoldConstantVectorArithmetic
if (Ops.size() != 2)
return SDValue();
if (isUndef(Opcode, Ops))
return getUNDEF(VT);
SDNode *N1 = Ops[0].getNode();
SDNode *N2 = Ops[1].getNode();
// Handle the case of two scalars.
if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
if (C1->isOpaque() || C2->isOpaque())
return SDValue();
Optional<APInt> FoldAttempt =
FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
if (!FoldAttempt)
return SDValue();
SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
assert((!Folded || !VT.isVector()) &&
"Can't fold vectors ops with scalar operands");
return Folded;
}
}
// fold (add Sym, c) -> Sym+c
if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
return FoldSymbolOffset(Opcode, VT, GA, N2);
if (TLI->isCommutativeBinOp(Opcode))
if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
return FoldSymbolOffset(Opcode, VT, GA, N1);
// TODO: All the folds below are performed lane-by-lane and assume a fixed
// vector width, however we should be able to do constant folds involving
// splat vector nodes too.
if (VT.isScalableVector())
return SDValue();
// For fixed width vectors, extract each constant element and fold them
// individually. Either input may be an undef value.
auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
if (!BV1 && !N1->isUndef())
return SDValue();
auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
if (!BV2 && !N2->isUndef())
return SDValue();
// If both operands are undef, that's handled the same way as scalars.
if (!BV1 && !BV2)
return SDValue();
assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
"Vector binop with different number of elements in operands?");
EVT SVT = VT.getScalarType();
EVT LegalSVT = SVT;
if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
if (LegalSVT.bitsLT(SVT))
return SDValue();
}
SmallVector<SDValue, 4> Outputs;
unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
for (unsigned I = 0; I != NumOps; ++I) {
SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
if (SVT.isInteger()) {
if (V1->getValueType(0).bitsGT(SVT))
V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
if (V2->getValueType(0).bitsGT(SVT))
V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
}
if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
return SDValue();
// Fold one vector element.
SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
if (LegalSVT != SVT)
ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
// Scalar folding only succeeded if the result is a constant or UNDEF.
if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
ScalarResult.getOpcode() != ISD::ConstantFP)
return SDValue();
Outputs.push_back(ScalarResult);
}
assert(VT.getVectorNumElements() == Outputs.size() &&
"Vector size mismatch!");
// We may have a vector type but a scalar result. Create a splat.
Outputs.resize(VT.getVectorNumElements(), Outputs.back());
// Build a big vector out of the scalar elements we generated.
return getBuildVector(VT, SDLoc(), Outputs);
}
// TODO: Merge with FoldConstantArithmetic
SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
const SDLoc &DL, EVT VT,
ArrayRef<SDValue> Ops,
const SDNodeFlags Flags) {
// If the opcode is a target-specific ISD node, there's nothing we can
// do here and the operand rules may not line up with the below, so
// bail early.
if (Opcode >= ISD::BUILTIN_OP_END)
return SDValue();
if (isUndef(Opcode, Ops))
return getUNDEF(VT);
// We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
if (!VT.isVector())
return SDValue();
// TODO: All the folds below are performed lane-by-lane and assume a fixed
// vector width, however we should be able to do constant folds involving
// splat vector nodes too.
if (VT.isScalableVector())
return SDValue();
// From this point onwards all vectors are assumed to be fixed width.
unsigned NumElts = VT.getVectorNumElements();
auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
return !Op.getValueType().isVector() ||
Op.getValueType().getVectorNumElements() == NumElts;
};
auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
(BV && BV->isConstant());
};
// All operands must be vector types with the same number of elements as
// the result type and must be either UNDEF or a build vector of constant
// or UNDEF scalars.
if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
!llvm::all_of(Ops, IsScalarOrSameVectorSize))
return SDValue();
// If we are comparing vectors, then the result needs to be a i1 boolean
// that is then sign-extended back to the legal result type.
EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
// Find legal integer scalar type for constant promotion and
// ensure that its scalar size is at least as large as source.
EVT LegalSVT = VT.getScalarType();
if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
if (LegalSVT.bitsLT(VT.getScalarType()))
return SDValue();
}
// Constant fold each scalar lane separately.
SmallVector<SDValue, 4> ScalarResults;
for (unsigned i = 0; i != NumElts; i++) {
SmallVector<SDValue, 4> ScalarOps;
for (SDValue Op : Ops) {
EVT InSVT = Op.getValueType().getScalarType();
BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
if (!InBV) {
// We've checked that this is UNDEF or a constant of some kind.
if (Op.isUndef())
ScalarOps.push_back(getUNDEF(InSVT));
else
ScalarOps.push_back(Op);
continue;
}
SDValue ScalarOp = InBV->getOperand(i);
EVT ScalarVT = ScalarOp.getValueType();
// Build vector (integer) scalar operands may need implicit
// truncation - do this before constant folding.
if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
ScalarOps.push_back(ScalarOp);
}
// Constant fold the scalar operands.
SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
// Legalize the (integer) scalar constant if necessary.
if (LegalSVT != SVT)
ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
// Scalar folding only succeeded if the result is a constant or UNDEF.
if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
ScalarResult.getOpcode() != ISD::ConstantFP)
return SDValue();
ScalarResults.push_back(ScalarResult);
}
SDValue V = getBuildVector(VT, DL, ScalarResults);
NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
return V;
}
SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
EVT VT, SDValue N1, SDValue N2) {
// TODO: We don't do any constant folding for strict FP opcodes here, but we
// should. That will require dealing with a potentially non-default
// rounding mode, checking the "opStatus" return value from the APFloat
// math calculations, and possibly other variations.
auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
if (N1CFP && N2CFP) {
APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
switch (Opcode) {
case ISD::FADD:
C1.add(C2, APFloat::rmNearestTiesToEven);
return getConstantFP(C1, DL, VT);
case ISD::FSUB:
C1.subtract(C2, APFloat::rmNearestTiesToEven);
return getConstantFP(C1, DL, VT);
case ISD::FMUL:
C1.multiply(C2, APFloat::rmNearestTiesToEven);
return getConstantFP(C1, DL, VT);
case ISD::FDIV:
C1.divide(C2, APFloat::rmNearestTiesToEven);
return getConstantFP(C1, DL, VT);
case ISD::FREM:
C1.mod(C2);
return getConstantFP(C1, DL, VT);
case ISD::FCOPYSIGN:
C1.copySign(C2);
return getConstantFP(C1, DL, VT);
default: break;
}
}
if (N1CFP && Opcode == ISD::FP_ROUND) {
APFloat C1 = N1CFP->getValueAPF(); // make copy
bool Unused;
// This can return overflow, underflow, or inexact; we don't care.
// FIXME need to be more flexible about rounding mode.
(void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
&Unused);
return getConstantFP(C1, DL, VT);
}
switch (Opcode) {
case ISD::FSUB:
// -0.0 - undef --> undef (consistent with "fneg undef")
if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
return getUNDEF(VT);
LLVM_FALLTHROUGH;
case ISD::FADD:
case ISD::FMUL:
case ISD::FDIV:
case ISD::FREM:
// If both operands are undef, the result is undef. If 1 operand is undef,
// the result is NaN. This should match the behavior of the IR optimizer.
if (N1.isUndef() && N2.isUndef())
return getUNDEF(VT);
if (N1.isUndef() || N2.isUndef())
return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
}
return SDValue();
}
SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
// There's no need to assert on a byte-aligned pointer. All pointers are at
// least byte aligned.
if (A == Align(1))
return Val;
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
ID.AddInteger(A.value());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
return SDValue(E, 0);
auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
Val.getValueType(), A);
createOperands(N, {Val});
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
SDValue N1, SDValue N2, const SDNodeFlags Flags) {
ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
// Canonicalize constant to RHS if commutative.
if (TLI->isCommutativeBinOp(Opcode)) {
if (N1C && !N2C) {
std::swap(N1C, N2C);
std::swap(N1, N2);
} else if (N1CFP && !N2CFP) {
std::swap(N1CFP, N2CFP);
std::swap(N1, N2);
}
}
switch (Opcode) {
default: break;
case ISD::TokenFactor:
assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
N2.getValueType() == MVT::Other && "Invalid token factor!");
// Fold trivial token factors.
if (N1.getOpcode() == ISD::EntryToken) return N2;
if (N2.getOpcode() == ISD::EntryToken) return N1;
if (N1 == N2) return N1;
break;
case ISD::BUILD_VECTOR: {
// Attempt to simplify BUILD_VECTOR.
SDValue Ops[] = {N1, N2};
if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
return V;
break;
}
case ISD::CONCAT_VECTORS: {
SDValue Ops[] = {N1, N2};
if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
return V;
break;
}
case ISD::AND:
assert(VT.isInteger() && "This operator does not apply to FP types!");
assert(N1.getValueType() == N2.getValueType() &&
N1.getValueType() == VT && "Binary operator types must match!");
// (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
// worth handling here.
if (N2C && N2C->isNullValue())
return N2;
if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
return N1;
break;
case ISD::OR:
case ISD::XOR:
case ISD::ADD:
case ISD::SUB:
assert(VT.isInteger() && "This operator does not apply to FP types!");
assert(N1.getValueType() == N2.getValueType() &&
N1.getValueType() == VT && "Binary operator types must match!");
// (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
// it's worth handling here.
if (N2C && N2C->isNullValue())
return N1;
break;
case ISD::MUL:
assert(VT.isInteger() && "This operator does not apply to FP types!");
assert(N1.getValueType() == N2.getValueType() &&
N1.getValueType() == VT && "Binary operator types must match!");
if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue();
APInt N2CImm = N2C->getAPIntValue();
return getVScale(DL, VT, MulImm * N2CImm);
}
break;
case ISD::UDIV:
case ISD::UREM:
case ISD::MULHU:
case ISD::MULHS:
case ISD::SDIV:
case ISD::SREM:
case ISD::SMIN:
case ISD::SMAX:
case ISD::UMIN:
case ISD::UMAX:
case ISD::SADDSAT:
case ISD::SSUBSAT:
case ISD::UADDSAT:
case ISD::USUBSAT:
assert(VT.isInteger() && "This operator does not apply to FP types!");
assert(N1.getValueType() == N2.getValueType() &&
N1.getValueType() == VT && "Binary operator types must match!");
break;
case ISD::FADD:
case ISD::FSUB:
case ISD::FMUL:
case ISD::FDIV:
case ISD::FREM:
assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
assert(N1.getValueType() == N2.getValueType() &&
N1.getValueType() == VT && "Binary operator types must match!");
if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
return V;
break;
case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
assert(N1.getValueType() == VT &&
N1.getValueType().isFloatingPoint() &&
N2.getValueType().isFloatingPoint() &&
"Invalid FCOPYSIGN!");
break;
case ISD::SHL:
if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue();
APInt ShiftImm = N2C->getAPIntValue();
return getVScale(DL, VT, MulImm << ShiftImm);
}
LLVM_FALLTHROUGH;
case ISD::SRA:
case ISD::SRL:
if (SDValue V = simplifyShift(N1, N2))
return V;
LLVM_FALLTHROUGH;
case ISD::ROTL:
case ISD::ROTR:
assert(VT == N1.getValueType() &&
"Shift operators return type must be the same as their first arg");
assert(VT.isInteger() && N2.getValueType().isInteger() &&
"Shifts only work on integers");
assert((!VT.isVector() || VT == N2.getValueType()) &&
"Vector shift amounts must be in the same as their first arg");
// Verify that the shift amount VT is big enough to hold valid shift
// amounts. This catches things like trying to shift an i1024 value by an
// i8, which is easy to fall into in generic code that uses
// TLI.getShiftAmount().
assert(N2.getValueType().getScalarSizeInBits().getFixedSize() >=
Log2_32_Ceil(VT.getScalarSizeInBits().getFixedSize()) &&
"Invalid use of small shift amount with oversized value!");
// Always fold shifts of i1 values so the code generator doesn't need to
// handle them. Since we know the size of the shift has to be less than the
// size of the value, the shift/rotate count is guaranteed to be zero.
if (VT == MVT::i1)
return N1;
if (N2C && N2C->isNullValue())
return N1;
break;
case ISD::FP_ROUND:
assert(VT.isFloatingPoint() &&
N1.getValueType().isFloatingPoint() &&
VT.bitsLE(N1.getValueType()) &&
N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
"Invalid FP_ROUND!");
if (N1.getValueType() == VT) return N1; // noop conversion.
break;
case ISD::AssertSext:
case ISD::AssertZext: {
EVT EVT = cast<VTSDNode>(N2)->getVT();
assert(VT == N1.getValueType() && "Not an inreg extend!");
assert(VT.isInteger() && EVT.isInteger() &&
"Cannot *_EXTEND_INREG FP types");
assert(!EVT.isVector() &&
"AssertSExt/AssertZExt type should be the vector element type "
"rather than the vector type!");
assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
if (VT.getScalarType() == EVT) return N1; // noop assertion.
break;
}
case ISD::SIGN_EXTEND_INREG: {
EVT EVT = cast<VTSDNode>(N2)->getVT();
assert(VT == N1.getValueType() && "Not an inreg extend!");
assert(VT.isInteger() && EVT.isInteger() &&
"Cannot *_EXTEND_INREG FP types");
assert(EVT.isVector() == VT.isVector() &&
"SIGN_EXTEND_INREG type should be vector iff the operand "
"type is vector!");
assert((!EVT.isVector() ||
EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
"Vector element counts must match in SIGN_EXTEND_INREG");
assert(EVT.bitsLE(VT) && "Not extending!");
if (EVT == VT) return N1; // Not actually extending
auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
unsigned FromBits = EVT.getScalarSizeInBits();
Val <<= Val.getBitWidth() - FromBits;
Val.ashrInPlace(Val.getBitWidth() - FromBits);
return getConstant(Val, DL, ConstantVT);
};
if (N1C) {
const APInt &Val = N1C->getAPIntValue();
return SignExtendInReg(Val, VT);
}
if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
SmallVector<SDValue, 8> Ops;
llvm::EVT OpVT = N1.getOperand(0).getValueType();
for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
SDValue Op = N1.getOperand(i);
if (Op.isUndef()) {
Ops.push_back(getUNDEF(OpVT));
continue;
}
ConstantSDNode *C = cast<ConstantSDNode>(Op);
APInt Val = C->getAPIntValue();
Ops.push_back(SignExtendInReg(Val, OpVT));
}
return getBuildVector(VT, DL, Ops);
}
break;
}
case ISD::EXTRACT_VECTOR_ELT:
assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
"The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
element type of the vector.");
// Extract from an undefined value or using an undefined index is undefined.
if (N1.isUndef() || N2.isUndef())
return getUNDEF(VT);
// EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
// vectors. For scalable vectors we will provide appropriate support for
// dealing with arbitrary indices.
if (N2C && N1.getValueType().isFixedLengthVector() &&
N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
return getUNDEF(VT);
// EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
// expanding copies of large vectors from registers. This only works for
// fixed length vectors, since we need to know the exact number of
// elements.
if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
unsigned Factor =
N1.getOperand(0).getValueType().getVectorNumElements();
return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
N1.getOperand(N2C->getZExtValue() / Factor),
getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
}
// EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
// lowering is expanding large vector constants.
if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
N1.getOpcode() == ISD::SPLAT_VECTOR)) {
assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
N1.getValueType().isFixedLengthVector()) &&
"BUILD_VECTOR used for scalable vectors");
unsigned Index =
N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
SDValue Elt = N1.getOperand(Index);
if (VT != Elt.getValueType())
// If the vector element type is not legal, the BUILD_VECTOR operands
// are promoted and implicitly truncated, and the result implicitly
// extended. Make that explicit here.
Elt = getAnyExtOrTrunc(Elt, DL, VT);
return Elt;
}
// EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
// operations are lowered to scalars.
if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
// If the indices are the same, return the inserted element else
// if the indices are known different, extract the element from
// the original vector.
SDValue N1Op2 = N1.getOperand(2);
ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
if (N1Op2C && N2C) {
if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
if (VT == N1.getOperand(1).getValueType())
return N1.getOperand(1);
else
return getSExtOrTrunc(N1.getOperand(1), DL, VT);
}
return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
}
}
// EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
// when vector types are scalarized and v1iX is legal.
// vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
// Here we are completely ignoring the extract element index (N2),
// which is fine for fixed width vectors, since any index other than 0
// is undefined anyway. However, this cannot be ignored for scalable
// vectors - in theory we could support this, but we don't want to do this
// without a profitability check.
if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
N1.getValueType().isFixedLengthVector() &&
N1.getValueType().getVectorNumElements() == 1) {
return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
N1.getOperand(1));
}
break;
case ISD::EXTRACT_ELEMENT:
assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
assert(!N1.getValueType().isVector() && !VT.isVector() &&
(N1.getValueType().isInteger() == VT.isInteger()) &&
N1.getValueType() != VT &&
"Wrong types for EXTRACT_ELEMENT!");
// EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
// 64-bit integers into 32-bit parts. Instead of building the extract of
// the BUILD_PAIR, only to have legalize rip it apart, just do it now.
if (N1.getOpcode() == ISD::BUILD_PAIR)
return N1.getOperand(N2C->getZExtValue());
// EXTRACT_ELEMENT of a constant int is also very common.
if (N1C) {
unsigned ElementSize = VT.getSizeInBits();
unsigned Shift = ElementSize * N2C->getZExtValue();
APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
}
break;
case ISD::EXTRACT_SUBVECTOR:
EVT N1VT = N1.getValueType();
assert(VT.isVector() && N1VT.isVector() &&
"Extract subvector VTs must be vectors!");
assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
"Extract subvector VTs must have the same element type!");
assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
"Cannot extract a scalable vector from a fixed length vector!");
assert((VT.isScalableVector() != N1VT.isScalableVector() ||
VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
"Extract subvector must be from larger vector to smaller vector!");
assert(N2C && "Extract subvector index must be a constant");
assert((VT.isScalableVector() != N1VT.isScalableVector() ||
(VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
N1VT.getVectorMinNumElements()) &&
"Extract subvector overflow!");
assert(N2C->getAPIntValue().getBitWidth() ==
TLI->getVectorIdxTy(getDataLayout())
.getSizeInBits()
.getFixedSize() &&
"Constant index for EXTRACT_SUBVECTOR has an invalid size");
// Trivial extraction.
if (VT == N1VT)
return N1;
// EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
if (N1.isUndef())
return getUNDEF(VT);
// EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
// the concat have the same type as the extract.
if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
N1.getNumOperands() > 0 && VT == N1.getOperand(0).getValueType()) {
unsigned Factor = VT.getVectorMinNumElements();
return N1.getOperand(N2C->getZExtValue() / Factor);
}
// EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
// during shuffle legalization.
if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
VT == N1.getOperand(1).getValueType())
return N1.getOperand(1);
break;
}
// Perform trivial constant folding.
if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
return SV;
if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
return V;
// Canonicalize an UNDEF to the RHS, even over a constant.
if (N1.isUndef()) {
if (TLI->isCommutativeBinOp(Opcode)) {
std::swap(N1, N2);
} else {
switch (Opcode) {
case ISD::SIGN_EXTEND_INREG:
case ISD::SUB:
return getUNDEF(VT); // fold op(undef, arg2) -> undef
case ISD::UDIV:
case ISD::SDIV:
case ISD::UREM:
case ISD::SREM:
case ISD::SSUBSAT:
case ISD::USUBSAT:
return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
}
}
}
// Fold a bunch of operators when the RHS is undef.
if (N2.isUndef()) {
switch (Opcode) {
case ISD::XOR:
if (N1.isUndef())
// Handle undef ^ undef -> 0 special case. This is a common
// idiom (misuse).
return getConstant(0, DL, VT);
LLVM_FALLTHROUGH;
case ISD::ADD:
case ISD::SUB:
case ISD::UDIV:
case ISD::SDIV:
case ISD::UREM:
case ISD::SREM:
return getUNDEF(VT); // fold op(arg1, undef) -> undef
case ISD::MUL:
case ISD::AND:
case ISD::SSUBSAT:
case ISD::USUBSAT:
return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
case ISD::OR:
case ISD::SADDSAT:
case ISD::UADDSAT:
return getAllOnesConstant(DL, VT);
}
}
// Memoize this node if possible.
SDNode *N;
SDVTList VTs = getVTList(VT);
SDValue Ops[] = {N1, N2};
if (VT != MVT::Glue) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTs, Ops);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
E->intersectFlagsWith(Flags);
return SDValue(E, 0);
}
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
N->setFlags(Flags);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
} else {
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
createOperands(N, Ops);
}
InsertNode(N);
SDValue V = SDValue(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
SDValue N1, SDValue N2, SDValue N3,
const SDNodeFlags Flags) {
// Perform various simplifications.
switch (Opcode) {
case ISD::FMA: {
assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
assert(N1.getValueType() == VT && N2.getValueType() == VT &&
N3.getValueType() == VT && "FMA types must match!");
ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
if (N1CFP && N2CFP && N3CFP) {
APFloat V1 = N1CFP->getValueAPF();
const APFloat &V2 = N2CFP->getValueAPF();
const APFloat &V3 = N3CFP->getValueAPF();
V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
return getConstantFP(V1, DL, VT);
}
break;
}
case ISD::BUILD_VECTOR: {
// Attempt to simplify BUILD_VECTOR.
SDValue Ops[] = {N1, N2, N3};
if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
return V;
break;
}
case ISD::CONCAT_VECTORS: {
SDValue Ops[] = {N1, N2, N3};
if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
return V;
break;
}
case ISD::SETCC: {
assert(VT.isInteger() && "SETCC result type must be an integer!");
assert(N1.getValueType() == N2.getValueType() &&
"SETCC operands must have the same type!");
assert(VT.isVector() == N1.getValueType().isVector() &&
"SETCC type should be vector iff the operand type is vector!");
assert((!VT.isVector() || VT.getVectorElementCount() ==
N1.getValueType().getVectorElementCount()) &&
"SETCC vector element counts must match!");
// Use FoldSetCC to simplify SETCC's.
if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
return V;
// Vector constant folding.
SDValue Ops[] = {N1, N2, N3};
if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
return V;
}
break;
}
case ISD::SELECT:
case ISD::VSELECT:
if (SDValue V = simplifySelect(N1, N2, N3))
return V;
break;
case ISD::VECTOR_SHUFFLE:
llvm_unreachable("should use getVectorShuffle constructor!");
case ISD::INSERT_VECTOR_ELT: {
ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
// INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
// for scalable vectors where we will generate appropriate code to
// deal with out-of-bounds cases correctly.
if (N3C && N1.getValueType().isFixedLengthVector() &&
N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
return getUNDEF(VT);
// Undefined index can be assumed out-of-bounds, so that's UNDEF too.
if (N3.isUndef())
return getUNDEF(VT);
// If the inserted element is an UNDEF, just use the input vector.
if (N2.isUndef())
return N1;
break;
}
case ISD::INSERT_SUBVECTOR: {
// Inserting undef into undef is still undef.
if (N1.isUndef() && N2.isUndef())
return getUNDEF(VT);
EVT N2VT = N2.getValueType();
assert(VT == N1.getValueType() &&
"Dest and insert subvector source types must match!");
assert(VT.isVector() && N2VT.isVector() &&
"Insert subvector VTs must be vectors!");
assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
"Cannot insert a scalable vector into a fixed length vector!");
assert((VT.isScalableVector() != N2VT.isScalableVector() ||
VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
"Insert subvector must be from smaller vector to larger vector!");
assert(isa<ConstantSDNode>(N3) &&
"Insert subvector index must be constant");
assert((VT.isScalableVector() != N2VT.isScalableVector() ||
(N2VT.getVectorMinNumElements() +
cast<ConstantSDNode>(N3)->getZExtValue()) <=
VT.getVectorMinNumElements()) &&
"Insert subvector overflow!");
// Trivial insertion.
if (VT == N2VT)
return N2;
// If this is an insert of an extracted vector into an undef vector, we
// can just use the input to the extract.
if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
return N2.getOperand(0);
break;
}
case ISD::BITCAST:
// Fold bit_convert nodes from a type to themselves.
if (N1.getValueType() == VT)
return N1;
break;
}
// Memoize node if it doesn't produce a flag.
SDNode *N;
SDVTList VTs = getVTList(VT);
SDValue Ops[] = {N1, N2, N3};
if (VT != MVT::Glue) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTs, Ops);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
E->intersectFlagsWith(Flags);
return SDValue(E, 0);
}
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
N->setFlags(Flags);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
} else {
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
createOperands(N, Ops);
}
InsertNode(N);
SDValue V = SDValue(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
SDValue Ops[] = { N1, N2, N3, N4 };
return getNode(Opcode, DL, VT, Ops);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
SDValue N1, SDValue N2, SDValue N3, SDValue N4,
SDValue N5) {
SDValue Ops[] = { N1, N2, N3, N4, N5 };
return getNode(Opcode, DL, VT, Ops);
}
/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
/// the incoming stack arguments to be loaded from the stack.
SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
SmallVector<SDValue, 8> ArgChains;
// Include the original chain at the beginning of the list. When this is
// used by target LowerCall hooks, this helps legalize find the
// CALLSEQ_BEGIN node.
ArgChains.push_back(Chain);
// Add a chain value for each stack argument.
for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
if (FI->getIndex() < 0)
ArgChains.push_back(SDValue(L, 1));
// Build a tokenfactor for all the chains.
return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
}
/// getMemsetValue - Vectorized representation of the memset value
/// operand.
static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
const SDLoc &dl) {
assert(!Value.isUndef());
unsigned NumBits = VT.getScalarSizeInBits();
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
assert(C->getAPIntValue().getBitWidth() == 8);
APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
if (VT.isInteger()) {
bool IsOpaque = VT.getSizeInBits() > 64 ||
!DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
return DAG.getConstant(Val, dl, VT, false, IsOpaque);
}
return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
VT);
}
assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
EVT IntVT = VT.getScalarType();
if (!IntVT.isInteger())
IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
if (NumBits > 8) {
// Use a multiplication with 0x010101... to extend the input to the
// required length.
APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
DAG.getConstant(Magic, dl, IntVT));
}
if (VT != Value.getValueType() && !VT.isInteger())
Value = DAG.getBitcast(VT.getScalarType(), Value);
if (VT != Value.getValueType())
Value = DAG.getSplatBuildVector(VT, dl, Value);
return Value;
}
/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
/// used when a memcpy is turned into a memset when the source is a constant
/// string ptr.
static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
const TargetLowering &TLI,
const ConstantDataArraySlice &Slice) {
// Handle vector with all elements zero.
if (Slice.Array == nullptr) {
if (VT.isInteger())
return DAG.getConstant(0, dl, VT);
else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
return DAG.getConstantFP(0.0, dl, VT);
else if (VT.isVector()) {
unsigned NumElts = VT.getVectorNumElements();
MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
return DAG.getNode(ISD::BITCAST, dl, VT,
DAG.getConstant(0, dl,
EVT::getVectorVT(*DAG.getContext(),
EltVT, NumElts)));
} else
llvm_unreachable("Expected type!");
}
assert(!VT.isVector() && "Can't handle vector type here!");
unsigned NumVTBits = VT.getSizeInBits();
unsigned NumVTBytes = NumVTBits / 8;
unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
APInt Val(NumVTBits, 0);
if (DAG.getDataLayout().isLittleEndian()) {
for (unsigned i = 0; i != NumBytes; ++i)
Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
} else {
for (unsigned i = 0; i != NumBytes; ++i)
Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
}
// If the "cost" of materializing the integer immediate is less than the cost
// of a load, then it is cost effective to turn the load into the immediate.
Type *Ty = VT.getTypeForEVT(*DAG.getContext());
if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
return DAG.getConstant(Val, dl, VT);
return SDValue(nullptr, 0);
}
SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
const SDLoc &DL,
const SDNodeFlags Flags) {
EVT VT = Base.getValueType();
SDValue Index;
if (Offset.isScalable())
Index = getVScale(DL, Base.getValueType(),
APInt(Base.getValueSizeInBits().getFixedSize(),
Offset.getKnownMinSize()));
else
Index = getConstant(Offset.getFixedSize(), DL, VT);
return getMemBasePlusOffset(Base, Index, DL, Flags);
}
SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
const SDLoc &DL,
const SDNodeFlags Flags) {
assert(Offset.getValueType().isInteger());
EVT BasePtrVT = Ptr.getValueType();
return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
}
/// Returns true if memcpy source is constant data.
static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
uint64_t SrcDelta = 0;
GlobalAddressSDNode *G = nullptr;
if (Src.getOpcode() == ISD::GlobalAddress)
G = cast<GlobalAddressSDNode>(Src);
else if (Src.getOpcode() == ISD::ADD &&
Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
Src.getOperand(1).getOpcode() == ISD::Constant) {
G = cast<GlobalAddressSDNode>(Src.getOperand(0));
SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
}
if (!G)
return false;
return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
SrcDelta + G->getOffset());
}
static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
SelectionDAG &DAG) {
// On Darwin, -Os means optimize for size without hurting performance, so
// only really optimize for size when -Oz (MinSize) is used.
if (MF.getTarget().getTargetTriple().isOSDarwin())
return MF.getFunction().hasMinSize();
return DAG.shouldOptForSize();
}
static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
SmallVector<SDValue, 32> &OutChains, unsigned From,
unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
SmallVector<SDValue, 16> &OutStoreChains) {
assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
SmallVector<SDValue, 16> GluedLoadChains;
for (unsigned i = From; i < To; ++i) {
OutChains.push_back(OutLoadChains[i]);
GluedLoadChains.push_back(OutLoadChains[i]);
}
// Chain for all loads.
SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
GluedLoadChains);
for (unsigned i = From; i < To; ++i) {
StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
ST->getBasePtr(), ST->getMemoryVT(),
ST->getMemOperand());
OutChains.push_back(NewStore);
}
}
static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
SDValue Chain, SDValue Dst, SDValue Src,
uint64_t Size, Align Alignment,
bool isVol, bool AlwaysInline,
MachinePointerInfo DstPtrInfo,
MachinePointerInfo SrcPtrInfo) {
// Turn a memcpy of undef to nop.
// FIXME: We need to honor volatile even is Src is undef.
if (Src.isUndef())
return Chain;
// Expand memcpy to a series of load and store ops if the size operand falls
// below a certain threshold.
// TODO: In the AlwaysInline case, if the size is big then generate a loop
// rather than maybe a humongous number of loads and stores.
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const DataLayout &DL = DAG.getDataLayout();
LLVMContext &C = *DAG.getContext();
std::vector<EVT> MemOps;
bool DstAlignCanChange = false;
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo &MFI = MF.getFrameInfo();
bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
DstAlignCanChange = true;
MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
if (!SrcAlign || Alignment > *SrcAlign)
SrcAlign = Alignment;
assert(SrcAlign && "SrcAlign must be set");
ConstantDataArraySlice Slice;
bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
const MemOp Op = isZeroConstant
? MemOp::Set(Size, DstAlignCanChange, Alignment,
/*IsZeroMemset*/ true, isVol)
: MemOp::Copy(Size, DstAlignCanChange, Alignment,
*SrcAlign, isVol, CopyFromConstant);
if (!TLI.findOptimalMemOpLowering(
MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
return SDValue();
if (DstAlignCanChange) {
Type *Ty = MemOps[0].getTypeForEVT(C);
Align NewAlign = DL.getABITypeAlign(Ty);
// Don't promote to an alignment that would require dynamic stack
// realignment.
const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
if (!TRI->needsStackRealignment(MF))
while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
NewAlign = NewAlign / 2;
if (NewAlign > Alignment) {
// Give the stack frame object a larger alignment if needed.
if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
MFI.setObjectAlignment(FI->getIndex(), NewAlign);
Alignment = NewAlign;
}
}
MachineMemOperand::Flags MMOFlags =
isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
SmallVector<SDValue, 16> OutLoadChains;
SmallVector<SDValue, 16> OutStoreChains;
SmallVector<SDValue, 32> OutChains;
unsigned NumMemOps = MemOps.size();
uint64_t SrcOff = 0, DstOff = 0;
for (unsigned i = 0; i != NumMemOps; ++i) {
EVT VT = MemOps[i];
unsigned VTSize = VT.getSizeInBits() / 8;
SDValue Value, Store;
if (VTSize > Size) {
// Issuing an unaligned load / store pair that overlaps with the previous
// pair. Adjust the offset accordingly.
assert(i == NumMemOps-1 && i != 0);
SrcOff -= VTSize - Size;
DstOff -= VTSize - Size;
}
if (CopyFromConstant &&
(isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
// It's unlikely a store of a vector immediate can be done in a single
// instruction. It would require a load from a constantpool first.
// We only handle zero vectors here.
// FIXME: Handle other cases where store of vector immediate is done in
// a single instruction.
ConstantDataArraySlice SubSlice;
if (SrcOff < Slice.Length) {
SubSlice = Slice;
SubSlice.move(SrcOff);
} else {
// This is an out-of-bounds access and hence UB. Pretend we read zero.
SubSlice.Array = nullptr;
SubSlice.Offset = 0;
SubSlice.Length = VTSize;
}
Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
if (Value.getNode()) {
Store = DAG.getStore(
Chain, dl, Value,
DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
DstPtrInfo.getWithOffset(DstOff), Alignment.value(), MMOFlags);
OutChains.push_back(Store);
}
}
if (!Store.getNode()) {
// The type might not be legal for the target. This should only happen
// if the type is smaller than a legal type, as on PPC, so the right
// thing to do is generate a LoadExt/StoreTrunc pair. These simplify
// to Load/Store if NVT==VT.
// FIXME does the case above also need this?
EVT NVT = TLI.getTypeToTransformTo(C, VT);
assert(NVT.bitsGE(VT));
bool isDereferenceable =
SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
if (isDereferenceable)
SrcMMOFlags |= MachineMemOperand::MODereferenceable;
Value = DAG.getExtLoad(
ISD::EXTLOAD, dl, NVT, Chain,
DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
SrcPtrInfo.getWithOffset(SrcOff), VT,
commonAlignment(*SrcAlign, SrcOff).value(), SrcMMOFlags);
OutLoadChains.push_back(Value.getValue(1));
Store = DAG.getTruncStore(
Chain, dl, Value,
DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
DstPtrInfo.getWithOffset(DstOff), VT, Alignment.value(), MMOFlags);
OutStoreChains.push_back(Store);
}
SrcOff += VTSize;
DstOff += VTSize;
Size -= VTSize;
}
unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
unsigned NumLdStInMemcpy = OutStoreChains.size();
if (NumLdStInMemcpy) {
// It may be that memcpy might be converted to memset if it's memcpy
// of constants. In such a case, we won't have loads and stores, but
// just stores. In the absence of loads, there is nothing to gang up.
if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
// If target does not care, just leave as it.
for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
OutChains.push_back(OutLoadChains[i]);
OutChains.push_back(OutStoreChains[i]);
}
} else {
// Ld/St less than/equal limit set by target.
if (NumLdStInMemcpy <= GluedLdStLimit) {
chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
NumLdStInMemcpy, OutLoadChains,
OutStoreChains);
} else {
unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
unsigned GlueIter = 0;
for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
unsigned IndexTo = NumLdStInMemcpy - GlueIter;
chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
OutLoadChains, OutStoreChains);
GlueIter += GluedLdStLimit;
}
// Residual ld/st.
if (RemainingLdStInMemcpy) {
chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
RemainingLdStInMemcpy, OutLoadChains,
OutStoreChains);
}
}
}
}
return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
}
static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
SDValue Chain, SDValue Dst, SDValue Src,
uint64_t Size, Align Alignment,
bool isVol, bool AlwaysInline,
MachinePointerInfo DstPtrInfo,
MachinePointerInfo SrcPtrInfo) {
// Turn a memmove of undef to nop.
// FIXME: We need to honor volatile even is Src is undef.
if (Src.isUndef())
return Chain;
// Expand memmove to a series of load and store ops if the size operand falls
// below a certain threshold.
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const DataLayout &DL = DAG.getDataLayout();
LLVMContext &C = *DAG.getContext();
std::vector<EVT> MemOps;
bool DstAlignCanChange = false;
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo &MFI = MF.getFrameInfo();
bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
DstAlignCanChange = true;
MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
if (!SrcAlign || Alignment > *SrcAlign)
SrcAlign = Alignment;
assert(SrcAlign && "SrcAlign must be set");
unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
if (!TLI.findOptimalMemOpLowering(
MemOps, Limit,
MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
/*IsVolatile*/ true),
DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
MF.getFunction().getAttributes()))
return SDValue();
if (DstAlignCanChange) {
Type *Ty = MemOps[0].getTypeForEVT(C);
Align NewAlign = DL.getABITypeAlign(Ty);
if (NewAlign > Alignment) {
// Give the stack frame object a larger alignment if needed.
if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
MFI.setObjectAlignment(FI->getIndex(), NewAlign);
Alignment = NewAlign;
}
}
MachineMemOperand::Flags MMOFlags =
isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
uint64_t SrcOff = 0, DstOff = 0;
SmallVector<SDValue, 8> LoadValues;
SmallVector<SDValue, 8> LoadChains;
SmallVector<SDValue, 8> OutChains;
unsigned NumMemOps = MemOps.size();
for (unsigned i = 0; i < NumMemOps; i++) {
EVT VT = MemOps[i];
unsigned VTSize = VT.getSizeInBits() / 8;
SDValue Value;
bool isDereferenceable =
SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
if (isDereferenceable)
SrcMMOFlags |= MachineMemOperand::MODereferenceable;
Value = DAG.getLoad(
VT, dl, Chain,
DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
SrcPtrInfo.getWithOffset(SrcOff), SrcAlign->value(), SrcMMOFlags);
LoadValues.push_back(Value);
LoadChains.push_back(Value.getValue(1));
SrcOff += VTSize;
}
Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
OutChains.clear();
for (unsigned i = 0; i < NumMemOps; i++) {
EVT VT = MemOps[i];
unsigned VTSize = VT.getSizeInBits() / 8;
SDValue Store;
Store = DAG.getStore(
Chain, dl, LoadValues[i],
DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
DstPtrInfo.getWithOffset(DstOff), Alignment.value(), MMOFlags);
OutChains.push_back(Store);
DstOff += VTSize;
}
return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
}
/// Lower the call to 'memset' intrinsic function into a series of store
/// operations.
///
/// \param DAG Selection DAG where lowered code is placed.
/// \param dl Link to corresponding IR location.
/// \param Chain Control flow dependency.
/// \param Dst Pointer to destination memory location.
/// \param Src Value of byte to write into the memory.
/// \param Size Number of bytes to write.
/// \param Alignment Alignment of the destination in bytes.
/// \param isVol True if destination is volatile.
/// \param DstPtrInfo IR information on the memory pointer.
/// \returns New head in the control flow, if lowering was successful, empty
/// SDValue otherwise.
///
/// The function tries to replace 'llvm.memset' intrinsic with several store
/// operations and value calculation code. This is usually profitable for small
/// memory size.
static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
SDValue Chain, SDValue Dst, SDValue Src,
uint64_t Size, Align Alignment, bool isVol,
MachinePointerInfo DstPtrInfo) {
// Turn a memset of undef to nop.
// FIXME: We need to honor volatile even is Src is undef.
if (Src.isUndef())
return Chain;
// Expand memset to a series of load/store ops if the size operand
// falls below a certain threshold.
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
std::vector<EVT> MemOps;
bool DstAlignCanChange = false;
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo &MFI = MF.getFrameInfo();
bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
DstAlignCanChange = true;
bool IsZeroVal =
isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
if (!TLI.findOptimalMemOpLowering(
MemOps, TLI.getMaxStoresPerMemset(OptSize),
MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
return SDValue();
if (DstAlignCanChange) {
Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
if (NewAlign > Alignment) {
// Give the stack frame object a larger alignment if needed.
if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
MFI.setObjectAlignment(FI->getIndex(), NewAlign);
Alignment = NewAlign;
}
}
SmallVector<SDValue, 8> OutChains;
uint64_t DstOff = 0;
unsigned NumMemOps = MemOps.size();
// Find the largest store and generate the bit pattern for it.
EVT LargestVT = MemOps[0];
for (unsigned i = 1; i < NumMemOps; i++)
if (MemOps[i].bitsGT(LargestVT))
LargestVT = MemOps[i];
SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
for (unsigned i = 0; i < NumMemOps; i++) {
EVT VT = MemOps[i];
unsigned VTSize = VT.getSizeInBits() / 8;
if (VTSize > Size) {
// Issuing an unaligned load / store pair that overlaps with the previous
// pair. Adjust the offset accordingly.
assert(i == NumMemOps-1 && i != 0);
DstOff -= VTSize - Size;
}
// If this store is smaller than the largest store see whether we can get
// the smaller value for free with a truncate.
SDValue Value = MemSetValue;
if (VT.bitsLT(LargestVT)) {
if (!LargestVT.isVector() && !VT.isVector() &&
TLI.isTruncateFree(LargestVT, VT))
Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
else
Value = getMemsetValue(Src, VT, DAG, dl);
}
assert(Value.getValueType() == VT && "Value with wrong type.");
SDValue Store = DAG.getStore(
Chain, dl, Value,
DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
DstPtrInfo.getWithOffset(DstOff), Alignment.value(),
isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
OutChains.push_back(Store);
DstOff += VT.getSizeInBits() / 8;
Size -= VTSize;
}
return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
}
static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
unsigned AS) {
// Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
// pointer operands can be losslessly bitcasted to pointers of address space 0
if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
report_fatal_error("cannot lower memory intrinsic in address space " +
Twine(AS));
}
}
SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
SDValue Src, SDValue Size, Align Alignment,
bool isVol, bool AlwaysInline, bool isTailCall,
MachinePointerInfo DstPtrInfo,
MachinePointerInfo SrcPtrInfo) {
// Check to see if we should lower the memcpy to loads and stores first.
// For cases within the target-specified limits, this is the best choice.
ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
if (ConstantSize) {
// Memcpy with size zero? Just return the original chain.
if (ConstantSize->isNullValue())
return Chain;
SDValue Result = getMemcpyLoadsAndStores(
*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
isVol, false, DstPtrInfo, SrcPtrInfo);
if (Result.getNode())
return Result;
}
// Then check to see if we should lower the memcpy with target-specific
// code. If the target chooses to do this, this is the next best.
if (TSI) {
SDValue Result = TSI->EmitTargetCodeForMemcpy(
*this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
DstPtrInfo, SrcPtrInfo);
if (Result.getNode())
return Result;
}
// If we really need inline code and the target declined to provide it,
// use a (potentially long) sequence of loads and stores.
if (AlwaysInline) {
assert(ConstantSize && "AlwaysInline requires a constant size!");
return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
ConstantSize->getZExtValue(), Alignment,
isVol, true, DstPtrInfo, SrcPtrInfo);
}
checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
// FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
// memcpy is not guaranteed to be safe. libc memcpys aren't required to
// respect volatile, so they may do things like read or write memory
// beyond the given memory regions. But fixing this isn't easy, and most
// people don't care.
// Emit a library call.
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Ty = Type::getInt8PtrTy(*getContext());
Entry.Node = Dst; Args.push_back(Entry);
Entry.Node = Src; Args.push_back(Entry);
Entry.Ty = getDataLayout().getIntPtrType(*getContext());
Entry.Node = Size; Args.push_back(Entry);
// FIXME: pass in SDLoc
TargetLowering::CallLoweringInfo CLI(*this);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
Dst.getValueType().getTypeForEVT(*getContext()),
getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
TLI->getPointerTy(getDataLayout())),
std::move(Args))
.setDiscardResult()
.setTailCall(isTailCall);
std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
return CallResult.second;
}
SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
SDValue Dst, unsigned DstAlign,
SDValue Src, unsigned SrcAlign,
SDValue Size, Type *SizeTy,
unsigned ElemSz, bool isTailCall,
MachinePointerInfo DstPtrInfo,
MachinePointerInfo SrcPtrInfo) {
// Emit a library call.
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Ty = getDataLayout().getIntPtrType(*getContext());
Entry.Node = Dst;
Args.push_back(Entry);
Entry.Node = Src;
Args.push_back(Entry);
Entry.Ty = SizeTy;
Entry.Node = Size;
Args.push_back(Entry);
RTLIB::Libcall LibraryCall =
RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
report_fatal_error("Unsupported element size");
TargetLowering::CallLoweringInfo CLI(*this);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
Type::getVoidTy(*getContext()),
getExternalSymbol(TLI->getLibcallName(LibraryCall),
TLI->getPointerTy(getDataLayout())),
std::move(Args))
.setDiscardResult()
.setTailCall(isTailCall);
std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
return CallResult.second;
}
SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
SDValue Src, SDValue Size, Align Alignment,
bool isVol, bool isTailCall,
MachinePointerInfo DstPtrInfo,
MachinePointerInfo SrcPtrInfo) {
// Check to see if we should lower the memmove to loads and stores first.
// For cases within the target-specified limits, this is the best choice.
ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
if (ConstantSize) {
// Memmove with size zero? Just return the original chain.
if (ConstantSize->isNullValue())
return Chain;
SDValue Result = getMemmoveLoadsAndStores(
*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
isVol, false, DstPtrInfo, SrcPtrInfo);
if (Result.getNode())
return Result;
}
// Then check to see if we should lower the memmove with target-specific
// code. If the target chooses to do this, this is the next best.
if (TSI) {
SDValue Result =
TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
Alignment, isVol, DstPtrInfo, SrcPtrInfo);
if (Result.getNode())
return Result;
}
checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
// FIXME: If the memmove is volatile, lowering it to plain libc memmove may
// not be safe. See memcpy above for more details.
// Emit a library call.
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Ty = Type::getInt8PtrTy(*getContext());
Entry.Node = Dst; Args.push_back(Entry);
Entry.Node = Src; Args.push_back(Entry);
Entry.Ty = getDataLayout().getIntPtrType(*getContext());
Entry.Node = Size; Args.push_back(Entry);
// FIXME: pass in SDLoc
TargetLowering::CallLoweringInfo CLI(*this);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
Dst.getValueType().getTypeForEVT(*getContext()),
getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
TLI->getPointerTy(getDataLayout())),
std::move(Args))
.setDiscardResult()
.setTailCall(isTailCall);
std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
return CallResult.second;
}
SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
SDValue Dst, unsigned DstAlign,
SDValue Src, unsigned SrcAlign,
SDValue Size, Type *SizeTy,
unsigned ElemSz, bool isTailCall,
MachinePointerInfo DstPtrInfo,
MachinePointerInfo SrcPtrInfo) {
// Emit a library call.
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Ty = getDataLayout().getIntPtrType(*getContext());
Entry.Node = Dst;
Args.push_back(Entry);
Entry.Node = Src;
Args.push_back(Entry);
Entry.Ty = SizeTy;
Entry.Node = Size;
Args.push_back(Entry);
RTLIB::Libcall LibraryCall =
RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
report_fatal_error("Unsupported element size");
TargetLowering::CallLoweringInfo CLI(*this);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
Type::getVoidTy(*getContext()),
getExternalSymbol(TLI->getLibcallName(LibraryCall),
TLI->getPointerTy(getDataLayout())),
std::move(Args))
.setDiscardResult()
.setTailCall(isTailCall);
std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
return CallResult.second;
}
SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
SDValue Src, SDValue Size, Align Alignment,
bool isVol, bool isTailCall,
MachinePointerInfo DstPtrInfo) {
// Check to see if we should lower the memset to stores first.
// For cases within the target-specified limits, this is the best choice.
ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
if (ConstantSize) {
// Memset with size zero? Just return the original chain.
if (ConstantSize->isNullValue())
return Chain;
SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
ConstantSize->getZExtValue(), Alignment,
isVol, DstPtrInfo);
if (Result.getNode())
return Result;
}
// Then check to see if we should lower the memset with target-specific
// code. If the target chooses to do this, this is the next best.
if (TSI) {
SDValue Result = TSI->EmitTargetCodeForMemset(
*this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
if (Result.getNode())
return Result;
}
checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
// Emit a library call.
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
Args.push_back(Entry);
Entry.Node = Src;
Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
Args.push_back(Entry);
Entry.Node = Size;
Entry.Ty = getDataLayout().getIntPtrType(*getContext());
Args.push_back(Entry);
// FIXME: pass in SDLoc
TargetLowering::CallLoweringInfo CLI(*this);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
Dst.getValueType().getTypeForEVT(*getContext()),
getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
TLI->getPointerTy(getDataLayout())),
std::move(Args))
.setDiscardResult()
.setTailCall(isTailCall);
std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
return CallResult.second;
}
SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
SDValue Dst, unsigned DstAlign,
SDValue Value, SDValue Size, Type *SizeTy,
unsigned ElemSz, bool isTailCall,
MachinePointerInfo DstPtrInfo) {
// Emit a library call.
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Ty = getDataLayout().getIntPtrType(*getContext());
Entry.Node = Dst;
Args.push_back(Entry);
Entry.Ty = Type::getInt8Ty(*getContext());
Entry.Node = Value;
Args.push_back(Entry);
Entry.Ty = SizeTy;
Entry.Node = Size;
Args.push_back(Entry);
RTLIB::Libcall LibraryCall =
RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
report_fatal_error("Unsupported element size");
TargetLowering::CallLoweringInfo CLI(*this);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
Type::getVoidTy(*getContext()),
getExternalSymbol(TLI->getLibcallName(LibraryCall),
TLI->getPointerTy(getDataLayout())),
std::move(Args))
.setDiscardResult()
.setTailCall(isTailCall);
std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
return CallResult.second;
}
SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
SDVTList VTList, ArrayRef<SDValue> Ops,
MachineMemOperand *MMO) {
FoldingSetNodeID ID;
ID.AddInteger(MemVT.getRawBits());
AddNodeIDNode(ID, Opcode, VTList, Ops);
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void* IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<AtomicSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
VTList, MemVT, MMO);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
return SDValue(N, 0);
}
SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
EVT MemVT, SDVTList VTs, SDValue Chain,
SDValue Ptr, SDValue Cmp, SDValue Swp,
MachineMemOperand *MMO) {
assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
}
SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
SDValue Chain, SDValue Ptr, SDValue Val,
MachineMemOperand *MMO) {
assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
Opcode == ISD::ATOMIC_LOAD_SUB ||
Opcode == ISD::ATOMIC_LOAD_AND ||
Opcode == ISD::ATOMIC_LOAD_CLR ||
Opcode == ISD::ATOMIC_LOAD_OR ||
Opcode == ISD::ATOMIC_LOAD_XOR ||
Opcode == ISD::ATOMIC_LOAD_NAND ||
Opcode == ISD::ATOMIC_LOAD_MIN ||
Opcode == ISD::ATOMIC_LOAD_MAX ||
Opcode == ISD::ATOMIC_LOAD_UMIN ||
Opcode == ISD::ATOMIC_LOAD_UMAX ||
Opcode == ISD::ATOMIC_LOAD_FADD ||
Opcode == ISD::ATOMIC_LOAD_FSUB ||
Opcode == ISD::ATOMIC_SWAP ||
Opcode == ISD::ATOMIC_STORE) &&
"Invalid Atomic Op");
EVT VT = Val.getValueType();
SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
getVTList(VT, MVT::Other);
SDValue Ops[] = {Chain, Ptr, Val};
return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
}
SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
EVT VT, SDValue Chain, SDValue Ptr,
MachineMemOperand *MMO) {
assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
SDVTList VTs = getVTList(VT, MVT::Other);
SDValue Ops[] = {Chain, Ptr};
return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
}
/// getMergeValues - Create a MERGE_VALUES node from the given operands.
SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
if (Ops.size() == 1)
return Ops[0];
SmallVector<EVT, 4> VTs;
VTs.reserve(Ops.size());
for (unsigned i = 0; i < Ops.size(); ++i)
VTs.push_back(Ops[i].getValueType());
return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
}
SDValue SelectionDAG::getMemIntrinsicNode(
unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
if (!Size && MemVT.isScalableVector())
Size = MemoryLocation::UnknownSize;
else if (!Size)
Size = MemVT.getStoreSize();
MachineFunction &MF = getMachineFunction();
MachineMemOperand *MMO =
MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
}
SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
SDVTList VTList,
ArrayRef<SDValue> Ops, EVT MemVT,
MachineMemOperand *MMO) {
assert((Opcode == ISD::INTRINSIC_VOID ||
Opcode == ISD::INTRINSIC_W_CHAIN ||
Opcode == ISD::PREFETCH ||
((int)Opcode <= std::numeric_limits<int>::max() &&
(int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
"Opcode is not a memory-accessing opcode!");
// Memoize the node unless it returns a flag.
MemIntrinsicSDNode *N;
if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTList, Ops);
ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
Opcode, dl.getIROrder(), VTList, MemVT, MMO));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
VTList, MemVT, MMO);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
} else {
N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
VTList, MemVT, MMO);
createOperands(N, Ops);
}
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
SDValue Chain, int FrameIndex,
int64_t Size, int64_t Offset) {
const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
const auto VTs = getVTList(MVT::Other);
SDValue Ops[2] = {
Chain,
getFrameIndex(FrameIndex,
getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
true)};
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTs, Ops);
ID.AddInteger(FrameIndex);
ID.AddInteger(Size);
ID.AddInteger(Offset);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
return SDValue(E, 0);
LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
/// MachinePointerInfo record from it. This is particularly useful because the
/// code generator has many cases where it doesn't bother passing in a
/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
SelectionDAG &DAG, SDValue Ptr,
int64_t Offset = 0) {
// If this is FI+Offset, we can model it.
if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
FI->getIndex(), Offset);
// If this is (FI+Offset1)+Offset2, we can model it.
if (Ptr.getOpcode() != ISD::ADD ||
!isa<ConstantSDNode>(Ptr.getOperand(1)) ||
!isa<FrameIndexSDNode>(Ptr.getOperand(0)))
return Info;
int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
return MachinePointerInfo::getFixedStack(
DAG.getMachineFunction(), FI,
Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
}
/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
/// MachinePointerInfo record from it. This is particularly useful because the
/// code generator has many cases where it doesn't bother passing in a
/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
SelectionDAG &DAG, SDValue Ptr,
SDValue OffsetOp) {
// If the 'Offset' value isn't a constant, we can't handle this.
if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
if (OffsetOp.isUndef())
return InferPointerInfo(Info, DAG, Ptr);
return Info;
}
SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
EVT VT, const SDLoc &dl, SDValue Chain,
SDValue Ptr, SDValue Offset,
MachinePointerInfo PtrInfo, EVT MemVT,
Align Alignment,
MachineMemOperand::Flags MMOFlags,
const AAMDNodes &AAInfo, const MDNode *Ranges) {
assert(Chain.getValueType() == MVT::Other &&
"Invalid chain type");
MMOFlags |= MachineMemOperand::MOLoad;
assert((MMOFlags & MachineMemOperand::MOStore) == 0);
// If we don't have a PtrInfo, infer the trivial frame index case to simplify
// clients.
if (PtrInfo.V.isNull())
PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
MachineFunction &MF = getMachineFunction();
MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
Alignment, AAInfo, Ranges);
return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
}
SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
EVT VT, const SDLoc &dl, SDValue Chain,
SDValue Ptr, SDValue Offset, EVT MemVT,
MachineMemOperand *MMO) {
if (VT == MemVT) {
ExtType = ISD::NON_EXTLOAD;
} else if (ExtType == ISD::NON_EXTLOAD) {
assert(VT == MemVT && "Non-extending load from different memory type!");
} else {
// Extending load.
assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
"Should only be an extending load, not truncating!");
assert(VT.isInteger() == MemVT.isInteger() &&
"Cannot convert from FP to Int or Int -> FP!");
assert(VT.isVector() == MemVT.isVector() &&
"Cannot use an ext load to convert to or from a vector!");
assert((!VT.isVector() ||
VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
"Cannot use an ext load to change the number of vector elements!");
}
bool Indexed = AM != ISD::UNINDEXED;
assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
SDVTList VTs = Indexed ?
getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
SDValue Ops[] = { Chain, Ptr, Offset };
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
ID.AddInteger(MemVT.getRawBits());
ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<LoadSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
ExtType, MemVT, MMO);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
SDValue Ptr, MachinePointerInfo PtrInfo,
MaybeAlign Alignment,
MachineMemOperand::Flags MMOFlags,
const AAMDNodes &AAInfo, const MDNode *Ranges) {
SDValue Undef = getUNDEF(Ptr.getValueType());
return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
}
SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
SDValue Ptr, MachineMemOperand *MMO) {
SDValue Undef = getUNDEF(Ptr.getValueType());
return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
VT, MMO);
}
SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
EVT VT, SDValue Chain, SDValue Ptr,
MachinePointerInfo PtrInfo, EVT MemVT,
MaybeAlign Alignment,
MachineMemOperand::Flags MMOFlags,
const AAMDNodes &AAInfo) {
SDValue Undef = getUNDEF(Ptr.getValueType());
return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
MemVT, Alignment, MMOFlags, AAInfo);
}
SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
MachineMemOperand *MMO) {
SDValue Undef = getUNDEF(Ptr.getValueType());
return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
MemVT, MMO);
}
SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
SDValue Base, SDValue Offset,
ISD::MemIndexedMode AM) {
LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
// Don't propagate the invariant or dereferenceable flags.
auto MMOFlags =
LD->getMemOperand()->getFlags() &
~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
LD->getChain(), Base, Offset, LD->getPointerInfo(),
LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
LD->getAAInfo());
}
SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
SDValue Ptr, MachinePointerInfo PtrInfo,
Align Alignment,
MachineMemOperand::Flags MMOFlags,
const AAMDNodes &AAInfo) {
assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
MMOFlags |= MachineMemOperand::MOStore;
assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
if (PtrInfo.V.isNull())
PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
MachineFunction &MF = getMachineFunction();
uint64_t Size =
MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
MachineMemOperand *MMO =
MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
return getStore(Chain, dl, Val, Ptr, MMO);
}
SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
SDValue Ptr, MachineMemOperand *MMO) {
assert(Chain.getValueType() == MVT::Other &&
"Invalid chain type");
EVT VT = Val.getValueType();
SDVTList VTs = getVTList(MVT::Other);
SDValue Undef = getUNDEF(Ptr.getValueType());
SDValue Ops[] = { Chain, Val, Ptr, Undef };
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
ID.AddInteger(VT.getRawBits());
ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<StoreSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
ISD::UNINDEXED, false, VT, MMO);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
SDValue Ptr, MachinePointerInfo PtrInfo,
EVT SVT, Align Alignment,
MachineMemOperand::Flags MMOFlags,
const AAMDNodes &AAInfo) {
assert(Chain.getValueType() == MVT::Other &&
"Invalid chain type");
MMOFlags |= MachineMemOperand::MOStore;
assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
if (PtrInfo.V.isNull())
PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
MachineFunction &MF = getMachineFunction();
MachineMemOperand *MMO = MF.getMachineMemOperand(
PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
}
SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
SDValue Ptr, EVT SVT,
MachineMemOperand *MMO) {
EVT VT = Val.getValueType();
assert(Chain.getValueType() == MVT::Other &&
"Invalid chain type");
if (VT == SVT)
return getStore(Chain, dl, Val, Ptr, MMO);
assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
"Should only be a truncating store, not extending!");
assert(VT.isInteger() == SVT.isInteger() &&
"Can't do FP-INT conversion!");
assert(VT.isVector() == SVT.isVector() &&
"Cannot use trunc store to convert to or from a vector!");
assert((!VT.isVector() ||
VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
"Cannot use trunc store to change the number of vector elements!");
SDVTList VTs = getVTList(MVT::Other);
SDValue Undef = getUNDEF(Ptr.getValueType());
SDValue Ops[] = { Chain, Val, Ptr, Undef };
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
ID.AddInteger(SVT.getRawBits());
ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<StoreSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
ISD::UNINDEXED, true, SVT, MMO);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
SDValue Base, SDValue Offset,
ISD::MemIndexedMode AM) {
StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
ID.AddInteger(ST->getMemoryVT().getRawBits());
ID.AddInteger(ST->getRawSubclassData());
ID.AddInteger(ST->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
return SDValue(E, 0);
auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
ST->isTruncatingStore(), ST->getMemoryVT(),
ST->getMemOperand());
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
SDValue Base, SDValue Offset, SDValue Mask,
SDValue PassThru, EVT MemVT,
MachineMemOperand *MMO,
ISD::MemIndexedMode AM,
ISD::LoadExtType ExtTy, bool isExpanding) {
bool Indexed = AM != ISD::UNINDEXED;
assert((Indexed || Offset.isUndef()) &&
"Unindexed masked load with an offset!");
SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
: getVTList(VT, MVT::Other);
SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
ID.AddInteger(MemVT.getRawBits());
ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
AM, ExtTy, isExpanding, MemVT, MMO);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
SDValue Base, SDValue Offset,
ISD::MemIndexedMode AM) {
MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
Offset, LD->getMask(), LD->getPassThru(),
LD->getMemoryVT(), LD->getMemOperand(), AM,
LD->getExtensionType(), LD->isExpandingLoad());
}
SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
SDValue Val, SDValue Base, SDValue Offset,
SDValue Mask, EVT MemVT,
MachineMemOperand *MMO,
ISD::MemIndexedMode AM, bool IsTruncating,
bool IsCompressing) {
assert(Chain.getValueType() == MVT::Other &&
"Invalid chain type");
bool Indexed = AM != ISD::UNINDEXED;
assert((Indexed || Offset.isUndef()) &&
"Unindexed masked store with an offset!");
SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
: getVTList(MVT::Other);
SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
ID.AddInteger(MemVT.getRawBits());
ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N =
newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
IsTruncating, IsCompressing, MemVT, MMO);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
SDValue Base, SDValue Offset,
ISD::MemIndexedMode AM) {
MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
assert(ST->getOffset().isUndef() &&
"Masked store is already a indexed store!");
return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
AM, ST->isTruncatingStore(), ST->isCompressingStore());
}
SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
ArrayRef<SDValue> Ops,
MachineMemOperand *MMO,
ISD::MemIndexType IndexType) {
assert(Ops.size() == 6 && "Incompatible number of operands");
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
ID.AddInteger(VT.getRawBits());
ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
dl.getIROrder(), VTs, VT, MMO, IndexType));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
VTs, VT, MMO, IndexType);
createOperands(N, Ops);
assert(N->getPassThru().getValueType() == N->getValueType(0) &&
"Incompatible type of the PassThru value in MaskedGatherSDNode");
assert(N->getMask().getValueType().getVectorNumElements() ==
N->getValueType(0).getVectorNumElements() &&
"Vector width mismatch between mask and data");
assert(N->getIndex().getValueType().getVectorNumElements() >=
N->getValueType(0).getVectorNumElements() &&
"Vector width mismatch between index and data");
assert(isa<ConstantSDNode>(N->getScale()) &&
cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
"Scale should be a constant power of 2");
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
ArrayRef<SDValue> Ops,
MachineMemOperand *MMO,
ISD::MemIndexType IndexType) {
assert(Ops.size() == 6 && "Incompatible number of operands");
FoldingSetNodeID ID;
AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
ID.AddInteger(VT.getRawBits());
ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
dl.getIROrder(), VTs, VT, MMO, IndexType));
ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
return SDValue(E, 0);
}
auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
VTs, VT, MMO, IndexType);
createOperands(N, Ops);
assert(N->getMask().getValueType().getVectorNumElements() ==
N->getValue().getValueType().getVectorNumElements() &&
"Vector width mismatch between mask and data");
assert(N->getIndex().getValueType().getVectorNumElements() >=
N->getValue().getValueType().getVectorNumElements() &&
"Vector width mismatch between index and data");
assert(isa<ConstantSDNode>(N->getScale()) &&
cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
"Scale should be a constant power of 2");
CSEMap.InsertNode(N, IP);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
// select undef, T, F --> T (if T is a constant), otherwise F
// select, ?, undef, F --> F
// select, ?, T, undef --> T
if (Cond.isUndef())
return isConstantValueOfAnyType(T) ? T : F;
if (T.isUndef())
return F;
if (F.isUndef())
return T;
// select true, T, F --> T
// select false, T, F --> F
if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
return CondC->isNullValue() ? F : T;
// TODO: This should simplify VSELECT with constant condition using something
// like this (but check boolean contents to be complete?):
// if (ISD::isBuildVectorAllOnes(Cond.getNode()))
// return T;
// if (ISD::isBuildVectorAllZeros(Cond.getNode()))
// return F;
// select ?, T, T --> T
if (T == F)
return T;
return SDValue();
}
SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
// shift undef, Y --> 0 (can always assume that the undef value is 0)
if (X.isUndef())
return getConstant(0, SDLoc(X.getNode()), X.getValueType());
// shift X, undef --> undef (because it may shift by the bitwidth)
if (Y.isUndef())
return getUNDEF(X.getValueType());
// shift 0, Y --> 0
// shift X, 0 --> X
if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
return X;
// shift X, C >= bitwidth(X) --> undef
// All vector elements must be too big (or undef) to avoid partial undefs.
auto isShiftTooBig = [X](ConstantSDNode *Val) {
return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
};
if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
return getUNDEF(X.getValueType());
return SDValue();
}
SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
SDNodeFlags Flags) {
// If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
// (an undef operand can be chosen to be Nan/Inf), then the result of this
// operation is poison. That result can be relaxed to undef.
ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
(YC && YC->getValueAPF().isNaN());
bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
(YC && YC->getValueAPF().isInfinity());
if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
return getUNDEF(X.getValueType());
if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
return getUNDEF(X.getValueType());
if (!YC)
return SDValue();
// X + -0.0 --> X
if (Opcode == ISD::FADD)
if (YC->getValueAPF().isNegZero())
return X;
// X - +0.0 --> X
if (Opcode == ISD::FSUB)
if (YC->getValueAPF().isPosZero())
return X;
// X * 1.0 --> X
// X / 1.0 --> X
if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
if (YC->getValueAPF().isExactlyValue(1.0))
return X;
return SDValue();
}
SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
SDValue Ptr, SDValue SV, unsigned Align) {
SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
ArrayRef<SDUse> Ops) {
switch (Ops.size()) {
case 0: return getNode(Opcode, DL, VT);
case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
default: break;
}
// Copy from an SDUse array into an SDValue array for use with
// the regular getNode logic.
SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
return getNode(Opcode, DL, VT, NewOps);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
unsigned NumOps = Ops.size();
switch (NumOps) {
case 0: return getNode(Opcode, DL, VT);
case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
default: break;
}
switch (Opcode) {
default: break;
case ISD::BUILD_VECTOR:
// Attempt to simplify BUILD_VECTOR.
if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
return V;
break;
case ISD::CONCAT_VECTORS:
if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
return V;
break;
case ISD::SELECT_CC:
assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
assert(Ops[0].getValueType() == Ops[1].getValueType() &&
"LHS and RHS of condition must have same type!");
assert(Ops[2].getValueType() == Ops[3].getValueType() &&
"True and False arms of SelectCC must have same type!");
assert(Ops[2].getValueType() == VT &&
"select_cc node must be of same type as true and false value!");
break;
case ISD::BR_CC:
assert(NumOps == 5 && "BR_CC takes 5 operands!");
assert(Ops[2].getValueType() == Ops[3].getValueType() &&
"LHS/RHS of comparison should match types!");
break;
}
// Memoize nodes.
SDNode *N;
SDVTList VTs = getVTList(VT);
if (VT != MVT::Glue) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTs, Ops);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
return SDValue(E, 0);
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
} else {
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
createOperands(N, Ops);
}
N->setFlags(Flags);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
return getNode(Opcode, DL, getVTList(ResultTys), Ops);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
if (VTList.NumVTs == 1)
return getNode(Opcode, DL, VTList.VTs[0], Ops);
switch (Opcode) {
case ISD::STRICT_FP_EXTEND:
assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
"Invalid STRICT_FP_EXTEND!");
assert(VTList.VTs[0].isFloatingPoint() &&
Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
"STRICT_FP_EXTEND result type should be vector iff the operand "
"type is vector!");
assert((!VTList.VTs[0].isVector() ||
VTList.VTs[0].getVectorNumElements() ==
Ops[1].getValueType().getVectorNumElements()) &&
"Vector element count mismatch!");
assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
"Invalid fpext node, dst <= src!");
break;
case ISD::STRICT_FP_ROUND:
assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
"STRICT_FP_ROUND result type should be vector iff the operand "
"type is vector!");
assert((!VTList.VTs[0].isVector() ||
VTList.VTs[0].getVectorNumElements() ==
Ops[1].getValueType().getVectorNumElements()) &&
"Vector element count mismatch!");
assert(VTList.VTs[0].isFloatingPoint() &&
Ops[1].getValueType().isFloatingPoint() &&
VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
isa<ConstantSDNode>(Ops[2]) &&
(cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
"Invalid STRICT_FP_ROUND!");
break;
#if 0
// FIXME: figure out how to safely handle things like
// int foo(int x) { return 1 << (x & 255); }
// int bar() { return foo(256); }
case ISD::SRA_PARTS:
case ISD::SRL_PARTS:
case ISD::SHL_PARTS:
if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
else if (N3.getOpcode() == ISD::AND)
if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
// If the and is only masking out bits that cannot effect the shift,
// eliminate the and.
unsigned NumBits = VT.getScalarSizeInBits()*2;
if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
}
break;
#endif
}
// Memoize the node unless it returns a flag.
SDNode *N;
if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTList, Ops);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
return SDValue(E, 0);
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
createOperands(N, Ops);
CSEMap.InsertNode(N, IP);
} else {
N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
createOperands(N, Ops);
}
N->setFlags(Flags);
InsertNode(N);
SDValue V(N, 0);
NewSDValueDbgMsg(V, "Creating new node: ", this);
return V;
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
SDVTList VTList) {
return getNode(Opcode, DL, VTList, None);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
SDValue N1) {
SDValue Ops[] = { N1 };
return getNode(Opcode, DL, VTList, Ops);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
SDValue N1, SDValue N2) {
SDValue Ops[] = { N1, N2 };
return getNode(Opcode, DL, VTList, Ops);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
SDValue N1, SDValue N2, SDValue N3) {
SDValue Ops[] = { N1, N2, N3 };
return getNode(Opcode, DL, VTList, Ops);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
SDValue Ops[] = { N1, N2, N3, N4 };
return getNode(Opcode, DL, VTList, Ops);
}
SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
SDValue N1, SDValue N2, SDValue N3, SDValue N4,
SDValue N5) {
SDValue Ops[] = { N1, N2, N3, N4, N5 };
return getNode(Opcode, DL, VTList, Ops);
}
SDVTList SelectionDAG::getVTList(EVT VT) {
return makeVTList(SDNode::getValueTypeList(VT), 1);
}
SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
FoldingSetNodeID ID;
ID.AddInteger(2U);
ID.AddInteger(VT1.getRawBits());
ID.AddInteger(VT2.getRawBits());
void *IP = nullptr;
SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
if (!Result) {
EVT *Array = Allocator.Allocate<EVT>(2);
Array[0] = VT1;
Array[1] = VT2;
Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
VTListMap.InsertNode(Result, IP);
}
return Result->getSDVTList();
}
SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
FoldingSetNodeID ID;
ID.AddInteger(3U);
ID.AddInteger(VT1.getRawBits());
ID.AddInteger(VT2.getRawBits());
ID.AddInteger(VT3.getRawBits());
void *IP = nullptr;
SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
if (!Result) {
EVT *Array = Allocator.Allocate<EVT>(3);
Array[0] = VT1;
Array[1] = VT2;
Array[2] = VT3;
Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
VTListMap.InsertNode(Result, IP);
}
return Result->getSDVTList();
}
SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
FoldingSetNodeID ID;
ID.AddInteger(4U);
ID.AddInteger(VT1.getRawBits());
ID.AddInteger(VT2.getRawBits());
ID.AddInteger(VT3.getRawBits());
ID.AddInteger(VT4.getRawBits());
void *IP = nullptr;
SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
if (!Result) {
EVT *Array = Allocator.Allocate<EVT>(4);
Array[0] = VT1;
Array[1] = VT2;
Array[2] = VT3;
Array[3] = VT4;
Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
VTListMap.InsertNode(Result, IP);
}
return Result->getSDVTList();
}
SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
unsigned NumVTs = VTs.size();
FoldingSetNodeID ID;
ID.AddInteger(NumVTs);
for (unsigned index = 0; index < NumVTs; index++) {
ID.AddInteger(VTs[index].getRawBits());
}
void *IP = nullptr;
SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
if (!Result) {
EVT *Array = Allocator.Allocate<EVT>(NumVTs);
llvm::copy(VTs, Array);
Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
VTListMap.InsertNode(Result, IP);
}
return Result->getSDVTList();
}
/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
/// specified operands. If the resultant node already exists in the DAG,
/// this does not modify the specified node, instead it returns the node that
/// already exists. If the resultant node does not exist in the DAG, the
/// input node is returned. As a degenerate case, if you specify the same
/// input operands as the node already has, the input node is returned.
SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
// Check to see if there is no change.
if (Op == N->getOperand(0)) return N;
// See if the modified node already exists.
void *InsertPos = nullptr;
if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
return Existing;
// Nope it doesn't. Remove the node from its current place in the maps.
if (InsertPos)
if (!RemoveNodeFromCSEMaps(N))
InsertPos = nullptr;
// Now we update the operands.
N->OperandList[0].set(Op);
updateDivergence(N);
// If this gets put into a CSE map, add it.
if (InsertPos) CSEMap.InsertNode(N, InsertPos);
return N;
}
SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
// Check to see if there is no change.
if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
return N; // No operands changed, just return the input node.
// See if the modified node already exists.
void *InsertPos = nullptr;
if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
return Existing;
// Nope it doesn't. Remove the node from its current place in the maps.
if (InsertPos)
if (!RemoveNodeFromCSEMaps(N))
InsertPos = nullptr;
// Now we update the operands.
if (N->OperandList[0] != Op1)
N->OperandList[0].set(Op1);
if (N->OperandList[1] != Op2)
N->OperandList[1].set(Op2);
updateDivergence(N);
// If this gets put into a CSE map, add it.
if (InsertPos) CSEMap.InsertNode(N, InsertPos);
return N;
}
SDNode *SelectionDAG::
UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
SDValue Ops[] = { Op1, Op2, Op3 };
return UpdateNodeOperands(N, Ops);
}
SDNode *SelectionDAG::
UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
SDValue Op3, SDValue Op4) {
SDValue Ops[] = { Op1, Op2, Op3, Op4 };
return UpdateNodeOperands(N, Ops);
}
SDNode *SelectionDAG::
UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
SDValue Op3, SDValue Op4, SDValue Op5) {
SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
return UpdateNodeOperands(N, Ops);
}
SDNode *SelectionDAG::
UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
unsigned NumOps = Ops.size();
assert(N->getNumOperands() == NumOps &&
"Update with wrong number of operands");
// If no operands changed just return the input node.
if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
return N;
// See if the modified node already exists.
void *InsertPos = nullptr;
if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
return Existing;
// Nope it doesn't. Remove the node from its current place in the maps.
if (InsertPos)
if (!RemoveNodeFromCSEMaps(N))
InsertPos = nullptr;
// Now we update the operands.
for (unsigned i = 0; i != NumOps; ++i)
if (N->OperandList[i] != Ops[i])
N->OperandList[i].set(Ops[i]);
updateDivergence(N);
// If this gets put into a CSE map, add it.
if (InsertPos) CSEMap.InsertNode(N, InsertPos);
return N;
}
/// DropOperands - Release the operands and set this node to have
/// zero operands.
void SDNode::DropOperands() {
// Unlike the code in MorphNodeTo that does this, we don't need to
// watch for dead nodes here.
for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
SDUse &Use = *I++;
Use.set(SDValue());
}
}
void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
ArrayRef<MachineMemOperand *> NewMemRefs) {
if (NewMemRefs.empty()) {
N->clearMemRefs();
return;
}
// Check if we can avoid allocating by storing a single reference directly.
if (NewMemRefs.size() == 1) {
N->MemRefs = NewMemRefs[0];
N->NumMemRefs = 1;
return;
}
MachineMemOperand **MemRefsBuffer =
Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
llvm::copy(NewMemRefs, MemRefsBuffer);
N->MemRefs = MemRefsBuffer;
N->NumMemRefs = static_cast<int>(NewMemRefs.size());
}
/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
/// machine opcode.
///
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT) {
SDVTList VTs = getVTList(VT);
return SelectNodeTo(N, MachineOpc, VTs, None);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT, SDValue Op1) {
SDVTList VTs = getVTList(VT);
SDValue Ops[] = { Op1 };
return SelectNodeTo(N, MachineOpc, VTs, Ops);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT, SDValue Op1,
SDValue Op2) {
SDVTList VTs = getVTList(VT);
SDValue Ops[] = { Op1, Op2 };
return SelectNodeTo(N, MachineOpc, VTs, Ops);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT, SDValue Op1,
SDValue Op2, SDValue Op3) {
SDVTList VTs = getVTList(VT);
SDValue Ops[] = { Op1, Op2, Op3 };
return SelectNodeTo(N, MachineOpc, VTs, Ops);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT, ArrayRef<SDValue> Ops) {
SDVTList VTs = getVTList(VT);
return SelectNodeTo(N, MachineOpc, VTs, Ops);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
SDVTList VTs = getVTList(VT1, VT2);
return SelectNodeTo(N, MachineOpc, VTs, Ops);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT1, EVT VT2) {
SDVTList VTs = getVTList(VT1, VT2);
return SelectNodeTo(N, MachineOpc, VTs, None);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT1, EVT VT2, EVT VT3,
ArrayRef<SDValue> Ops) {
SDVTList VTs = getVTList(VT1, VT2, VT3);
return SelectNodeTo(N, MachineOpc, VTs, Ops);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
EVT VT1, EVT VT2,
SDValue Op1, SDValue Op2) {
SDVTList VTs = getVTList(VT1, VT2);
SDValue Ops[] = { Op1, Op2 };
return SelectNodeTo(N, MachineOpc, VTs, Ops);
}
SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
SDVTList VTs,ArrayRef<SDValue> Ops) {
SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
// Reset the NodeID to -1.
New->setNodeId(-1);
if (New != N) {
ReplaceAllUsesWith(N, New);
RemoveDeadNode(N);
}
return New;
}
/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
/// the line number information on the merged node since it is not possible to
/// preserve the information that operation is associated with multiple lines.
/// This will make the debugger working better at -O0, were there is a higher
/// probability having other instructions associated with that line.
///
/// For IROrder, we keep the smaller of the two
SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
DebugLoc NLoc = N->getDebugLoc();
if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
N->setDebugLoc(DebugLoc());
}
unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
N->setIROrder(Order);
return N;
}
/// MorphNodeTo - This *mutates* the specified node to have the specified
/// return type, opcode, and operands.
///
/// Note that MorphNodeTo returns the resultant node. If there is already a
/// node of the specified opcode and operands, it returns that node instead of
/// the current one. Note that the SDLoc need not be the same.
///
/// Using MorphNodeTo is faster than creating a new node and swapping it in
/// with ReplaceAllUsesWith both because it often avoids allocating a new
/// node, and because it doesn't require CSE recalculation for any of
/// the node's users.
///
/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
/// As a consequence it isn't appropriate to use from within the DAG combiner or
/// the legalizer which maintain worklists that would need to be updated when
/// deleting things.
SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
SDVTList VTs, ArrayRef<SDValue> Ops) {
// If an identical node already exists, use it.
void *IP = nullptr;
if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opc, VTs, Ops);
if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
}
if (!RemoveNodeFromCSEMaps(N))
IP = nullptr;
// Start the morphing.
N->NodeType = Opc;
N->ValueList = VTs.VTs;
N->NumValues = VTs.NumVTs;
// Clear the operands list, updating used nodes to remove this from their
// use list. Keep track of any operands that become dead as a result.
SmallPtrSet<SDNode*, 16> DeadNodeSet;
for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
SDUse &Use = *I++;
SDNode *Used = Use.getNode();
Use.set(SDValue());
if (Used->use_empty())
DeadNodeSet.insert(Used);
}
// For MachineNode, initialize the memory references information.
if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
MN->clearMemRefs();
// Swap for an appropriately sized array from the recycler.
removeOperands(N);
createOperands(N, Ops);
// Delete any nodes that are still dead after adding the uses for the
// new operands.
if (!DeadNodeSet.empty()) {
SmallVector<SDNode *, 16> DeadNodes;
for (SDNode *N : DeadNodeSet)
if (N->use_empty())
DeadNodes.push_back(N);
RemoveDeadNodes(DeadNodes);
}
if (IP)
CSEMap.InsertNode(N, IP); // Memoize the new node.
return N;
}
SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
unsigned OrigOpc = Node->getOpcode();
unsigned NewOpc;
switch (OrigOpc) {
default:
llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
#include "llvm/IR/ConstrainedOps.def"
}
assert(Node->getNumValues() == 2 && "Unexpected number of results!");
// We're taking this node out of the chain, so we need to re-link things.
SDValue InputChain = Node->getOperand(0);
SDValue OutputChain = SDValue(Node, 1);
ReplaceAllUsesOfValueWith(OutputChain, InputChain);
SmallVector<SDValue, 3> Ops;
for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
Ops.push_back(Node->getOperand(i));
SDVTList VTs = getVTList(Node->getValueType(0));
SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
// MorphNodeTo can operate in two ways: if an existing node with the
// specified operands exists, it can just return it. Otherwise, it
// updates the node in place to have the requested operands.
if (Res == Node) {
// If we updated the node in place, reset the node ID. To the isel,
// this should be just like a newly allocated machine node.
Res->setNodeId(-1);
} else {
ReplaceAllUsesWith(Node, Res);
RemoveDeadNode(Node);
}
return Res;
}
/// getMachineNode - These are used for target selectors to create a new node
/// with specified return type(s), MachineInstr opcode, and operands.
///
/// Note that getMachineNode returns the resultant node. If there is already a
/// node of the specified opcode and operands, it returns that node instead of
/// the current one.
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT) {
SDVTList VTs = getVTList(VT);
return getMachineNode(Opcode, dl, VTs, None);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT, SDValue Op1) {
SDVTList VTs = getVTList(VT);
SDValue Ops[] = { Op1 };
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT, SDValue Op1, SDValue Op2) {
SDVTList VTs = getVTList(VT);
SDValue Ops[] = { Op1, Op2 };
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT, SDValue Op1, SDValue Op2,
SDValue Op3) {
SDVTList VTs = getVTList(VT);
SDValue Ops[] = { Op1, Op2, Op3 };
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT, ArrayRef<SDValue> Ops) {
SDVTList VTs = getVTList(VT);
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT1, EVT VT2, SDValue Op1,
SDValue Op2) {
SDVTList VTs = getVTList(VT1, VT2);
SDValue Ops[] = { Op1, Op2 };
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT1, EVT VT2, SDValue Op1,
SDValue Op2, SDValue Op3) {
SDVTList VTs = getVTList(VT1, VT2);
SDValue Ops[] = { Op1, Op2, Op3 };
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT1, EVT VT2,
ArrayRef<SDValue> Ops) {
SDVTList VTs = getVTList(VT1, VT2);
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT1, EVT VT2, EVT VT3,
SDValue Op1, SDValue Op2) {
SDVTList VTs = getVTList(VT1, VT2, VT3);
SDValue Ops[] = { Op1, Op2 };
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT1, EVT VT2, EVT VT3,
SDValue Op1, SDValue Op2,
SDValue Op3) {
SDVTList VTs = getVTList(VT1, VT2, VT3);
SDValue Ops[] = { Op1, Op2, Op3 };
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
EVT VT1, EVT VT2, EVT VT3,
ArrayRef<SDValue> Ops) {
SDVTList VTs = getVTList(VT1, VT2, VT3);
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
ArrayRef<EVT> ResultTys,
ArrayRef<SDValue> Ops) {
SDVTList VTs = getVTList(ResultTys);
return getMachineNode(Opcode, dl, VTs, Ops);
}
MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
SDVTList VTs,
ArrayRef<SDValue> Ops) {
bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
MachineSDNode *N;
void *IP = nullptr;
if (DoCSE) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, ~Opcode, VTs, Ops);
IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
}
}
// Allocate a new MachineSDNode.
N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
createOperands(N, Ops);
if (DoCSE)
CSEMap.InsertNode(N, IP);
InsertNode(N);
NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
return N;
}
/// getTargetExtractSubreg - A convenience function for creating
/// TargetOpcode::EXTRACT_SUBREG nodes.
SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
SDValue Operand) {
SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
VT, Operand, SRIdxVal);
return SDValue(Subreg, 0);
}
/// getTargetInsertSubreg - A convenience function for creating
/// TargetOpcode::INSERT_SUBREG nodes.
SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
SDValue Operand, SDValue Subreg) {
SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
VT, Operand, Subreg, SRIdxVal);
return SDValue(Result, 0);
}
/// getNodeIfExists - Get the specified node if it's already available, or
/// else return NULL.
SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
ArrayRef<SDValue> Ops,
const SDNodeFlags Flags) {
if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
FoldingSetNodeID ID;
AddNodeIDNode(ID, Opcode, VTList, Ops);
void *IP = nullptr;
if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
E->intersectFlagsWith(Flags);
return E;
}
}
return nullptr;
}
/// getDbgValue - Creates a SDDbgValue node.
///
/// SDNode
SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
SDNode *N, unsigned R, bool IsIndirect,
const DebugLoc &DL, unsigned O) {
assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
return new (DbgInfo->getAlloc())
SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
}
/// Constant
SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
DIExpression *Expr,
const Value *C,
const DebugLoc &DL, unsigned O) {
assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
}
/// FrameIndex
SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
DIExpression *Expr, unsigned FI,
bool IsIndirect,
const DebugLoc &DL,
unsigned O) {
assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
return new (DbgInfo->getAlloc())
SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
}
/// VReg
SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
DIExpression *Expr,
unsigned VReg, bool IsIndirect,
const DebugLoc &DL, unsigned O) {
assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
return new (DbgInfo->getAlloc())
SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
}
void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
unsigned OffsetInBits, unsigned SizeInBits,
bool InvalidateDbg) {
SDNode *FromNode = From.getNode();
SDNode *ToNode = To.getNode();
assert(FromNode && ToNode && "Can't modify dbg values");
// PR35338
// TODO: assert(From != To && "Redundant dbg value transfer");
// TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
if (From == To || FromNode == ToNode)
return;
if (!FromNode->getHasDebugValue())
return;
SmallVector<SDDbgValue *, 2> ClonedDVs;
for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
continue;
// TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
// Just transfer the dbg value attached to From.
if (Dbg->getResNo() != From.getResNo())
continue;
DIVariable *Var = Dbg->getVariable();
auto *Expr = Dbg->getExpression();
// If a fragment is requested, update the expression.
if (SizeInBits) {
// When splitting a larger (e.g., sign-extended) value whose
// lower bits are described with an SDDbgValue, do not attempt
// to transfer the SDDbgValue to the upper bits.
if (auto FI = Expr->getFragmentInfo())
if (OffsetInBits + SizeInBits > FI->SizeInBits)
continue;
auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
SizeInBits);
if (!Fragment)
continue;
Expr = *Fragment;
}
// Clone the SDDbgValue and move it to To.
SDDbgValue *Clone = getDbgValue(
Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), Dbg->getDebugLoc(),
std::max(ToNode->getIROrder(), Dbg->getOrder()));
ClonedDVs.push_back(Clone);
if (InvalidateDbg) {
// Invalidate value and indicate the SDDbgValue should not be emitted.
Dbg->setIsInvalidated();
Dbg->setIsEmitted();
}
}
for (SDDbgValue *Dbg : ClonedDVs)
AddDbgValue(Dbg, ToNode, false);
}
void SelectionDAG::salvageDebugInfo(SDNode &N) {
if (!N.getHasDebugValue())
return;
SmallVector<SDDbgValue *, 2> ClonedDVs;
for (auto DV : GetDbgValues(&N)) {
if (DV->isInvalidated())
continue;
switch (N.getOpcode()) {
default:
break;
case ISD::ADD:
SDValue N0 = N.getOperand(0);
SDValue N1 = N.getOperand(1);
if (!isConstantIntBuildVectorOrConstantInt(N0) &&
isConstantIntBuildVectorOrConstantInt(N1)) {
uint64_t Offset = N.getConstantOperandVal(1);
// Rewrite an ADD constant node into a DIExpression. Since we are
// performing arithmetic to compute the variable's *value* in the
// DIExpression, we need to mark the expression with a
// DW_OP_stack_value.
auto *DIExpr = DV->getExpression();
DIExpr =
DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset);
SDDbgValue *Clone =
getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
ClonedDVs.push_back(Clone);
DV->setIsInvalidated();
DV->setIsEmitted();
LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
N0.getNode()->dumprFull(this);
dbgs() << " into " << *DIExpr << '\n');
}
}
}
for (SDDbgValue *Dbg : ClonedDVs)
AddDbgValue(Dbg, Dbg->getSDNode(), false);
}
/// Creates a SDDbgLabel node.
SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
const DebugLoc &DL, unsigned O) {
assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
}
namespace {
/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
/// pointed to by a use iterator is deleted, increment the use iterator
/// so that it doesn't dangle.
///
class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
SDNode::use_iterator &UI;
SDNode::use_iterator &UE;
void NodeDeleted(SDNode *N, SDNode *E) override {
// Increment the iterator as needed.
while (UI != UE && N == *UI)
++UI;
}
public:
RAUWUpdateListener(SelectionDAG &d,
SDNode::use_iterator &ui,
SDNode::use_iterator &ue)
: SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
};
} // end anonymous namespace
/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
/// This can cause recursive merging of nodes in the DAG.
///
/// This version assumes From has a single result value.
///
void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
SDNode *From = FromN.getNode();
assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
"Cannot replace with this method!");
assert(From != To.getNode() && "Cannot replace uses of with self");
// Preserve Debug Values
transferDbgValues(FromN, To);
// Iterate over all the existing uses of From. New uses will be added
// to the beginning of the use list, which we avoid visiting.
// This specifically avoids visiting uses of From that arise while the
// replacement is happening, because any such uses would be the result
// of CSE: If an existing node looks like From after one of its operands
// is replaced by To, we don't want to replace of all its users with To
// too. See PR3018 for more info.
SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
RAUWUpdateListener Listener(*this, UI, UE);
while (UI != UE) {
SDNode *User = *UI;
// This node is about to morph, remove its old self from the CSE maps.
RemoveNodeFromCSEMaps(User);
// A user can appear in a use list multiple times, and when this
// happens the uses are usually next to each other in the list.
// To help reduce the number of CSE recomputations, process all
// the uses of this user that we can find this way.
do {
SDUse &Use = UI.getUse();
++UI;
Use.set(To);
if (To->isDivergent() != From->isDivergent())
updateDivergence(User);
} while (UI != UE && *UI == User);
// Now that we have modified User, add it back to the CSE maps. If it
// already exists there, recursively merge the results together.
AddModifiedNodeToCSEMaps(User);
}
// If we just RAUW'd the root, take note.
if (FromN == getRoot())
setRoot(To);
}
/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
/// This can cause recursive merging of nodes in the DAG.
///
/// This version assumes that for each value of From, there is a
/// corresponding value in To in the same position with the same type.
///
void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
#ifndef NDEBUG
for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
assert((!From->hasAnyUseOfValue(i) ||
From->getValueType(i) == To->getValueType(i)) &&
"Cannot use this version of ReplaceAllUsesWith!");
#endif
// Handle the trivial case.
if (From == To)
return;
// Preserve Debug Info. Only do this if there's a use.
for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
if (From->hasAnyUseOfValue(i)) {
assert((i < To->getNumValues()) && "Invalid To location");
transferDbgValues(SDValue(From, i), SDValue(To, i));
}
// Iterate over just the existing users of From. See the comments in
// the ReplaceAllUsesWith above.
SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
RAUWUpdateListener Listener(*this, UI, UE);
while (UI != UE) {
SDNode *User = *UI;
// This node is about to morph, remove its old self from the CSE maps.
RemoveNodeFromCSEMaps(User);
// A user can appear in a use list multiple times, and when this
// happens the uses are usually next to each other in the list.
// To help reduce the number of CSE recomputations, process all
// the uses of this user that we can find this way.
do {
SDUse &Use = UI.getUse();
++UI;
Use.setNode(To);
if (To->isDivergent() != From->isDivergent())
updateDivergence(User);
} while (UI != UE && *UI == User);
// Now that we have modified User, add it back to the CSE maps. If it
// already exists there, recursively merge the results together.
AddModifiedNodeToCSEMaps(User);
}
// If we just RAUW'd the root, take note.
if (From == getRoot().getNode())
setRoot(SDValue(To, getRoot().getResNo()));
}
/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
/// This can cause recursive merging of nodes in the DAG.
///
/// This version can replace From with any result values. To must match the
/// number and types of values returned by From.
void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
if (From->getNumValues() == 1) // Handle the simple case efficiently.
return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
// Preserve Debug Info.
for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
transferDbgValues(SDValue(From, i), To[i]);
// Iterate over just the existing users of From. See the comments in
// the ReplaceAllUsesWith above.
SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
RAUWUpdateListener Listener(*this, UI, UE);
while (UI != UE) {
SDNode *User = *UI;
// This node is about to morph, remove its old self from the CSE maps.
RemoveNodeFromCSEMaps(User);
// A user can appear in a use list multiple times, and when this happens the
// uses are usually next to each other in the list. To help reduce the
// number of CSE and divergence recomputations, process all the uses of this
// user that we can find this way.
bool To_IsDivergent = false;
do {
SDUse &Use = UI.getUse();
const SDValue &ToOp = To[Use.getResNo()];
++UI;
Use.set(ToOp);
To_IsDivergent |= ToOp->isDivergent();
} while (UI != UE && *UI == User);
if (To_IsDivergent != From->isDivergent())
updateDivergence(User);
// Now that we have modified User, add it back to the CSE maps. If it
// already exists there, recursively merge the results together.
AddModifiedNodeToCSEMaps(User);
}
// If we just RAUW'd the root, take note.
if (From == getRoot().getNode())
setRoot(SDValue(To[getRoot().getResNo()]));
}
/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
/// uses of other values produced by From.getNode() alone. The Deleted
/// vector is handled the same way as for ReplaceAllUsesWith.
void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
// Handle the really simple, really trivial case efficiently.
if (From == To) return;
// Handle the simple, trivial, case efficiently.
if (From.getNode()->getNumValues() == 1) {
ReplaceAllUsesWith(From, To);
return;
}
// Preserve Debug Info.
transferDbgValues(From, To);
// Iterate over just the existing users of From. See the comments in
// the ReplaceAllUsesWith above.
SDNode::use_iterator UI = From.getNode()->use_begin(),
UE = From.getNode()->use_end();
RAUWUpdateListener Listener(*this, UI, UE);
while (UI != UE) {
SDNode *User = *UI;
bool UserRemovedFromCSEMaps = false;
// A user can appear in a use list multiple times, and when this
// happens the uses are usually next to each other in the list.
// To help reduce the number of CSE recomputations, process all
// the uses of this user that we can find this way.
do {
SDUse &Use = UI.getUse();
// Skip uses of different values from the same node.
if (Use.getResNo() != From.getResNo()) {
++UI;
continue;
}
// If this node hasn't been modified yet, it's still in the CSE maps,
// so remove its old self from the CSE maps.
if (!UserRemovedFromCSEMaps) {
RemoveNodeFromCSEMaps(User);
UserRemovedFromCSEMaps = true;
}
++UI;
Use.set(To);
if (To->isDivergent() != From->isDivergent())
updateDivergence(User);
} while (UI != UE && *UI == User);
// We are iterating over all uses of the From node, so if a use
// doesn't use the specific value, no changes are made.
if (!UserRemovedFromCSEMaps)
continue;
// Now that we have modified User, add it back to the CSE maps. If it
// already exists there, recursively merge the results together.
AddModifiedNodeToCSEMaps(User);
}
// If we just RAUW'd the root, take note.
if (From == getRoot())
setRoot(To);
}
namespace {
/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
/// to record information about a use.
struct UseMemo {
SDNode *User;
unsigned Index;
SDUse *Use;
};
/// operator< - Sort Memos by User.
bool operator<(const UseMemo &L, const UseMemo &R) {
return (intptr_t)L.User < (intptr_t)R.User;
}
} // end anonymous namespace
void SelectionDAG::updateDivergence(SDNode * N)
{
if (TLI->isSDNodeAlwaysUniform(N))
return;
bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
for (auto &Op : N->ops()) {
if (Op.Val.getValueType() != MVT::Other)
IsDivergent |= Op.getNode()->isDivergent();
}
if (N->SDNodeBits.IsDivergent != IsDivergent) {
N->SDNodeBits.IsDivergent = IsDivergent;
for (auto U : N->uses()) {
updateDivergence(U);
}
}
}
void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
DenseMap<SDNode *, unsigned> Degree;
Order.reserve(AllNodes.size());
for (auto &N : allnodes()) {
unsigned NOps = N.getNumOperands();
Degree[&N] = NOps;
if (0 == NOps)
Order.push_back(&N);
}
for (size_t I = 0; I != Order.size(); ++I) {
SDNode *N = Order[I];
for (auto U : N->uses()) {
unsigned &UnsortedOps = Degree[U];
if (0 == --UnsortedOps)
Order.push_back(U);
}
}
}
#ifndef NDEBUG
void SelectionDAG::VerifyDAGDiverence() {
std::vector<SDNode *> TopoOrder;
CreateTopologicalOrder(TopoOrder);
const TargetLowering &TLI = getTargetLoweringInfo();
DenseMap<const SDNode *, bool> DivergenceMap;
for (auto &N : allnodes()) {
DivergenceMap[&N] = false;
}
for (auto N : TopoOrder) {
bool IsDivergent = DivergenceMap[N];
bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
for (auto &Op : N->ops()) {
if (Op.Val.getValueType() != MVT::Other)
IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
}
if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
DivergenceMap[N] = true;
}
}
for (auto &N : allnodes()) {
(void)N;
assert(DivergenceMap[&N] == N.isDivergent() &&
"Divergence bit inconsistency detected\n");
}
}
#endif
/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
/// uses of other values produced by From.getNode() alone. The same value
/// may appear in both the From and To list. The Deleted vector is
/// handled the same way as for ReplaceAllUsesWith.
void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
const SDValue *To,
unsigned Num){
// Handle the simple, trivial case efficiently.
if (Num == 1)
return ReplaceAllUsesOfValueWith(*From, *To);
transferDbgValues(*From, *To);
// Read up all the uses and make records of them. This helps
// processing new uses that are introduced during the
// replacement process.
SmallVector<UseMemo, 4> Uses;
for (unsigned i = 0; i != Num; ++i) {
unsigned FromResNo = From[i].getResNo();
SDNode *FromNode = From[i].getNode();
for (SDNode::use_iterator UI = FromNode->use_begin(),
E = FromNode->use_end(); UI != E; ++UI) {
SDUse &Use = UI.getUse();
if (Use.getResNo() == FromResNo) {
UseMemo Memo = { *UI, i, &Use };
Uses.push_back(Memo);
}
}
}
// Sort the uses, so that all the uses from a given User are together.
llvm::sort(Uses);
for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
UseIndex != UseIndexEnd; ) {
// We know that this user uses some value of From. If it is the right
// value, update it.
SDNode *User = Uses[UseIndex].User;
// This node is about to morph, remove its old self from the CSE maps.
RemoveNodeFromCSEMaps(User);
// The Uses array is sorted, so all the uses for a given User
// are next to each other in the list.
// To help reduce the number of CSE recomputations, process all
// the uses of this user that we can find this way.
do {
unsigned i = Uses[UseIndex].Index;
SDUse &Use = *Uses[UseIndex].Use;
++UseIndex;
Use.set(To[i]);
} while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
// Now that we have modified User, add it back to the CSE maps. If it
// already exists there, recursively merge the results together.
AddModifiedNodeToCSEMaps(User);
}
}
/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
/// based on their topological order. It returns the maximum id and a vector
/// of the SDNodes* in assigned order by reference.
unsigned SelectionDAG::AssignTopologicalOrder() {
unsigned DAGSize = 0;
// SortedPos tracks the progress of the algorithm. Nodes before it are
// sorted, nodes after it are unsorted. When the algorithm completes
// it is at the end of the list.
allnodes_iterator SortedPos = allnodes_begin();
// Visit all the nodes. Move nodes with no operands to the front of
// the list immediately. Annotate nodes that do have operands with their
// operand count. Before we do this, the Node Id fields of the nodes
// may contain arbitrary values. After, the Node Id fields for nodes
// before SortedPos will contain the topological sort index, and the
// Node Id fields for nodes At SortedPos and after will contain the
// count of outstanding operands.
for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
SDNode *N = &*I++;
checkForCycles(N, this);
unsigned Degree = N->getNumOperands();
if (Degree == 0) {
// A node with no uses, add it to the result array immediately.
N->setNodeId(DAGSize++);
allnodes_iterator Q(N);
if (Q != SortedPos)
SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
assert(SortedPos != AllNodes.end() && "Overran node list");
++SortedPos;
} else {
// Temporarily use the Node Id as scratch space for the degree count.
N->setNodeId(Degree);
}
}
// Visit all the nodes. As we iterate, move nodes into sorted order,
// such that by the time the end is reached all nodes will be sorted.
for (SDNode &Node : allnodes()) {
SDNode *N = &Node;
checkForCycles(N, this);
// N is in sorted position, so all its uses have one less operand
// that needs to be sorted.
for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
UI != UE; ++UI) {
SDNode *P = *UI;
unsigned Degree = P->getNodeId();
assert(Degree != 0 && "Invalid node degree");
--Degree;
if (Degree == 0) {
// All of P's operands are sorted, so P may sorted now.
P->setNodeId(DAGSize++);
if (P->getIterator() != SortedPos)
SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
assert(SortedPos != AllNodes.end() && "Overran node list");
++SortedPos;
} else {
// Update P's outstanding operand count.
P->setNodeId(Degree);
}
}
if (Node.getIterator() == SortedPos) {
#ifndef NDEBUG
allnodes_iterator I(N);
SDNode *S = &*++I;
dbgs() << "Overran sorted position:\n";
S->dumprFull(this); dbgs() << "\n";
dbgs() << "Checking if this is due to cycles\n";
checkForCycles(this, true);
#endif
llvm_unreachable(nullptr);
}
}
assert(SortedPos == AllNodes.end() &&
"Topological sort incomplete!");
assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
"First node in topological sort is not the entry token!");
assert(AllNodes.front().getNodeId() == 0 &&
"First node in topological sort has non-zero id!");
assert(AllNodes.front().getNumOperands() == 0 &&
"First node in topological sort has operands!");
assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
"Last node in topologic sort has unexpected id!");
assert(AllNodes.back().use_empty() &&
"Last node in topologic sort has users!");
assert(DAGSize == allnodes_size() && "Node count mismatch!");
return DAGSize;
}
/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
/// value is produced by SD.
void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
if (SD) {
assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
SD->setHasDebugValue(true);
}
DbgInfo->add(DB, SD, isParameter);
}
void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
DbgInfo->add(DB);
}
SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
SDValue NewMemOp) {
assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
// The new memory operation must have the same position as the old load in
// terms of memory dependency. Create a TokenFactor for the old load and new
// memory operation and update uses of the old load's output chain to use that
// TokenFactor.
SDValue OldChain = SDValue(OldLoad, 1);
SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
if (OldChain == NewChain || !OldLoad->hasAnyUseOfValue(1))
return NewChain;
SDValue TokenFactor =
getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
return TokenFactor;
}
SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
Function **OutFunction) {
assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
auto *Module = MF->getFunction().getParent();
auto *Function = Module->getFunction(Symbol);
if (OutFunction != nullptr)
*OutFunction = Function;
if (Function != nullptr) {
auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
return getGlobalAddress(Function, SDLoc(Op), PtrTy);
}
std::string ErrorStr;
raw_string_ostream ErrorFormatter(ErrorStr);
ErrorFormatter << "Undefined external symbol ";
ErrorFormatter << '"' << Symbol << '"';
ErrorFormatter.flush();
report_fatal_error(ErrorStr);
}
//===----------------------------------------------------------------------===//
// SDNode Class
//===----------------------------------------------------------------------===//
bool llvm::isNullConstant(SDValue V) {
ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
return Const != nullptr && Const->isNullValue();
}
bool llvm::isNullFPConstant(SDValue V) {
ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
return Const != nullptr && Const->isZero() && !Const->isNegative();
}
bool llvm::isAllOnesConstant(SDValue V) {
ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
return Const != nullptr && Const->isAllOnesValue();
}
bool llvm::isOneConstant(SDValue V) {
ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
return Const != nullptr && Const->isOne();
}
SDValue llvm::peekThroughBitcasts(SDValue V) {
while (V.getOpcode() == ISD::BITCAST)
V = V.getOperand(0);
return V;
}
SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
V = V.getOperand(0);
return V;
}
SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
V = V.getOperand(0);
return V;
}
bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
if (V.getOpcode() != ISD::XOR)
return false;
V = peekThroughBitcasts(V.getOperand(1));
unsigned NumBits = V.getScalarValueSizeInBits();
ConstantSDNode *C =
isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
}
ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
bool AllowTruncation) {
if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
return CN;
if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
BitVector UndefElements;
ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
// BuildVectors can truncate their operands. Ignore that case here unless
// AllowTruncation is set.
if (CN && (UndefElements.none() || AllowUndefs)) {
EVT CVT = CN->getValueType(0);
EVT NSVT = N.getValueType().getScalarType();
assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
if (AllowTruncation || (CVT == NSVT))
return CN;
}
}
return nullptr;
}
ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
bool AllowUndefs,
bool AllowTruncation) {
if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
return CN;
if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
BitVector UndefElements;
ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
// BuildVectors can truncate their operands. Ignore that case here unless
// AllowTruncation is set.
if (CN && (UndefElements.none() || AllowUndefs)) {
EVT CVT = CN->getValueType(0);
EVT NSVT = N.getValueType().getScalarType();
assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
if (AllowTruncation || (CVT == NSVT))
return CN;
}
}
return nullptr;
}
ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
return CN;
if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
BitVector UndefElements;
ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
if (CN && (UndefElements.none() || AllowUndefs))
return CN;
}
if (N.getOpcode() == ISD::SPLAT_VECTOR)
if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
return CN;
return nullptr;
}
ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
const APInt &DemandedElts,
bool AllowUndefs) {
if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
return CN;
if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
BitVector UndefElements;
ConstantFPSDNode *CN =
BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
if (CN && (UndefElements.none() || AllowUndefs))
return CN;
}
return nullptr;
}
bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
// TODO: may want to use peekThroughBitcast() here.
ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
return C && C->isNullValue();
}
bool llvm::isOneOrOneSplat(SDValue N) {
// TODO: may want to use peekThroughBitcast() here.
unsigned BitWidth = N.getScalarValueSizeInBits();
ConstantSDNode *C = isConstOrConstSplat(N);
return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
}
bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
N = peekThroughBitcasts(N);
unsigned BitWidth = N.getScalarValueSizeInBits();
ConstantSDNode *C = isConstOrConstSplat(N);
return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
}
HandleSDNode::~HandleSDNode() {
DropOperands();
}
GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
const DebugLoc &DL,
const GlobalValue *GA, EVT VT,
int64_t o, unsigned TF)
: SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
TheGlobal = GA;
}
AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
EVT VT, unsigned SrcAS,
unsigned DestAS)
: SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
: SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
MemSDNodeBits.IsVolatile = MMO->isVolatile();
MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
MemSDNodeBits.IsInvariant = MMO->isInvariant();
// We check here that the size of the memory operand fits within the size of
// the MMO. This is because the MMO might indicate only a possible address
// range instead of specifying the affected memory addresses precisely.
// TODO: Make MachineMemOperands aware of scalable vectors.
assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
"Size mismatch!");
}
/// Profile - Gather unique data for the node.
///
void SDNode::Profile(FoldingSetNodeID &ID) const {
AddNodeIDNode(ID, this);
}
namespace {
struct EVTArray {
std::vector<EVT> VTs;
EVTArray() {
VTs.reserve(MVT::LAST_VALUETYPE);
for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
VTs.push_back(MVT((MVT::SimpleValueType)i));
}
};
} // end anonymous namespace
static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
static ManagedStatic<EVTArray> SimpleVTArray;
static ManagedStatic<sys::SmartMutex<true>> VTMutex;
/// getValueTypeList - Return a pointer to the specified value type.
///
const EVT *SDNode::getValueTypeList(EVT VT) {
if (VT.isExtended()) {
sys::SmartScopedLock<true> Lock(*VTMutex);
return &(*EVTs->insert(VT).first);
} else {
assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
"Value type out of range!");
return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
}
}
/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
/// indicated value. This method ignores uses of other values defined by this
/// operation.
bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
assert(Value < getNumValues() && "Bad value!");
// TODO: Only iterate over uses of a given value of the node
for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
if (UI.getUse().getResNo() == Value) {
if (NUses == 0)
return false;
--NUses;
}
}
// Found exactly the right number of uses?
return NUses == 0;
}
/// hasAnyUseOfValue - Return true if there are any use of the indicated
/// value. This method ignores uses of other values defined by this operation.
bool SDNode::hasAnyUseOfValue(unsigned Value) const {
assert(Value < getNumValues() && "Bad value!");
for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
if (UI.getUse().getResNo() == Value)
return true;
return false;
}
/// isOnlyUserOf - Return true if this node is the only use of N.
bool SDNode::isOnlyUserOf(const SDNode *N) const {
bool Seen = false;
for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
SDNode *User = *I;
if (User == this)
Seen = true;
else
return false;
}
return Seen;
}
/// Return true if the only users of N are contained in Nodes.
bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
bool Seen = false;
for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
SDNode *User = *I;
if (llvm::any_of(Nodes,
[&User](const SDNode *Node) { return User == Node; }))
Seen = true;
else
return false;
}
return Seen;
}
/// isOperand - Return true if this node is an operand of N.
bool SDValue::isOperandOf(const SDNode *N) const {
return any_of(N->op_values(), [this](SDValue Op) { return *this == Op; });
}
bool SDNode::isOperandOf(const SDNode *N) const {
return any_of(N->op_values(),
[this](SDValue Op) { return this == Op.getNode(); });
}
/// reachesChainWithoutSideEffects - Return true if this operand (which must
/// be a chain) reaches the specified operand without crossing any
/// side-effecting instructions on any chain path. In practice, this looks
/// through token factors and non-volatile loads. In order to remain efficient,
/// this only looks a couple of nodes in, it does not do an exhaustive search.
///
/// Note that we only need to examine chains when we're searching for
/// side-effects; SelectionDAG requires that all side-effects are represented
/// by chains, even if another operand would force a specific ordering. This
/// constraint is necessary to allow transformations like splitting loads.
bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
unsigned Depth) const {
if (*this == Dest) return true;
// Don't search too deeply, we just want to be able to see through
// TokenFactor's etc.
if (Depth == 0) return false;
// If this is a token factor, all inputs to the TF happen in parallel.
if (getOpcode() == ISD::TokenFactor) {
// First, try a shallow search.
if (is_contained((*this)->ops(), Dest)) {
// We found the chain we want as an operand of this TokenFactor.
// Essentially, we reach the chain without side-effects if we could
// serialize the TokenFactor into a simple chain of operations with
// Dest as the last operation. This is automatically true if the
// chain has one use: there are no other ordering constraints.
// If the chain has more than one use, we give up: some other
// use of Dest might force a side-effect between Dest and the current
// node.
if (Dest.hasOneUse())
return true;
}
// Next, try a deep search: check whether every operand of the TokenFactor
// reaches Dest.
return llvm::all_of((*this)->ops(), [=](SDValue Op) {
return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
});
}
// Loads don't have side effects, look through them.
if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
if (Ld->isUnordered())
return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
}
return false;
}
bool SDNode::hasPredecessor(const SDNode *N) const {
SmallPtrSet<const SDNode *, 32> Visited;
SmallVector<const SDNode *, 16> Worklist;
Worklist.push_back(this);
return hasPredecessorHelper(N, Visited, Worklist);
}
void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
this->Flags.intersectWith(Flags);
}
SDValue
SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
ArrayRef<ISD::NodeType> CandidateBinOps,
bool AllowPartials) {
// The pattern must end in an extract from index 0.
if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
!isNullConstant(Extract->getOperand(1)))
return SDValue();
// Match against one of the candidate binary ops.
SDValue Op = Extract->getOperand(0);
if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
return Op.getOpcode() == unsigned(BinOp);
}))
return SDValue();
// Floating-point reductions may require relaxed constraints on the final step
// of the reduction because they may reorder intermediate operations.
unsigned CandidateBinOp = Op.getOpcode();
if (Op.getValueType().isFloatingPoint()) {
SDNodeFlags Flags = Op->getFlags();
switch (CandidateBinOp) {
case ISD::FADD:
if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
return SDValue();
break;
default:
llvm_unreachable("Unhandled FP opcode for binop reduction");
}
}
// Matching failed - attempt to see if we did enough stages that a partial
// reduction from a subvector is possible.
auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
if (!AllowPartials || !Op)
return SDValue();
EVT OpVT = Op.getValueType();
EVT OpSVT = OpVT.getScalarType();
EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
return SDValue();
BinOp = (ISD::NodeType)CandidateBinOp;
return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
getVectorIdxConstant(0, SDLoc(Op)));
};
// At each stage, we're looking for something that looks like:
// %s = shufflevector <8 x i32> %op, <8 x i32> undef,
// <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
// i32 undef, i32 undef, i32 undef, i32 undef>
// %a = binop <8 x i32> %op, %s
// Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
// we expect something like:
// <4,5,6,7,u,u,u,u>
// <2,3,u,u,u,u,u,u>
// <1,u,u,u,u,u,u,u>
// While a partial reduction match would be:
// <2,3,u,u,u,u,u,u>
// <1,u,u,u,u,u,u,u>
unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
SDValue PrevOp;
for (unsigned i = 0; i < Stages; ++i) {
unsigned MaskEnd = (1 << i);
if (Op.getOpcode() != CandidateBinOp)
return PartialReduction(PrevOp, MaskEnd);
SDValue Op0 = Op.getOperand(0);
SDValue Op1 = Op.getOperand(1);
ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
if (Shuffle) {
Op = Op1;
} else {
Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
Op = Op0;
}
// The first operand of the shuffle should be the same as the other operand
// of the binop.
if (!Shuffle || Shuffle->getOperand(0) != Op)
return PartialReduction(PrevOp, MaskEnd);
// Verify the shuffle has the expected (at this stage of the pyramid) mask.
for (int Index = 0; Index < (int)MaskEnd; ++Index)
if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
return PartialReduction(PrevOp, MaskEnd);
PrevOp = Op;
}
// Handle subvector reductions, which tend to appear after the shuffle
// reduction stages.
while (Op.getOpcode() == CandidateBinOp) {
unsigned NumElts = Op.getValueType().getVectorNumElements();
SDValue Op0 = Op.getOperand(0);
SDValue Op1 = Op.getOperand(1);
if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
Op0.getOperand(0) != Op1.getOperand(0))
break;
SDValue Src = Op0.getOperand(0);
unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
if (NumSrcElts != (2 * NumElts))
break;
if (!(Op0.getConstantOperandAPInt(1) == 0 &&
Op1.getConstantOperandAPInt(1) == NumElts) &&
!(Op1.getConstantOperandAPInt(1) == 0 &&
Op0.getConstantOperandAPInt(1) == NumElts))
break;
Op = Src;
}
BinOp = (ISD::NodeType)CandidateBinOp;
return Op;
}
SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
assert(N->getNumValues() == 1 &&
"Can't unroll a vector with multiple results!");
EVT VT = N->getValueType(0);
unsigned NE = VT.getVectorNumElements();
EVT EltVT = VT.getVectorElementType();
SDLoc dl(N);
SmallVector<SDValue, 8> Scalars;
SmallVector<SDValue, 4> Operands(N->getNumOperands());
// If ResNE is 0, fully unroll the vector op.
if (ResNE == 0)
ResNE = NE;
else if (NE > ResNE)
NE = ResNE;
unsigned i;
for (i= 0; i != NE; ++i) {
for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
SDValue Operand = N->getOperand(j);
EVT OperandVT = Operand.getValueType();
if (OperandVT.isVector()) {
// A vector operand; extract a single element.
EVT OperandEltVT = OperandVT.getVectorElementType();
Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
Operand, getVectorIdxConstant(i, dl));
} else {
// A scalar operand; just use it as is.
Operands[j] = Operand;
}
}
switch (N->getOpcode()) {
default: {
Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
N->getFlags()));
break;
}
case ISD::VSELECT:
Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
break;
case ISD::SHL:
case ISD::SRA:
case ISD::SRL:
case ISD::ROTL:
case ISD::ROTR:
Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
getShiftAmountOperand(Operands[0].getValueType(),
Operands[1])));
break;
case ISD::SIGN_EXTEND_INREG: {
EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
Operands[0],
getValueType(ExtVT)));
}
}
}
for (; i < ResNE; ++i)
Scalars.push_back(getUNDEF(EltVT));
EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
return getBuildVector(VecVT, dl, Scalars);
}
std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
SDNode *N, unsigned ResNE) {
unsigned Opcode = N->getOpcode();
assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
"Expected an overflow opcode");
EVT ResVT = N->getValueType(0);
EVT OvVT = N->getValueType(1);
EVT ResEltVT = ResVT.getVectorElementType();
EVT OvEltVT = OvVT.getVectorElementType();
SDLoc dl(N);
// If ResNE is 0, fully unroll the vector op.
unsigned NE = ResVT.getVectorNumElements();
if (ResNE == 0)
ResNE = NE;
else if (NE > ResNE)
NE = ResNE;
SmallVector<SDValue, 8> LHSScalars;
SmallVector<SDValue, 8> RHSScalars;
ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
SDVTList VTs = getVTList(ResEltVT, SVT);
SmallVector<SDValue, 8> ResScalars;
SmallVector<SDValue, 8> OvScalars;
for (unsigned i = 0; i < NE; ++i) {
SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
SDValue Ov =
getSelect(dl, OvEltVT, Res.getValue(1),
getBoolConstant(true, dl, OvEltVT, ResVT),
getConstant(0, dl, OvEltVT));
ResScalars.push_back(Res);
OvScalars.push_back(Ov);
}
ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
getBuildVector(NewOvVT, dl, OvScalars));
}
bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
LoadSDNode *Base,
unsigned Bytes,
int Dist) const {
if (LD->isVolatile() || Base->isVolatile())
return false;
// TODO: probably too restrictive for atomics, revisit
if (!LD->isSimple())
return false;
if (LD->isIndexed() || Base->isIndexed())
return false;
if (LD->getChain() != Base->getChain())
return false;
EVT VT = LD->getValueType(0);
if (VT.getSizeInBits() / 8 != Bytes)
return false;
auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
auto LocDecomp = BaseIndexOffset::match(LD, *this);
int64_t Offset = 0;
if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
return (Dist * Bytes == Offset);
return false;
}
/// InferPtrAlignment - Infer alignment of a load / store address. Return None
/// if it cannot be inferred.
MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
// If this is a GlobalAddress + cst, return the alignment.
const GlobalValue *GV = nullptr;
int64_t GVOffset = 0;
if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
KnownBits Known(PtrWidth);
llvm::computeKnownBits(GV, Known, getDataLayout());
unsigned AlignBits = Known.countMinTrailingZeros();
if (AlignBits)
return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
}
// If this is a direct reference to a stack slot, use information about the
// stack slot's alignment.
int FrameIdx = INT_MIN;
int64_t FrameOffset = 0;
if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
FrameIdx = FI->getIndex();
} else if (isBaseWithConstantOffset(Ptr) &&
isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
// Handle FI+Cst
FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
FrameOffset = Ptr.getConstantOperandVal(1);
}
if (FrameIdx != INT_MIN) {
const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
}
return None;
}
/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
/// which is split (or expanded) into two not necessarily identical pieces.
std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
// Currently all types are split in half.
EVT LoVT, HiVT;
if (!VT.isVector())
LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
else
LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
return std::make_pair(LoVT, HiVT);
}
/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
/// type, dependent on an enveloping VT that has been split into two identical
/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
std::pair<EVT, EVT>
SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
bool *HiIsEmpty) const {
EVT EltTp = VT.getVectorElementType();
// Examples:
// custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
// custom VL=9 with enveloping VL=8/8 yields 8/1
// custom VL=10 with enveloping VL=8/8 yields 8/2
// etc.
ElementCount VTNumElts = VT.getVectorElementCount();
ElementCount EnvNumElts = EnvVT.getVectorElementCount();
assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
"Mixing fixed width and scalable vectors when enveloping a type");
EVT LoVT, HiVT;
if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
LoVT = EnvVT;
HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
*HiIsEmpty = false;
} else {
// Flag that hi type has zero storage size, but return split envelop type
// (this would be easier if vector types with zero elements were allowed).
LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
HiVT = EnvVT;
*HiIsEmpty = true;
}
return std::make_pair(LoVT, HiVT);
}
/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
/// low/high part.
std::pair<SDValue, SDValue>
SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
const EVT &HiVT) {
assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
"Splitting vector with an invalid mixture of fixed and scalable "
"vector types");
assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
N.getValueType().getVectorMinNumElements() &&
"More vector elements requested than available!");
SDValue Lo, Hi;
Lo =
getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
// For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
// (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
// IDX with the runtime scaling factor of the result vector type. For
// fixed-width result vectors, that runtime scaling factor is 1.
Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
return std::make_pair(Lo, Hi);
}
/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
EVT VT = N.getValueType();
EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
NextPowerOf2(VT.getVectorNumElements()));
return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
getVectorIdxConstant(0, DL));
}
void SelectionDAG::ExtractVectorElements(SDValue Op,
SmallVectorImpl<SDValue> &Args,
unsigned Start, unsigned Count,
EVT EltVT) {
EVT VT = Op.getValueType();
if (Count == 0)
Count = VT.getVectorNumElements();
if (EltVT == EVT())
EltVT = VT.getVectorElementType();
SDLoc SL(Op);
for (unsigned i = Start, e = Start + Count; i != e; ++i) {
Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
getVectorIdxConstant(i, SL)));
}
}
// getAddressSpace - Return the address space this GlobalAddress belongs to.
unsigned GlobalAddressSDNode::getAddressSpace() const {
return getGlobal()->getType()->getAddressSpace();
}
Type *ConstantPoolSDNode::getType() const {
if (isMachineConstantPoolEntry())
return Val.MachineCPVal->getType();
return Val.ConstVal->getType();
}
bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
unsigned &SplatBitSize,
bool &HasAnyUndefs,
unsigned MinSplatBits,
bool IsBigEndian) const {
EVT VT = getValueType(0);
assert(VT.isVector() && "Expected a vector type");
unsigned VecWidth = VT.getSizeInBits();
if (MinSplatBits > VecWidth)
return false;
// FIXME: The widths are based on this node's type, but build vectors can
// truncate their operands.
SplatValue = APInt(VecWidth, 0);
SplatUndef = APInt(VecWidth, 0);
// Get the bits. Bits with undefined values (when the corresponding element
// of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
// in SplatValue. If any of the values are not constant, give up and return
// false.
unsigned int NumOps = getNumOperands();
assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
unsigned EltWidth = VT.getScalarSizeInBits();
for (unsigned j = 0; j < NumOps; ++j) {
unsigned i = IsBigEndian ? NumOps - 1 - j : j;
SDValue OpVal = getOperand(i);
unsigned BitPos = j * EltWidth;
if (OpVal.isUndef())
SplatUndef.setBits(BitPos, BitPos + EltWidth);
else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
else
return false;
}
// The build_vector is all constants or undefs. Find the smallest element
// size that splats the vector.
HasAnyUndefs = (SplatUndef != 0);
// FIXME: This does not work for vectors with elements less than 8 bits.
while (VecWidth > 8) {
unsigned HalfSize = VecWidth / 2;
APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
APInt LowValue = SplatValue.trunc(HalfSize);
APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
APInt LowUndef = SplatUndef.trunc(HalfSize);
// If the two halves do not match (ignoring undef bits), stop here.
if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
MinSplatBits > HalfSize)
break;
SplatValue = HighValue | LowValue;
SplatUndef = HighUndef & LowUndef;
VecWidth = HalfSize;
}
SplatBitSize = VecWidth;
return true;
}
SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
BitVector *UndefElements) const {
if (UndefElements) {
UndefElements->clear();
UndefElements->resize(getNumOperands());
}
assert(getNumOperands() == DemandedElts.getBitWidth() &&
"Unexpected vector size");
if (!DemandedElts)
return SDValue();
SDValue Splatted;
for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
if (!DemandedElts[i])
continue;
SDValue Op = getOperand(i);
if (Op.isUndef()) {
if (UndefElements)
(*UndefElements)[i] = true;
} else if (!Splatted) {
Splatted = Op;
} else if (Splatted != Op) {
return SDValue();
}
}
if (!Splatted) {
unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
assert(getOperand(FirstDemandedIdx).isUndef() &&
"Can only have a splat without a constant for all undefs.");
return getOperand(FirstDemandedIdx);
}
return Splatted;
}
SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
return getSplatValue(DemandedElts, UndefElements);
}
ConstantSDNode *
BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
BitVector *UndefElements) const {
return dyn_cast_or_null<ConstantSDNode>(
getSplatValue(DemandedElts, UndefElements));
}
ConstantSDNode *
BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
}
ConstantFPSDNode *
BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
BitVector *UndefElements) const {
return dyn_cast_or_null<ConstantFPSDNode>(
getSplatValue(DemandedElts, UndefElements));
}
ConstantFPSDNode *
BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
}
int32_t
BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
uint32_t BitWidth) const {
if (ConstantFPSDNode *CN =
dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
bool IsExact;
APSInt IntVal(BitWidth);
const APFloat &APF = CN->getValueAPF();
if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
APFloat::opOK ||
!IsExact)
return -1;
return IntVal.exactLogBase2();
}
return -1;
}
bool BuildVectorSDNode::isConstant() const {
for (const SDValue &Op : op_values()) {
unsigned Opc = Op.getOpcode();
if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
return false;
}
return true;
}
bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
// Find the first non-undef value in the shuffle mask.
unsigned i, e;
for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
/* search */;
// If all elements are undefined, this shuffle can be considered a splat
// (although it should eventually get simplified away completely).
if (i == e)
return true;
// Make sure all remaining elements are either undef or the same as the first
// non-undef value.
for (int Idx = Mask[i]; i != e; ++i)
if (Mask[i] >= 0 && Mask[i] != Idx)
return false;
return true;
}
// Returns the SDNode if it is a constant integer BuildVector
// or constant integer.
SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
if (isa<ConstantSDNode>(N))
return N.getNode();
if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
return N.getNode();
// Treat a GlobalAddress supporting constant offset folding as a
// constant integer.
if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
if (GA->getOpcode() == ISD::GlobalAddress &&
TLI->isOffsetFoldingLegal(GA))
return GA;
if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
isa<ConstantSDNode>(N.getOperand(0)))
return N.getNode();
return nullptr;
}
SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
if (isa<ConstantFPSDNode>(N))
return N.getNode();
if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
return N.getNode();
return nullptr;
}
void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
assert(!Node->OperandList && "Node already has operands");
assert(SDNode::getMaxNumOperands() >= Vals.size() &&
"too many operands to fit into SDNode");
SDUse *Ops = OperandRecycler.allocate(
ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
bool IsDivergent = false;
for (unsigned I = 0; I != Vals.size(); ++I) {
Ops[I].setUser(Node);
Ops[I].setInitial(Vals[I]);
if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
}
Node->NumOperands = Vals.size();
Node->OperandList = Ops;
IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
if (!TLI->isSDNodeAlwaysUniform(Node))
Node->SDNodeBits.IsDivergent = IsDivergent;
checkForCycles(Node);
}
SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
SmallVectorImpl<SDValue> &Vals) {
size_t Limit = SDNode::getMaxNumOperands();
while (Vals.size() > Limit) {
unsigned SliceIdx = Vals.size() - Limit;
auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
Vals.erase(Vals.begin() + SliceIdx, Vals.end());
Vals.emplace_back(NewTF);
}
return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
}
#ifndef NDEBUG
static void checkForCyclesHelper(const SDNode *N,
SmallPtrSetImpl<const SDNode*> &Visited,
SmallPtrSetImpl<const SDNode*> &Checked,
const llvm::SelectionDAG *DAG) {
// If this node has already been checked, don't check it again.
if (Checked.count(N))
return;
// If a node has already been visited on this depth-first walk, reject it as
// a cycle.
if (!Visited.insert(N).second) {
errs() << "Detected cycle in SelectionDAG\n";
dbgs() << "Offending node:\n";
N->dumprFull(DAG); dbgs() << "\n";
abort();
}
for (const SDValue &Op : N->op_values())
checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
Checked.insert(N);
Visited.erase(N);
}
#endif
void llvm::checkForCycles(const llvm::SDNode *N,
const llvm::SelectionDAG *DAG,
bool force) {
#ifndef NDEBUG
bool check = force;
#ifdef EXPENSIVE_CHECKS
check = true;
#endif // EXPENSIVE_CHECKS
if (check) {
assert(N && "Checking nonexistent SDNode");
SmallPtrSet<const SDNode*, 32> visited;
SmallPtrSet<const SDNode*, 32> checked;
checkForCyclesHelper(N, visited, checked, DAG);
}
#endif // !NDEBUG
}
void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
checkForCycles(DAG->getRoot().getNode(), DAG, force);
}
|
#include <chainbase/chainbase.hpp>
#include <fc/filesystem.hpp>
#include <memory>
namespace iwillio { namespace testing {
/**
* Utility class to create and tear down a temporary chainbase::database using RAII
*
* @tparam MAX_SIZE - the maximum size of the chainbase::database
*/
template<uint64_t MAX_SIZE>
struct chainbase_fixture {
chainbase_fixture()
: _tempdir()
, _db(std::make_unique<chainbase::database>(_tempdir.path(), chainbase::database::read_write, MAX_SIZE))
{
}
~chainbase_fixture()
{
_db.reset();
_tempdir.remove();
}
fc::temp_directory _tempdir;
std::unique_ptr<chainbase::database> _db;
};
} } // iwillio::testing
|
// UNSUPPORTED: cuda
// REQUIRES: gpu,linux
// RUN: %clangxx -fsycl %s -DINLINE_ASM -o %t.out
// RUN: %t.out
// RUN: %clangxx -fsycl %s -o %t.ref.out
// RUN: %t.ref.out
#include "include/asmhelper.h"
#include <CL/sycl.hpp>
#include <iostream>
#include <vector>
using dataType = cl::sycl::cl_int;
template <typename T = dataType>
struct KernelFunctor : WithOutputBuffer<T> {
KernelFunctor(size_t problem_size) : WithOutputBuffer<T>(problem_size) {}
void operator()(cl::sycl::handler &cgh) {
auto C = this->getOutputBuffer().template get_access<cl::sycl::access::mode::write>(cgh);
cgh.parallel_for<KernelFunctor<T>>(
cl::sycl::range<1>{this->getOutputBufferSize()}, [=](cl::sycl::id<1> wiID) [[cl::intel_reqd_sub_group_size(8)]] {
volatile int local_var = 47;
local_var += C[0];
#if defined(INLINE_ASM) && defined(__SYCL_DEVICE_ONLY__)
asm volatile("{\n"
".decl temp v_type=G type=w num_elts=8 align=GRF\n"
"mov (M1,16) temp(0, 0)<1> %0(0,0)<1;1,0>\n"
"}\n" ::"rw"(local_var));
#else
volatile int temp = 0;
temp = local_var;
#endif
});
}
};
int main() {
KernelFunctor<> f(DEFAULT_PROBLEM_SIZE);
if (!launchInlineASMTest(f))
return 0;
if (verify_all_the_same(f.getOutputBufferData(), 0))
return 0;
return 1;
}
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
vector <ll> ans;
bool check(ll n)
{
for(ll i = 30; i >= 0; i--) {
ll val = (1LL << i) - 1;
if(val == n)
return 0;
}
return 1;
}
int main()
{
ll n;
cin >> n;
ll f = 0;
for(ll i = 30; i >= 0; i--) {
ll bt = (n >> i) & 1;
if(bt == 1) {
f = i;
break;
}
}
if(n % 2 == 0) {
ans.push_back(0);
n++;
}
while(check(n)) {
for(ll i = f; i >= 0; i--) {
ll bt = (n >> i) & 1;
if(bt == 0) {
ans.push_back(i + 1);
n ^= ( (1LL << (i + 1)) - 1);
n++;
break;
}
}
}
cout << (2 * ans.size() ) << endl;
for(ll i = 0; i < ans.size(); i++) {
if(i != 0)
printf(" ");
printf("%lld", ans[i]);
}
if(ans.size() != 0)
cout << endl;
return 0;
}
|
int main() {
auto A = A;
A.i;
return 0;
}
|
#include "ares-test.h"
// library initialization is only needed for windows builds
#ifdef WIN32
#define EXPECTED_NONINIT ARES_ENOTINITIALIZED
#else
#define EXPECTED_NONINIT ARES_SUCCESS
#endif
namespace ares {
namespace test {
TEST(LibraryInit, Basic) {
EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
ares_library_cleanup();
EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
}
TEST(LibraryInit, UnexpectedCleanup) {
EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
ares_library_cleanup();
EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
}
TEST(LibraryInit, DISABLED_InvalidParam) {
// TODO: police flags argument to ares_library_init()
EXPECT_EQ(ARES_EBADQUERY, ares_library_init(ARES_LIB_INIT_ALL << 2));
EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
ares_library_cleanup();
}
TEST(LibraryInit, Nested) {
EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
ares_library_cleanup();
EXPECT_EQ(ARES_SUCCESS, ares_library_initialized());
ares_library_cleanup();
EXPECT_EQ(EXPECTED_NONINIT, ares_library_initialized());
}
TEST(LibraryInit, BasicChannelInit) {
EXPECT_EQ(ARES_SUCCESS, ares_library_init(ARES_LIB_INIT_ALL));
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
EXPECT_NE(nullptr, channel);
ares_destroy(channel);
ares_library_cleanup();
}
TEST_F(LibraryTest, OptionsChannelInit) {
struct ares_options opts = {0};
int optmask = 0;
opts.flags = ARES_FLAG_USEVC | ARES_FLAG_PRIMARY;
optmask |= ARES_OPT_FLAGS;
opts.timeout = 2000;
optmask |= ARES_OPT_TIMEOUTMS;
opts.tries = 2;
optmask |= ARES_OPT_TRIES;
opts.ndots = 4;
optmask |= ARES_OPT_NDOTS;
opts.udp_port = 54;
optmask |= ARES_OPT_UDP_PORT;
opts.tcp_port = 54;
optmask |= ARES_OPT_TCP_PORT;
opts.socket_send_buffer_size = 514;
optmask |= ARES_OPT_SOCK_SNDBUF;
opts.socket_receive_buffer_size = 514;
optmask |= ARES_OPT_SOCK_RCVBUF;
opts.ednspsz = 1280;
optmask |= ARES_OPT_EDNSPSZ;
opts.nservers = 2;
opts.servers = (struct in_addr *)malloc(opts.nservers * sizeof(struct in_addr));
opts.servers[0].s_addr = htonl(0x01020304);
opts.servers[1].s_addr = htonl(0x02030405);
optmask |= ARES_OPT_SERVERS;
opts.ndomains = 2;
opts.domains = (char **)malloc(opts.ndomains * sizeof(char *));
opts.domains[0] = strdup("example.com");
opts.domains[1] = strdup("example2.com");
optmask |= ARES_OPT_DOMAINS;
opts.lookups = strdup("b");
optmask |= ARES_OPT_LOOKUPS;
optmask |= ARES_OPT_ROTATE;
opts.resolvconf_path = strdup("/etc/resolv.conf");
optmask |= ARES_OPT_RESOLVCONF;
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
EXPECT_NE(nullptr, channel);
ares_channel channel2 = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_dup(&channel2, channel));
struct ares_options opts2 = {0};
int optmask2 = 0;
EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel2, &opts2, &optmask2));
// Note that not all opts-settable fields are saved (e.g.
// ednspsz, socket_{send,receive}_buffer_size).
EXPECT_EQ(opts.flags, opts2.flags);
EXPECT_EQ(opts.timeout, opts2.timeout);
EXPECT_EQ(opts.tries, opts2.tries);
EXPECT_EQ(opts.ndots, opts2.ndots);
EXPECT_EQ(opts.udp_port, opts2.udp_port);
EXPECT_EQ(opts.tcp_port, opts2.tcp_port);
EXPECT_EQ(1, opts2.nservers); // Truncated by ARES_FLAG_PRIMARY
EXPECT_EQ(opts.servers[0].s_addr, opts2.servers[0].s_addr);
EXPECT_EQ(opts.ndomains, opts2.ndomains);
EXPECT_EQ(std::string(opts.domains[0]), std::string(opts2.domains[0]));
EXPECT_EQ(std::string(opts.domains[1]), std::string(opts2.domains[1]));
EXPECT_EQ(std::string(opts.lookups), std::string(opts2.lookups));
EXPECT_EQ(std::string(opts.resolvconf_path), std::string(opts2.resolvconf_path));
ares_destroy_options(&opts);
ares_destroy_options(&opts2);
ares_destroy(channel);
ares_destroy(channel2);
}
TEST_F(LibraryTest, ChannelAllocFail) {
ares_channel channel;
for (int ii = 1; ii <= 25; ii++) {
ClearFails();
SetAllocFail(ii);
channel = nullptr;
int rc = ares_init(&channel);
// The number of allocations depends on local environment, so don't expect ENOMEM.
if (rc == ARES_ENOMEM) {
EXPECT_EQ(nullptr, channel);
} else {
ares_destroy(channel);
}
}
}
TEST_F(LibraryTest, OptionsChannelAllocFail) {
struct ares_options opts = {0};
int optmask = 0;
opts.flags = ARES_FLAG_USEVC;
optmask |= ARES_OPT_FLAGS;
opts.timeout = 2;
optmask |= ARES_OPT_TIMEOUT;
opts.tries = 2;
optmask |= ARES_OPT_TRIES;
opts.ndots = 4;
optmask |= ARES_OPT_NDOTS;
opts.udp_port = 54;
optmask |= ARES_OPT_UDP_PORT;
opts.tcp_port = 54;
optmask |= ARES_OPT_TCP_PORT;
opts.socket_send_buffer_size = 514;
optmask |= ARES_OPT_SOCK_SNDBUF;
opts.socket_receive_buffer_size = 514;
optmask |= ARES_OPT_SOCK_RCVBUF;
opts.ednspsz = 1280;
optmask |= ARES_OPT_EDNSPSZ;
opts.nservers = 2;
opts.servers = (struct in_addr *)malloc(opts.nservers * sizeof(struct in_addr));
opts.servers[0].s_addr = htonl(0x01020304);
opts.servers[1].s_addr = htonl(0x02030405);
optmask |= ARES_OPT_SERVERS;
opts.ndomains = 2;
opts.domains = (char **)malloc(opts.ndomains * sizeof(char *));
opts.domains[0] = strdup("example.com");
opts.domains[1] = strdup("example2.com");
optmask |= ARES_OPT_DOMAINS;
opts.lookups = strdup("b");
optmask |= ARES_OPT_LOOKUPS;
optmask |= ARES_OPT_ROTATE;
opts.resolvconf_path = strdup("/etc/resolv.conf");
optmask |= ARES_OPT_RESOLVCONF;
ares_channel channel = nullptr;
for (int ii = 1; ii <= 8; ii++) {
ClearFails();
SetAllocFail(ii);
int rc = ares_init_options(&channel, &opts, optmask);
if (rc == ARES_ENOMEM) {
EXPECT_EQ(nullptr, channel);
} else {
EXPECT_EQ(ARES_SUCCESS, rc);
ares_destroy(channel);
channel = nullptr;
}
}
ClearFails();
EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
EXPECT_NE(nullptr, channel);
// Add some servers and a sortlist for flavour.
EXPECT_EQ(ARES_SUCCESS,
ares_set_servers_csv(channel, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel, "1.2.3.4 2.3.4.5"));
ares_channel channel2 = nullptr;
for (int ii = 1; ii <= 18; ii++) {
ClearFails();
SetAllocFail(ii);
EXPECT_EQ(ARES_ENOMEM, ares_dup(&channel2, channel)) << ii;
EXPECT_EQ(nullptr, channel2) << ii;
}
struct ares_options opts2;
int optmask2 = 0;
for (int ii = 1; ii <= 6; ii++) {
memset(&opts2, 0, sizeof(opts2));
ClearFails();
SetAllocFail(ii);
EXPECT_EQ(ARES_ENOMEM, ares_save_options(channel, &opts2, &optmask2)) << ii;
// May still have allocations even after ARES_ENOMEM return code.
ares_destroy_options(&opts2);
}
ares_destroy_options(&opts);
ares_destroy(channel);
}
TEST_F(LibraryTest, FailChannelInit) {
EXPECT_EQ(ARES_SUCCESS,
ares_library_init_mem(ARES_LIB_INIT_ALL,
&LibraryTest::amalloc,
&LibraryTest::afree,
&LibraryTest::arealloc));
SetAllocFail(1);
ares_channel channel = nullptr;
EXPECT_EQ(ARES_ENOMEM, ares_init(&channel));
EXPECT_EQ(nullptr, channel);
ares_library_cleanup();
}
#ifndef WIN32
TEST_F(LibraryTest, EnvInit) {
ares_channel channel = nullptr;
EnvValue v1("LOCALDOMAIN", "this.is.local");
EnvValue v2("RES_OPTIONS", "options debug ndots:3 retry:3 rotate retrans:2");
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
ares_destroy(channel);
}
TEST_F(LibraryTest, EnvInitAllocFail) {
ares_channel channel;
EnvValue v1("LOCALDOMAIN", "this.is.local");
EnvValue v2("RES_OPTIONS", "options debug ndots:3 retry:3 rotate retrans:2");
for (int ii = 1; ii <= 10; ii++) {
ClearFails();
SetAllocFail(ii);
channel = nullptr;
int rc = ares_init(&channel);
if (rc == ARES_SUCCESS) {
ares_destroy(channel);
} else {
EXPECT_EQ(ARES_ENOMEM, rc);
}
}
}
#endif
TEST_F(DefaultChannelTest, SetAddresses) {
ares_set_local_ip4(channel_, 0x01020304);
byte addr6[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
ares_set_local_ip6(channel_, addr6);
ares_set_local_dev(channel_, "dummy");
}
TEST_F(DefaultChannelTest, SetSortlistFailures) {
EXPECT_EQ(ARES_ENODATA, ares_set_sortlist(nullptr, "1.2.3.4"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; lwk"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "xyzzy ; 0x123"));
}
TEST_F(DefaultChannelTest, SetSortlistVariants) {
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "1.2.3.4"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "1.2.3.4 ; 2.3.4.5"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "129.1.1.1"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "192.1.1.1"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "224.1.1.1"));
EXPECT_EQ(ARES_SUCCESS, ares_set_sortlist(channel_, "225.1.1.1"));
}
TEST_F(DefaultChannelTest, SetSortlistAllocFail) {
for (int ii = 1; ii <= 3; ii++) {
ClearFails();
SetAllocFail(ii);
EXPECT_EQ(ARES_ENOMEM, ares_set_sortlist(channel_, "12.13.0.0/16 1234::5678/40 1.2.3.4")) << ii;
}
}
#ifdef USE_WINSOCK
TEST(Init, NoLibraryInit) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_ENOTINITIALIZED, ares_init(&channel));
}
#endif
#ifdef HAVE_CONTAINER
// These tests rely on the ability of non-root users to create a chroot
// using Linux namespaces.
// The library uses a variety of information sources to initialize a channel,
// in particular to determine:
// - search: the search domains to use
// - servers: the name servers to use
// - lookup: whether to check files or DNS or both (e.g. "fb")
// - options: various resolver options
// - sortlist: the order of preference for IP addresses
//
// The first source from the following list is used:
// - init_by_options(): explicitly specified values in struct ares_options
// - init_by_environment(): values from the environment:
// - LOCALDOMAIN -> search (single value)
// - RES_OPTIONS -> options
// - init_by_resolv_conf(): values from various config files:
// - /etc/resolv.conf -> search, lookup, servers, sortlist, options
// - /etc/nsswitch.conf -> lookup
// - /etc/host.conf -> lookup
// - /etc/svc.conf -> lookup
// - init_by_defaults(): fallback values:
// - gethostname(3) -> domain
// - "fb" -> lookup
NameContentList filelist = {
{"/etc/resolv.conf", "nameserver 1.2.3.4\n"
"sortlist 1.2.3.4/16 2.3.4.5\n"
"search first.com second.com\n"},
{"/etc/hosts", "3.4.5.6 ahostname.com\n"},
{"/etc/nsswitch.conf", "hosts: files\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerChannelInit,
"myhostname", "mydomainname.org", filelist) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
std::vector<std::string> actual = GetNameServers(channel);
std::vector<std::string> expected = {"1.2.3.4"};
EXPECT_EQ(expected, actual);
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(2, opts.ndomains);
EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
EXPECT_EQ(std::string("second.com"), std::string(opts.domains[1]));
ares_destroy_options(&opts);
HostResult result;
ares_gethostbyname(channel, "ahostname.com", AF_INET, HostCallback, &result);
ProcessWork(channel, NoExtraFDs, nullptr);
EXPECT_TRUE(result.done_);
std::stringstream ss;
ss << result.host_;
EXPECT_EQ("{'ahostname.com' aliases=[] addrs=[3.4.5.6]}", ss.str());
ares_destroy(channel);
return HasFailure();
}
CONTAINED_TEST_F(LibraryTest, ContainerSortlistOptionInit,
"myhostname", "mydomainname.org", filelist) {
ares_channel channel = nullptr;
struct ares_options opts = {0};
int optmask = 0;
optmask |= ARES_OPT_SORTLIST;
opts.nsort = 0;
// Explicitly specifying an empty sortlist in the options should override the
// environment.
EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(0, opts.nsort);
EXPECT_EQ(nullptr, opts.sortlist);
EXPECT_EQ(ARES_OPT_SORTLIST, (optmask & ARES_OPT_SORTLIST));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
NameContentList fullresolv = {
{"/etc/resolv.conf", " nameserver 1.2.3.4 \n"
"search first.com second.com\n"
"lookup bind\n"
"options debug ndots:5\n"
"sortlist 1.2.3.4/16 2.3.4.5\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerFullResolvInit,
"myhostname", "mydomainname.org", fullresolv) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(std::string("b"), std::string(opts.lookups));
EXPECT_EQ(5, opts.ndots);
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
// Allow path for resolv.conf to be configurable
NameContentList myresolvconf = {
{"/tmp/myresolv.cnf", " nameserver 1.2.3.4 \n"
"search first.com second.com\n"
"lookup bind\n"
"options debug ndots:5\n"
"sortlist 1.2.3.4/16 2.3.4.5\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerMyResolvConfInit,
"myhostname", "mydomain.org", myresolvconf) {
char filename[] = "/tmp/myresolv.cnf";
ares_channel channel = nullptr;
struct ares_options options = {0};
options.resolvconf_path = strdup(filename);
int optmask = ARES_OPT_RESOLVCONF;
EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &options, optmask));
optmask = 0;
free(options.resolvconf_path);
options.resolvconf_path = NULL;
EXPECT_EQ(ARES_SUCCESS, ares_save_options(channel, &options, &optmask));
EXPECT_EQ(ARES_OPT_RESOLVCONF, (optmask & ARES_OPT_RESOLVCONF));
EXPECT_EQ(std::string(filename), std::string(options.resolvconf_path));
ares_destroy_options(&options);
ares_destroy(channel);
return HasFailure();
}
NameContentList hostconf = {
{"/etc/resolv.conf", "nameserver 1.2.3.4\n"
"sortlist1.2.3.4\n" // malformed line
"search first.com second.com\n"},
{"/etc/host.conf", "order bind hosts\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerHostConfInit,
"myhostname", "mydomainname.org", hostconf) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(std::string("bf"), std::string(opts.lookups));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
NameContentList svcconf = {
{"/etc/resolv.conf", "nameserver 1.2.3.4\n"
"search first.com second.com\n"},
{"/etc/svc.conf", "hosts= bind\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerSvcConfInit,
"myhostname", "mydomainname.org", svcconf) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(std::string("b"), std::string(opts.lookups));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
NameContentList malformedresolvconflookup = {
{"/etc/resolv.conf", "nameserver 1.2.3.4\n"
"lookup garbage\n"}}; // malformed line
CONTAINED_TEST_F(LibraryTest, ContainerMalformedResolvConfLookup,
"myhostname", "mydomainname.org", malformedresolvconflookup) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(std::string("fb"), std::string(opts.lookups));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
// Failures when expected config filenames are inaccessible.
class MakeUnreadable {
public:
explicit MakeUnreadable(const std::string& filename)
: filename_(filename) {
chmod(filename_.c_str(), 0000);
}
~MakeUnreadable() { chmod(filename_.c_str(), 0644); }
private:
std::string filename_;
};
CONTAINED_TEST_F(LibraryTest, ContainerResolvConfNotReadable,
"myhostname", "mydomainname.org", filelist) {
ares_channel channel = nullptr;
MakeUnreadable hide("/etc/resolv.conf");
// Unavailable /etc/resolv.conf falls back to defaults
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
return HasFailure();
}
CONTAINED_TEST_F(LibraryTest, ContainerNsswitchConfNotReadable,
"myhostname", "mydomainname.org", filelist) {
ares_channel channel = nullptr;
// Unavailable /etc/nsswitch.conf falls back to defaults.
MakeUnreadable hide("/etc/nsswitch.conf");
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(std::string("fb"), std::string(opts.lookups));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
CONTAINED_TEST_F(LibraryTest, ContainerHostConfNotReadable,
"myhostname", "mydomainname.org", hostconf) {
ares_channel channel = nullptr;
// Unavailable /etc/host.conf falls back to defaults.
MakeUnreadable hide("/etc/host.conf");
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
ares_destroy(channel);
return HasFailure();
}
CONTAINED_TEST_F(LibraryTest, ContainerSvcConfNotReadable,
"myhostname", "mydomainname.org", svcconf) {
ares_channel channel = nullptr;
// Unavailable /etc/svc.conf falls back to defaults.
MakeUnreadable hide("/etc/svc.conf");
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
ares_destroy(channel);
return HasFailure();
}
NameContentList rotateenv = {
{"/etc/resolv.conf", "nameserver 1.2.3.4\n"
"search first.com second.com\n"
"options rotate\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerRotateInit,
"myhostname", "mydomainname.org", rotateenv) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(ARES_OPT_ROTATE, (optmask & ARES_OPT_ROTATE));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
CONTAINED_TEST_F(LibraryTest, ContainerRotateOverride,
"myhostname", "mydomainname.org", rotateenv) {
ares_channel channel = nullptr;
struct ares_options opts = {0};
int optmask = ARES_OPT_NOROTATE;
EXPECT_EQ(ARES_SUCCESS, ares_init_options(&channel, &opts, optmask));
optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(ARES_OPT_NOROTATE, (optmask & ARES_OPT_NOROTATE));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
// Test that blacklisted IPv6 resolves are ignored. They're filtered from any
// source, so resolv.conf is as good as any.
NameContentList blacklistedIpv6 = {
{"/etc/resolv.conf", " nameserver 254.192.1.1\n" // 0xfe.0xc0.0x01.0x01
" nameserver fec0::dead\n" // Blacklisted
" nameserver ffc0::c001\n" // Not blacklisted
" domain first.com\n"},
{"/etc/nsswitch.conf", "hosts: files\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerBlacklistedIpv6,
"myhostname", "mydomainname.org", blacklistedIpv6) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
std::vector<std::string> actual = GetNameServers(channel);
std::vector<std::string> expected = {
"254.192.1.1",
"ffc0:0000:0000:0000:0000:0000:0000:c001"
};
EXPECT_EQ(expected, actual);
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(1, opts.ndomains);
EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
NameContentList multiresolv = {
{"/etc/resolv.conf", " nameserver 1::2 ; ;;\n"
" domain first.com\n"},
{"/etc/nsswitch.conf", "hosts: files\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerMultiResolvInit,
"myhostname", "mydomainname.org", multiresolv) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
std::vector<std::string> actual = GetNameServers(channel);
std::vector<std::string> expected = {"0001:0000:0000:0000:0000:0000:0000:0002"};
EXPECT_EQ(expected, actual);
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(1, opts.ndomains);
EXPECT_EQ(std::string("first.com"), std::string(opts.domains[0]));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
NameContentList systemdresolv = {
{"/etc/resolv.conf", "nameserver 1.2.3.4\n"
"domain first.com\n"},
{"/etc/nsswitch.conf", "hosts: junk resolve files\n"}};
CONTAINED_TEST_F(LibraryTest, ContainerSystemdResolvInit,
"myhostname", "mydomainname.org", systemdresolv) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(std::string("bf"), std::string(opts.lookups));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
NameContentList empty = {}; // no files
CONTAINED_TEST_F(LibraryTest, ContainerEmptyInit,
"host.domain.org", "domain.org", empty) {
ares_channel channel = nullptr;
EXPECT_EQ(ARES_SUCCESS, ares_init(&channel));
std::vector<std::string> actual = GetNameServers(channel);
std::vector<std::string> expected = {"127.0.0.1"};
EXPECT_EQ(expected, actual);
struct ares_options opts;
int optmask = 0;
ares_save_options(channel, &opts, &optmask);
EXPECT_EQ(1, opts.ndomains);
EXPECT_EQ(std::string("domain.org"), std::string(opts.domains[0]));
EXPECT_EQ(std::string("fb"), std::string(opts.lookups));
ares_destroy_options(&opts);
ares_destroy(channel);
return HasFailure();
}
#endif
} // namespace test
} // namespace ares
|
/*
* Copyright 2012 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkImageFilter.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkRect.h"
#include "include/effects/SkComposeImageFilter.h"
#include "include/private/SkSafe32.h"
#include "src/core/SkFuzzLogging.h"
#include "src/core/SkImageFilterCache.h"
#include "src/core/SkImageFilter_Base.h"
#include "src/core/SkLocalMatrixImageFilter.h"
#include "src/core/SkMatrixImageFilter.h"
#include "src/core/SkReadBuffer.h"
#include "src/core/SkSpecialImage.h"
#include "src/core/SkSpecialSurface.h"
#include "src/core/SkValidationUtils.h"
#include "src/core/SkWriteBuffer.h"
#if SK_SUPPORT_GPU
#include "include/gpu/GrContext.h"
#include "include/private/GrRecordingContext.h"
#include "src/gpu/GrColorSpaceXform.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrFixedClip.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrRenderTargetContext.h"
#include "src/gpu/GrTextureProxy.h"
#include "src/gpu/SkGr.h"
#endif
#include <atomic>
///////////////////////////////////////////////////////////////////////////////////////////////////
// SkImageFilter - A number of the public APIs on SkImageFilter downcast to SkImageFilter_Base
// in order to perform their actual work.
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns the number of inputs this filter will accept (some inputs can
* be NULL).
*/
int SkImageFilter::countInputs() const { return as_IFB(this)->fInputs.count(); }
/**
* Returns the input filter at a given index, or NULL if no input is
* connected. The indices used are filter-specific.
*/
const SkImageFilter* SkImageFilter::getInput(int i) const {
SkASSERT(i < this->countInputs());
return as_IFB(this)->fInputs[i].get();
}
bool SkImageFilter::isColorFilterNode(SkColorFilter** filterPtr) const {
return as_IFB(this)->onIsColorFilterNode(filterPtr);
}
SkIRect SkImageFilter::filterBounds(const SkIRect& src, const SkMatrix& ctm,
MapDirection direction, const SkIRect* inputRect) const {
// The old filterBounds() function uses SkIRects that are defined in layer space so, while
// we still are supporting it, bypass SkIF_B's new public filter bounds functions and go right
// to the internal layer-space calculations.
skif::Mapping mapping(SkMatrix::I(), ctm);
if (kReverse_MapDirection == direction) {
skif::LayerSpace<SkIRect> targetOutput(src);
skif::LayerSpace<SkIRect> content(inputRect ? *inputRect : src);
return SkIRect(as_IFB(this)->onGetInputLayerBounds(mapping, targetOutput, content));
} else {
SkASSERT(!inputRect);
skif::LayerSpace<SkIRect> content(src);
skif::LayerSpace<SkIRect> output = as_IFB(this)->onGetOutputLayerBounds(mapping, content);
// Manually apply the crop rect for now, until cropping is performed by a dedicated SkIF.
SkIRect dst;
as_IFB(this)->getCropRect().applyTo(
SkIRect(output), ctm, as_IFB(this)->affectsTransparentBlack(), &dst);
return dst;
}
}
SkRect SkImageFilter::computeFastBounds(const SkRect& src) const {
if (0 == this->countInputs()) {
return src;
}
SkRect combinedBounds = this->getInput(0) ? this->getInput(0)->computeFastBounds(src) : src;
for (int i = 1; i < this->countInputs(); i++) {
const SkImageFilter* input = this->getInput(i);
if (input) {
combinedBounds.join(input->computeFastBounds(src));
} else {
combinedBounds.join(src);
}
}
return combinedBounds;
}
bool SkImageFilter::canComputeFastBounds() const {
if (as_IFB(this)->affectsTransparentBlack()) {
return false;
}
for (int i = 0; i < this->countInputs(); i++) {
const SkImageFilter* input = this->getInput(i);
if (input && !input->canComputeFastBounds()) {
return false;
}
}
return true;
}
bool SkImageFilter::asAColorFilter(SkColorFilter** filterPtr) const {
SkASSERT(nullptr != filterPtr);
if (!this->isColorFilterNode(filterPtr)) {
return false;
}
if (nullptr != this->getInput(0) || (*filterPtr)->affectsTransparentBlack()) {
(*filterPtr)->unref();
return false;
}
return true;
}
sk_sp<SkImageFilter> SkImageFilter::MakeMatrixFilter(const SkMatrix& matrix,
SkFilterQuality filterQuality,
sk_sp<SkImageFilter> input) {
return SkMatrixImageFilter::Make(matrix, filterQuality, std::move(input));
}
sk_sp<SkImageFilter> SkImageFilter::makeWithLocalMatrix(const SkMatrix& matrix) const {
return SkLocalMatrixImageFilter::Make(matrix, this->refMe());
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// SkImageFilter_Base
///////////////////////////////////////////////////////////////////////////////////////////////////
SK_USE_FLUENT_IMAGE_FILTER_TYPES
static int32_t next_image_filter_unique_id() {
static std::atomic<int32_t> nextID{1};
int32_t id;
do {
id = nextID++;
} while (id == 0);
return id;
}
SkImageFilter_Base::SkImageFilter_Base(sk_sp<SkImageFilter> const* inputs,
int inputCount, const CropRect* cropRect)
: fUsesSrcInput(false)
, fUniqueID(next_image_filter_unique_id()) {
fCropRect = cropRect ? *cropRect : CropRect(SkRect(), 0x0);
fInputs.reset(inputCount);
for (int i = 0; i < inputCount; ++i) {
if (!inputs[i] || as_IFB(inputs[i])->fUsesSrcInput) {
fUsesSrcInput = true;
}
fInputs[i] = inputs[i];
}
}
SkImageFilter_Base::~SkImageFilter_Base() {
SkImageFilterCache::Get()->purgeByImageFilter(this);
}
bool SkImageFilter_Base::Common::unflatten(SkReadBuffer& buffer, int expectedCount) {
const int count = buffer.readInt();
if (!buffer.validate(count >= 0)) {
return false;
}
if (!buffer.validate(expectedCount < 0 || count == expectedCount)) {
return false;
}
SkASSERT(fInputs.empty());
for (int i = 0; i < count; i++) {
fInputs.push_back(buffer.readBool() ? buffer.readImageFilter() : nullptr);
if (!buffer.isValid()) {
return false;
}
}
SkRect rect;
buffer.readRect(&rect);
if (!buffer.isValid() || !buffer.validate(SkIsValidRect(rect))) {
return false;
}
uint32_t flags = buffer.readUInt();
fCropRect = CropRect(rect, flags);
return buffer.isValid();
}
void SkImageFilter_Base::flatten(SkWriteBuffer& buffer) const {
buffer.writeInt(fInputs.count());
for (int i = 0; i < fInputs.count(); i++) {
const SkImageFilter* input = this->getInput(i);
buffer.writeBool(input != nullptr);
if (input != nullptr) {
buffer.writeFlattenable(input);
}
}
buffer.writeRect(fCropRect.rect());
buffer.writeUInt(fCropRect.flags());
}
skif::FilterResult<For::kOutput> SkImageFilter_Base::filterImage(const skif::Context& context) const {
// TODO (michaelludwig) - Old filters have an implicit assumption that the source image
// (originally passed separately) has an origin of (0, 0). SkComposeImageFilter makes an effort
// to ensure that remains the case. Once everyone uses the new type systems for bounds, non
// (0, 0) source origins will be easy to support.
SkASSERT(context.source().layerOrigin().x() == 0 && context.source().layerOrigin().y() == 0);
skif::FilterResult<For::kOutput> result;
if (!context.isValid()) {
return result;
}
uint32_t srcGenID = fUsesSrcInput ? context.sourceImage()->uniqueID() : 0;
const SkIRect srcSubset = fUsesSrcInput ? context.sourceImage()->subset()
: SkIRect::MakeWH(0, 0);
SkImageFilterCacheKey key(fUniqueID, context.mapping().layerMatrix(), context.clipBounds(),
srcGenID, srcSubset);
if (context.cache() && context.cache()->get(key, &result)) {
return result;
}
result = this->onFilterImage(context);
#if SK_SUPPORT_GPU
if (context.gpuBacked() && result.image() && !result.image()->isTextureBacked()) {
// Keep the result on the GPU - this is still required for some
// image filters that don't support GPU in all cases
auto asTexture = result.image()->makeTextureImage(context.getContext());
result = skif::FilterResult<For::kOutput>(std::move(asTexture), result.layerOrigin());
}
#endif
if (context.cache()) {
context.cache()->set(key, this, result);
}
return result;
}
skif::LayerSpace<SkIRect> SkImageFilter_Base::getInputBounds(
const skif::Mapping& mapping, const skif::DeviceSpace<SkRect>& desiredOutput,
const skif::ParameterSpace<SkRect>* knownContentBounds) const {
// Map both the device-space desired coverage area and the known content bounds to layer space
skif::LayerSpace<SkIRect> desiredBounds = mapping.deviceToLayer(desiredOutput).roundOut();
// If we have no known content bounds use the desired coverage area, because that is the most
// conservative possibility.
skif::LayerSpace<SkIRect> contentBounds =
knownContentBounds ? mapping.paramToLayer(*knownContentBounds).roundOut()
: desiredBounds;
// Process the layer-space desired output with the filter DAG to determine required input
skif::LayerSpace<SkIRect> requiredInput = this->onGetInputLayerBounds(
mapping, desiredBounds, contentBounds);
// If we know what's actually going to be drawn into the layer, and we don't change transparent
// black, then we can further restrict the layer to what the known content is
if (knownContentBounds && !this->affectsTransparentBlack()) {
if (!requiredInput.intersect(contentBounds)) {
// Nothing would be output by the filter, so return empty rect
return skif::LayerSpace<SkIRect>(SkIRect::MakeEmpty());
}
}
return requiredInput;
}
skif::DeviceSpace<SkIRect> SkImageFilter_Base::getOutputBounds(
const skif::Mapping& mapping, const skif::ParameterSpace<SkRect>& contentBounds) const {
// Map the input content into the layer space where filtering will occur
skif::LayerSpace<SkRect> layerContent = mapping.paramToLayer(contentBounds);
// Determine the filter DAGs output bounds in layer space
skif::LayerSpace<SkIRect> filterOutput = this->onGetOutputLayerBounds(
mapping, layerContent.roundOut());
// FIXME (michaelludwig) - To be removed once cropping is isolated, but remain consistent with
// old filterBounds(kForward) behavior.
SkIRect dst;
as_IFB(this)->getCropRect().applyTo(
SkIRect(filterOutput), mapping.layerMatrix(),
as_IFB(this)->affectsTransparentBlack(), &dst);
// Map all the way to device space
return mapping.layerToDevice(skif::LayerSpace<SkIRect>(dst));
}
// TODO (michaelludwig) - Default to using the old onFilterImage, as filters are updated one by one.
// Once the old function is gone, this onFilterImage() will be made a pure virtual.
skif::FilterResult<For::kOutput> SkImageFilter_Base::onFilterImage(const skif::Context& context) const {
SkIPoint origin;
auto image = this->onFilterImage(context, &origin);
return skif::FilterResult<For::kOutput>(std::move(image), skif::LayerSpace<SkIPoint>(origin));
}
bool SkImageFilter_Base::canHandleComplexCTM() const {
// CropRects need to apply in the source coordinate system, but are not aware of complex CTMs
// when performing clipping. For a simple fix, any filter with a crop rect set cannot support
// complex CTMs until that's updated.
if (this->cropRectIsSet() || !this->onCanHandleComplexCTM()) {
return false;
}
const int count = this->countInputs();
for (int i = 0; i < count; ++i) {
const SkImageFilter_Base* input = as_IFB(this->getInput(i));
if (input && !input->canHandleComplexCTM()) {
return false;
}
}
return true;
}
void SkImageFilter::CropRect::applyTo(const SkIRect& imageBounds, const SkMatrix& ctm,
bool embiggen, SkIRect* cropped) const {
*cropped = imageBounds;
if (fFlags) {
SkRect devCropR;
ctm.mapRect(&devCropR, fRect);
SkIRect devICropR = devCropR.roundOut();
// Compute the left/top first, in case we need to modify the right/bottom for a missing edge
if (fFlags & kHasLeft_CropEdge) {
if (embiggen || devICropR.fLeft > cropped->fLeft) {
cropped->fLeft = devICropR.fLeft;
}
} else {
devICropR.fRight = Sk32_sat_add(cropped->fLeft, devICropR.width());
}
if (fFlags & kHasTop_CropEdge) {
if (embiggen || devICropR.fTop > cropped->fTop) {
cropped->fTop = devICropR.fTop;
}
} else {
devICropR.fBottom = Sk32_sat_add(cropped->fTop, devICropR.height());
}
if (fFlags & kHasWidth_CropEdge) {
if (embiggen || devICropR.fRight < cropped->fRight) {
cropped->fRight = devICropR.fRight;
}
}
if (fFlags & kHasHeight_CropEdge) {
if (embiggen || devICropR.fBottom < cropped->fBottom) {
cropped->fBottom = devICropR.fBottom;
}
}
}
}
bool SkImageFilter_Base::applyCropRect(const Context& ctx, const SkIRect& srcBounds,
SkIRect* dstBounds) const {
SkIRect tmpDst = this->onFilterNodeBounds(srcBounds, ctx.ctm(), kForward_MapDirection, nullptr);
fCropRect.applyTo(tmpDst, ctx.ctm(), this->affectsTransparentBlack(), dstBounds);
// Intersect against the clip bounds, in case the crop rect has
// grown the bounds beyond the original clip. This can happen for
// example in tiling, where the clip is much smaller than the filtered
// primitive. If we didn't do this, we would be processing the filter
// at the full crop rect size in every tile.
return dstBounds->intersect(ctx.clipBounds());
}
// Return a larger (newWidth x newHeight) copy of 'src' with black padding
// around it.
static sk_sp<SkSpecialImage> pad_image(SkSpecialImage* src, const SkImageFilter_Base::Context& ctx,
int newWidth, int newHeight, int offX, int offY) {
// We would like to operate in the source's color space (so that we return an "identical"
// image, other than the padding. To achieve that, we'd create a new context using
// src->getColorSpace() to replace ctx.colorSpace().
// That fails in at least two ways. For formats that are texturable but not renderable (like
// F16 on some ES implementations), we can't create a surface to do the work. For sRGB, images
// may be tagged with an sRGB color space (which leads to an sRGB config in makeSurface). But
// the actual config of that sRGB image on a device with no sRGB support is non-sRGB.
//
// Rather than try to special case these situations, we execute the image padding in the
// destination color space. This should not affect the output of the DAG in (almost) any case,
// because the result of this call is going to be used as an input, where it would have been
// switched to the destination space anyway. The one exception would be a filter that expected
// to consume unclamped F16 data, but the padded version of the image is pre-clamped to 8888.
// We can revisit this logic if that ever becomes an actual problem.
sk_sp<SkSpecialSurface> surf(ctx.makeSurface(SkISize::Make(newWidth, newHeight)));
if (!surf) {
return nullptr;
}
SkCanvas* canvas = surf->getCanvas();
SkASSERT(canvas);
canvas->clear(0x0);
src->draw(canvas, offX, offY, nullptr);
return surf->makeImageSnapshot();
}
sk_sp<SkSpecialImage> SkImageFilter_Base::applyCropRectAndPad(const Context& ctx,
SkSpecialImage* src,
SkIPoint* srcOffset,
SkIRect* bounds) const {
const SkIRect srcBounds = SkIRect::MakeXYWH(srcOffset->x(), srcOffset->y(),
src->width(), src->height());
if (!this->applyCropRect(ctx, srcBounds, bounds)) {
return nullptr;
}
if (srcBounds.contains(*bounds)) {
return sk_sp<SkSpecialImage>(SkRef(src));
} else {
sk_sp<SkSpecialImage> img(pad_image(src, ctx, bounds->width(), bounds->height(),
Sk32_sat_sub(srcOffset->x(), bounds->x()),
Sk32_sat_sub(srcOffset->y(), bounds->y())));
*srcOffset = SkIPoint::Make(bounds->x(), bounds->y());
return img;
}
}
// NOTE: The new onGetOutputLayerBounds() and onGetInputLayerBounds() default to calling into the
// deprecated onFilterBounds and onFilterNodeBounds. While these functions are not tagged, they do
// match the documented default behavior for the new bounds functions.
SkIRect SkImageFilter_Base::onFilterBounds(const SkIRect& src, const SkMatrix& ctm,
MapDirection dir, const SkIRect* inputRect) const {
if (this->countInputs() < 1) {
return src;
}
SkIRect totalBounds;
for (int i = 0; i < this->countInputs(); ++i) {
const SkImageFilter* filter = this->getInput(i);
SkIRect rect = filter ? filter->filterBounds(src, ctm, dir, inputRect) : src;
if (0 == i) {
totalBounds = rect;
} else {
totalBounds.join(rect);
}
}
return totalBounds;
}
SkIRect SkImageFilter_Base::onFilterNodeBounds(const SkIRect& src, const SkMatrix&,
MapDirection, const SkIRect*) const {
return src;
}
skif::LayerSpace<SkIRect> SkImageFilter_Base::visitInputLayerBounds(
const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput,
const skif::LayerSpace<SkIRect>& contentBounds) const {
if (this->countInputs() < 1) {
// TODO (michaelludwig) - if a filter doesn't have any inputs, it doesn't need any
// implicit source image, so arguably we could return an empty rect here. 'desiredOutput' is
// consistent with original behavior, so empty bounds may have unintended side effects
// but should be explored later.
return desiredOutput;
}
skif::LayerSpace<SkIRect> netInput;
for (int i = 0; i < this->countInputs(); ++i) {
const SkImageFilter* filter = this->getInput(i);
// The required input for this input filter, or 'targetOutput' if the filter is null and
// the source image is used (so must be sized to cover 'targetOutput').
skif::LayerSpace<SkIRect> requiredInput =
filter ? as_IFB(filter)->onGetInputLayerBounds(mapping, desiredOutput,
contentBounds)
: desiredOutput;
// Accumulate with all other filters
if (i == 0) {
netInput = requiredInput;
} else {
netInput.join(requiredInput);
}
}
return netInput;
}
skif::LayerSpace<SkIRect> SkImageFilter_Base::visitOutputLayerBounds(
const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const {
if (this->countInputs() < 1) {
// TODO (michaelludwig) - if a filter doesn't have any inputs, it presumably is determining
// its output size from something other than the implicit source contentBounds, in which
// case it shouldn't be calling this helper function, so explore adding an unreachable test
return contentBounds;
}
skif::LayerSpace<SkIRect> netOutput;
for (int i = 0; i < this->countInputs(); ++i) {
const SkImageFilter* filter = this->getInput(i);
// The output for just this input filter, or 'contentBounds' if the filter is null and
// the source image is used (i.e. the identity filter applied to the source).
skif::LayerSpace<SkIRect> output =
filter ? as_IFB(filter)->onGetOutputLayerBounds(mapping, contentBounds)
: contentBounds;
// Accumulate with all other filters
if (i == 0) {
netOutput = output;
} else {
netOutput.join(output);
}
}
return netOutput;
}
skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetInputLayerBounds(
const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& desiredOutput,
const skif::LayerSpace<SkIRect>& contentBounds, VisitChildren recurse) const {
// Call old functions for now since they may have been overridden by a subclass that's not been
// updated yet; normally this would just default to visitInputLayerBounds()
SkIRect content = SkIRect(contentBounds);
SkIRect input = this->onFilterNodeBounds(SkIRect(desiredOutput), mapping.layerMatrix(),
kReverse_MapDirection, &content);
if (recurse == VisitChildren::kYes) {
SkIRect aggregate = this->onFilterBounds(input, mapping.layerMatrix(),
kReverse_MapDirection, &input);
return skif::LayerSpace<SkIRect>(aggregate);
} else {
return skif::LayerSpace<SkIRect>(input);
}
}
skif::LayerSpace<SkIRect> SkImageFilter_Base::onGetOutputLayerBounds(
const skif::Mapping& mapping, const skif::LayerSpace<SkIRect>& contentBounds) const {
// Call old functions for now; normally this would default to visitOutputLayerBounds()
SkIRect aggregate = this->onFilterBounds(SkIRect(contentBounds), mapping.layerMatrix(),
kForward_MapDirection, nullptr);
SkIRect output = this->onFilterNodeBounds(aggregate, mapping.layerMatrix(),
kForward_MapDirection, nullptr);
return skif::LayerSpace<SkIRect>(output);
}
template<skif::Usage kU>
skif::FilterResult<kU> SkImageFilter_Base::filterInput(int index, const skif::Context& ctx) const {
// Sanity checks for the index-specific input usages
SkASSERT(kU != skif::Usage::kInput0 || index == 0);
SkASSERT(kU != skif::Usage::kInput1 || index == 1);
const SkImageFilter* input = this->getInput(index);
if (!input) {
// Convert from the generic kInput of the source image to kU
return static_cast<skif::FilterResult<kU>>(ctx.source());
}
skif::FilterResult<For::kOutput> result = as_IFB(input)->filterImage(this->mapContext(ctx));
SkASSERT(!result.image() || ctx.gpuBacked() == result.image()->isTextureBacked());
// Map the output result of the input image filter to the input usage requested for this filter
return static_cast<skif::FilterResult<kU>>(std::move(result));
}
// Instantiate filterInput() for kInput, kInput0, and kInput1. This does not provide a definition
// for kOutput, which should never be used anyways, and this way the linker will fail for us then.
template skif::FilterResult<For::kInput> SkImageFilter_Base::filterInput(int, const skif::Context&) const;
template skif::FilterResult<For::kInput0> SkImageFilter_Base::filterInput(int, const skif::Context&) const;
template skif::FilterResult<For::kInput1> SkImageFilter_Base::filterInput(int, const skif::Context&) const;
SkImageFilter_Base::Context SkImageFilter_Base::mapContext(const Context& ctx) const {
// We don't recurse through the child input filters because that happens automatically
// as part of the filterImage() evaluation. In this case, we want the bounds for the
// edge from this node to its children, without the effects of the child filters.
skif::LayerSpace<SkIRect> childOutput = this->onGetInputLayerBounds(
ctx.mapping(), ctx.desiredOutput(), ctx.desiredOutput(), VisitChildren::kNo);
return ctx.withNewDesiredOutput(childOutput);
}
#if SK_SUPPORT_GPU
sk_sp<SkSpecialImage> SkImageFilter_Base::DrawWithFP(GrRecordingContext* context,
std::unique_ptr<GrFragmentProcessor> fp,
const SkIRect& bounds,
SkColorType colorType,
const SkColorSpace* colorSpace,
GrProtected isProtected) {
GrPaint paint;
paint.addColorFragmentProcessor(std::move(fp));
paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
auto renderTargetContext = GrRenderTargetContext::Make(
context, SkColorTypeToGrColorType(colorType), sk_ref_sp(colorSpace),
SkBackingFit::kApprox, bounds.size(), 1, GrMipMapped::kNo, isProtected,
kBottomLeft_GrSurfaceOrigin);
if (!renderTargetContext) {
return nullptr;
}
SkIRect dstIRect = SkIRect::MakeWH(bounds.width(), bounds.height());
SkRect srcRect = SkRect::Make(bounds);
SkRect dstRect = SkRect::MakeWH(srcRect.width(), srcRect.height());
GrFixedClip clip(dstIRect);
renderTargetContext->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(), dstRect,
srcRect);
return SkSpecialImage::MakeDeferredFromGpu(
context, dstIRect, kNeedNewImageUniqueID_SpecialImage,
renderTargetContext->asTextureProxyRef(), renderTargetContext->colorInfo().colorType(),
renderTargetContext->colorInfo().refColorSpace());
}
sk_sp<SkSpecialImage> SkImageFilter_Base::ImageToColorSpace(SkSpecialImage* src,
SkColorType colorType,
SkColorSpace* colorSpace) {
// There are several conditions that determine if we actually need to convert the source to the
// destination's color space. Rather than duplicate that logic here, just try to make an xform
// object. If that produces something, then both are tagged, and the source is in a different
// gamut than the dest. There is some overhead to making the xform, but those are cached, and
// if we get one back, that means we're about to use it during the conversion anyway.
auto colorSpaceXform = GrColorSpaceXform::Make(src->getColorSpace(), src->alphaType(),
colorSpace, kPremul_SkAlphaType);
if (!colorSpaceXform) {
// No xform needed, just return the original image
return sk_ref_sp(src);
}
sk_sp<SkSpecialSurface> surf(src->makeSurface(colorType, colorSpace,
SkISize::Make(src->width(), src->height())));
if (!surf) {
return sk_ref_sp(src);
}
SkCanvas* canvas = surf->getCanvas();
SkASSERT(canvas);
SkPaint p;
p.setBlendMode(SkBlendMode::kSrc);
src->draw(canvas, 0, 0, &p);
return surf->makeImageSnapshot();
}
#endif
// In repeat mode, when we are going to sample off one edge of the srcBounds we require the
// opposite side be preserved.
SkIRect SkImageFilter_Base::DetermineRepeatedSrcBound(const SkIRect& srcBounds,
const SkIVector& filterOffset,
const SkISize& filterSize,
const SkIRect& originalSrcBounds) {
SkIRect tmp = srcBounds;
tmp.adjust(-filterOffset.fX, -filterOffset.fY,
filterSize.fWidth - filterOffset.fX, filterSize.fHeight - filterOffset.fY);
if (tmp.fLeft < originalSrcBounds.fLeft || tmp.fRight > originalSrcBounds.fRight) {
tmp.fLeft = originalSrcBounds.fLeft;
tmp.fRight = originalSrcBounds.fRight;
}
if (tmp.fTop < originalSrcBounds.fTop || tmp.fBottom > originalSrcBounds.fBottom) {
tmp.fTop = originalSrcBounds.fTop;
tmp.fBottom = originalSrcBounds.fBottom;
}
return tmp;
}
void SkImageFilter_Base::PurgeCache() {
SkImageFilterCache::Get()->purge();
}
static sk_sp<SkImageFilter> apply_ctm_to_filter(sk_sp<SkImageFilter> input, const SkMatrix& ctm,
SkMatrix* remainder) {
if (ctm.isScaleTranslate() || as_IFB(input)->canHandleComplexCTM()) {
// The filter supports the CTM, so leave it as-is and 'remainder' stores the whole CTM
*remainder = ctm;
return input;
}
// We have a complex CTM and a filter that can't support them, so it needs to use the matrix
// transform filter that resamples the image contents. Decompose the simple portion of the ctm
// into 'remainder'
SkMatrix ctmToEmbed;
SkSize scale;
if (ctm.decomposeScale(&scale, &ctmToEmbed)) {
// decomposeScale splits ctm into scale * ctmToEmbed, so bake ctmToEmbed into DAG
// with a matrix filter and return scale as the remaining matrix for the real CTM.
remainder->setScale(scale.fWidth, scale.fHeight);
// ctmToEmbed is passed to SkMatrixImageFilter, which performs its transforms as if it were
// a pre-transformation before applying the image-filter context's CTM. In this case, we
// need ctmToEmbed to be a post-transformation (i.e. after the scale matrix since
// decomposeScale produces ctm = ctmToEmbed * scale). Giving scale^-1 * ctmToEmbed * scale
// to the matrix filter achieves this effect.
// TODO (michaelludwig) - When the original root node of a filter can be drawn directly to a
// device using ctmToEmbed, this abuse of SkMatrixImageFilter can go away.
ctmToEmbed.preScale(scale.fWidth, scale.fHeight);
ctmToEmbed.postScale(1.f / scale.fWidth, 1.f / scale.fHeight);
} else {
// Unable to decompose
// FIXME Ideally we'd embed the entire CTM as part of the matrix image filter, but
// the device <-> src bounds calculations for filters are very brittle under perspective,
// and can easily run into precision issues (wrong bounds that clip), or performance issues
// (producing large source-space images where 80% of the image is compressed into a few
// device pixels). A longer term solution for perspective-space image filtering is needed
// see skbug.com/9074
if (ctm.hasPerspective()) {
*remainder = ctm;
return input;
}
ctmToEmbed = ctm;
remainder->setIdentity();
}
return SkMatrixImageFilter::Make(ctmToEmbed, kLow_SkFilterQuality, input);
}
sk_sp<SkImageFilter> SkImageFilter_Base::applyCTM(const SkMatrix& ctm, SkMatrix* remainder) const {
return apply_ctm_to_filter(this->refMe(), ctm, remainder);
}
|
// Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/builtins/builtins-utils-inl.h"
#include "src/builtins/builtins.h"
#include "src/objects/bigint.h"
#include "src/objects/js-temporal-objects-inl.h"
namespace v8 {
namespace internal {
#define TO_BE_IMPLEMENTED(id) \
BUILTIN_NO_RCS(id) { \
HandleScope scope(isolate); \
UNIMPLEMENTED(); \
}
#define TEMPORAL_NOW0(T) \
BUILTIN(TemporalNow##T) { \
HandleScope scope(isolate); \
RETURN_RESULT_OR_FAILURE(isolate, JSTemporal##T::Now(isolate)); \
}
#define TEMPORAL_NOW2(T) \
BUILTIN(TemporalNow##T) { \
HandleScope scope(isolate); \
RETURN_RESULT_OR_FAILURE( \
isolate, JSTemporal##T::Now(isolate, args.atOrUndefined(isolate, 1), \
args.atOrUndefined(isolate, 2))); \
}
#define TEMPORAL_NOW_ISO1(T) \
BUILTIN(TemporalNow##T##ISO) { \
HandleScope scope(isolate); \
RETURN_RESULT_OR_FAILURE( \
isolate, \
JSTemporal##T::NowISO(isolate, args.atOrUndefined(isolate, 1))); \
}
/* Temporal #sec-temporal.plaindate.compare */
TO_BE_IMPLEMENTED(TemporalPlainDateCompare)
/* Temporal #sec-temporal.plaindate.prototype.toplainyearmonth */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeToPlainYearMonth)
/* Temporal #sec-temporal.plaindate.prototype.toplainmonthday */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeToPlainMonthDay)
/* Temporal #sec-temporal.plaindate.prototype.add */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeAdd)
/* Temporal #sec-temporal.plaindate.prototype.substract */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeSubtract)
/* Temporal #sec-temporal.plaindate.prototype.with */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeWith)
/* Temporal #sec-temporal.plaindate.prototype.until */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeUntil)
/* Temporal #sec-temporal.plaindate.prototype.since */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeSince)
/* Temporal #sec-temporal.plaindate.prototype.equals */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeEquals)
/* Temporal #sec-temporal.plaindate.prototype.toplaindatetime */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeToPlainDateTime)
/* Temporal #sec-temporal.plaindate.prototype.tozoneddatetime */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeToZonedDateTime)
/* Temporal #sec-temporal.plaindate.prototype.tostring */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeToString)
/* Temporal #sec-temporal.plaindate.prototype.tojson */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeToJSON)
/* Temporal.PlaneTime */
/* Temporal #sec-temporal.plaintime.compare */
TO_BE_IMPLEMENTED(TemporalPlainTimeCompare)
/* Temporal #sec-temporal.plaintime.prototype.add */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeAdd)
/* Temporal #sec-temporal.plaintime.prototype.subtract */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeSubtract)
/* Temporal #sec-temporal.plaintime.prototype.with */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeWith)
/* Temporal #sec-temporal.plaintime.prototype.until */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeUntil)
/* Temporal #sec-temporal.plaintime.prototype.since */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeSince)
/* Temporal #sec-temporal.plaintime.prototype.round */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeRound)
/* Temporal #sec-temporal.plaintime.prototype.equals */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeEquals)
/* Temporal #sec-temporal.plaintime.prototype.toplaindatetime */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeToPlainDateTime)
/* Temporal #sec-temporal.plaintime.prototype.tozoneddatetime */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeToZonedDateTime)
/* Temporal #sec-temporal.plaintime.prototype.tostring */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeToString)
/* Temporal #sec-temporal.plaindtimeprototype.tojson */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeToJSON)
/* Temporal.PlaneDateTime */
/* Temporal #sec-temporal.plaindatetime.from */
TO_BE_IMPLEMENTED(TemporalPlainDateTimeFrom)
/* Temporal #sec-temporal.plaindatetime.compare */
TO_BE_IMPLEMENTED(TemporalPlainDateTimeCompare)
/* Temporal #sec-temporal.plaindatetime.prototype.with */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeWith)
/* Temporal #sec-temporal.plaindatetime.prototype.withplainTime */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeWithPlainTime)
/* Temporal #sec-temporal.plaindatetime.prototype.withplainDate */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeWithPlainDate)
/* Temporal #sec-temporal.plaindatetime.prototype.add */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeAdd)
/* Temporal #sec-temporal.plaindatetime.prototype.subtract */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeSubtract)
/* Temporal #sec-temporal.plaindatetime.prototype.until */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeUntil)
/* Temporal #sec-temporal.plaindatetime.prototype.since */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeSince)
/* Temporal #sec-temporal.plaindatetime.prototype.round */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeRound)
/* Temporal #sec-temporal.plaindatetime.prototype.equals */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeEquals)
/* Temporal #sec-temporal.plaindatetime.prototype.tostring */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToString)
/* Temporal #sec-temporal.plainddatetimeprototype.tojson */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToJSON)
/* Temporal #sec-temporal.plaindatetime.prototype.tozoneddatetime */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToZonedDateTime)
/* Temporal #sec-temporal.plaindatetime.prototype.toplaindate */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToPlainDate)
/* Temporal #sec-temporal.plaindatetime.prototype.toplainyearmonth */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToPlainYearMonth)
/* Temporal #sec-temporal.plaindatetime.prototype.toplainmonthday */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToPlainMonthDay)
/* Temporal #sec-temporal.plaindatetime.prototype.toplaintime */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToPlainTime)
/* Temporal.ZonedDateTime */
/* Temporal #sec-temporal.zoneddatetime.from */
TO_BE_IMPLEMENTED(TemporalZonedDateTimeFrom)
/* Temporal #sec-temporal.zoneddatetime.compare */
TO_BE_IMPLEMENTED(TemporalZonedDateTimeCompare)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.year */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeYear)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.month */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeMonth)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.monthcode */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeMonthCode)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.day */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeDay)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.dayofweek */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeDayOfWeek)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.dayofyear */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeDayOfYear)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.weekofyear */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeWeekOfYear)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.hoursinday */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeHoursInDay)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.daysinweek */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeDaysInWeek)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.daysinmonth */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeDaysInMonth)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.daysinyear */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeDaysInYear)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.monthsinyear */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeMonthsInYear)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.inleapyear */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeInLeapYear)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.offsetnanoseconds */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeOffsetNanoseconds)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.offset */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeOffset)
/* Temporal #sec-temporal.zoneddatetime.prototype.with */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeWith)
/* Temporal #sec-temporal.zoneddatetime.prototype.withplaintime */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeWithPlainTime)
/* Temporal #sec-temporal.zoneddatetime.prototype.withplaindate */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeWithPlainDate)
/* Temporal #sec-temporal.zoneddatetime.prototype.add */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeAdd)
/* Temporal #sec-temporal.zoneddatetime.prototype.subtract */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeSubtract)
/* Temporal #sec-temporal.zoneddatetime.prototype.until */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeUntil)
/* Temporal #sec-temporal.zoneddatetime.prototype.since */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeSince)
/* Temporal #sec-temporal.zoneddatetime.prototype.round */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeRound)
/* Temporal #sec-temporal.zoneddatetime.prototype.equals */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeEquals)
/* Temporal #sec-temporal.zoneddatetime.prototype.tostring */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeToString)
/* Temporal #sec-temporal.zonedddatetimeprototype.tojson */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeToJSON)
/* Temporal #sec-temporal.zoneddatetime.prototype.startofday */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeStartOfDay)
/* Temporal #sec-temporal.zoneddatetime.prototype.toinstant */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeToInstant)
/* Temporal #sec-temporal.zoneddatetime.prototype.toplaindate */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeToPlainDate)
/* Temporal #sec-temporal.zoneddatetime.prototype.toplaintime */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeToPlainTime)
/* Temporal #sec-temporal.zoneddatetime.prototype.toplaindatetime */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeToPlainDateTime)
/* Temporal.Duration */
/* Temporal #sec-temporal.duration.from */
TO_BE_IMPLEMENTED(TemporalDurationFrom)
/* Temporal #sec-temporal.duration.compare */
TO_BE_IMPLEMENTED(TemporalDurationCompare)
/* Temporal #sec-temporal.duration.prototype.with */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeWith)
/* Temporal #sec-temporal.duration.prototype.add */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeAdd)
/* Temporal #sec-temporal.duration.prototype.subtract */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeSubtract)
/* Temporal #sec-temporal.duration.prototype.round */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeRound)
/* Temporal #sec-temporal.duration.prototype.total */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeTotal)
/* Temporal #sec-temporal.duration.prototype.tostring */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeToString)
/* Temporal #sec-temporal.duration.tojson */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeToJSON)
/* Temporal.Instant */
/* Temporal #sec-temporal.instant.compare */
TO_BE_IMPLEMENTED(TemporalInstantCompare)
/* Temporal #sec-temporal.instant.prototype.add */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeAdd)
/* Temporal #sec-temporal.instant.prototype.subtract */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeSubtract)
/* Temporal #sec-temporal.instant.prototype.until */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeUntil)
/* Temporal #sec-temporal.instant.prototype.since */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeSince)
/* Temporal #sec-temporal.instant.prototype.round */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeRound)
/* Temporal #sec-temporal.instant.prototype.equals */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeEquals)
/* Temporal #sec-temporal.instant.prototype.tostring */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeToString)
/* Temporal #sec-temporal.instant.tojson */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeToJSON)
/* Temporal #sec-temporal.instant.prototype.tozoneddatetime */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeToZonedDateTime)
/* Temporal #sec-temporal.instant.prototype.tozoneddatetimeiso */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeToZonedDateTimeISO)
/* Temporal.PlainYearMonth */
/* Temporal #sec-temporal.plainyearmonth.from */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthFrom)
/* Temporal #sec-temporal.plainyearmonth.compare */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthCompare)
/* Temporal #sec-temporal.plainyearmonth.prototype.with */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeWith)
/* Temporal #sec-temporal.plainyearmonth.prototype.add */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeAdd)
/* Temporal #sec-temporal.plainyearmonth.prototype.subtract */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeSubtract)
/* Temporal #sec-temporal.plainyearmonth.prototype.until */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeUntil)
/* Temporal #sec-temporal.plainyearmonth.prototype.since */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeSince)
/* Temporal #sec-temporal.plainyearmonth.prototype.equals */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeEquals)
/* Temporal #sec-temporal.plainyearmonth.tostring */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeToString)
/* Temporal #sec-temporal.plainyearmonth.tojson */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeToJSON)
/* Temporal #sec-temporal.plainyearmonth.prototype.toplaindate */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeToPlainDate)
/* Temporal.PlainMonthDay */
/* Temporal #sec-temporal.plainmonthday.from */
TO_BE_IMPLEMENTED(TemporalPlainMonthDayFrom)
/* There is no compare for PlainMonthDay. See
* https://github.com/tc39/proposal-temporal/issues/1547 */
/* Temporal #sec-temporal.plainmonthday.prototype.with */
TO_BE_IMPLEMENTED(TemporalPlainMonthDayPrototypeWith)
/* Temporal #sec-temporal.plainmonthday.prototype.equals */
TO_BE_IMPLEMENTED(TemporalPlainMonthDayPrototypeEquals)
/* Temporal #sec-temporal.plainmonthday.prototype.tostring */
TO_BE_IMPLEMENTED(TemporalPlainMonthDayPrototypeToString)
/* Temporal #sec-temporal.plainmonthday.tojson */
TO_BE_IMPLEMENTED(TemporalPlainMonthDayPrototypeToJSON)
/* Temporal #sec-temporal.plainmonthday.prototype.toplaindate */
TO_BE_IMPLEMENTED(TemporalPlainMonthDayPrototypeToPlainDate)
/* Temporal.TimeZone */
/* Temporal #sec-temporal.timezone.prototype.getoffsetnanosecondsfor */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeGetOffsetNanosecondsFor)
/* Temporal #sec-temporal.timezone.prototype.getoffsetstringfor */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeGetOffsetStringFor)
/* Temporal #sec-temporal.timezone.prototype.getplaindatetimefor */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeGetPlainDateTimeFor)
/* Temporal #sec-temporal.timezone.prototype.getinstantfor */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeGetInstantFor)
/* Temporal #sec-temporal.timezone.prototype.getpossibleinstantsfor */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeGetPossibleInstantsFor)
/* Temporal #sec-temporal.timezone.prototype.getnexttransition */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeGetNextTransition)
/* Temporal #sec-temporal.timezone.prototype.getprevioustransition */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeGetPreviousTransition)
/* Temporal #sec-temporal.timezone.prototype.tojson */
TO_BE_IMPLEMENTED(TemporalTimeZonePrototypeToJSON)
/* Temporal.Calendar */
/* Temporal #sec-temporal.calendar.prototype.yearmonthfromfields */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeYearMonthFromFields)
/* Temporal #sec-temporal.calendar.prototype.monthdayfromfields */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeMonthDayFromFields)
/* Temporal #sec-temporal.calendar.prototype.dateadd */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeDateAdd)
/* Temporal #sec-temporal.calendar.prototype.dateuntil */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeDateUntil)
/* Temporal #sec-temporal.calendar.prototype.month */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeMonth)
/* Temporal #sec-temporal.calendar.prototype.monthcode */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeMonthCode)
/* Temporal #sec-temporal.calendar.prototype.day */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeDay)
/* Temporal #sec-temporal.calendar.prototype.weekofyear */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeWeekOfYear)
/* Temporal #sec-temporal.calendar.prototype.tojson */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeToJSON)
// to be switch to TFJ later
/* Temporal #sec-temporal.calendar.prototype.fields */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeFields)
#ifdef V8_INTL_SUPPORT
/* Temporal */
/* Temporal #sec-temporal.calendar.prototype.era */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeEra)
/* Temporal #sec-temporal.calendar.prototype.erayear */
TO_BE_IMPLEMENTED(TemporalCalendarPrototypeEraYear)
/* Temporal #sec-temporal.duration.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalDurationPrototypeToLocaleString)
/* Temporal #sec-temporal.instant.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalInstantPrototypeToLocaleString)
/* Temporal #sec-temporal.plaindate.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalPlainDatePrototypeToLocaleString)
/* Temporal #sec-temporal.plaindatetime.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalPlainDateTimePrototypeToLocaleString)
/* Temporal #sec-temporal.plainmonthday.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalPlainMonthDayPrototypeToLocaleString)
/* Temporal #sec-temporal.plaintime.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalPlainTimePrototypeToLocaleString)
/* Temporal #sec-temporal.plainyearmonth.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalPlainYearMonthPrototypeToLocaleString)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.era */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeEra)
/* Temporal #sec-get-temporal.zoneddatetime.prototype.erayear */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeEraYear)
/* Temporal #sec-temporal.zoneddatetime.prototype.tolocalestring */
TO_BE_IMPLEMENTED(TemporalZonedDateTimePrototypeToLocaleString)
#endif // V8_INTL_SUPPORT
#define TEMPORAL_CONSTRUCTOR1(T) \
BUILTIN(Temporal##T##Constructor) { \
HandleScope scope(isolate); \
RETURN_RESULT_OR_FAILURE( \
isolate, \
JSTemporal##T::Constructor(isolate, args.target(), args.new_target(), \
args.atOrUndefined(isolate, 1))); \
}
#define TEMPORAL_ID_BY_TO_STRING(T) \
BUILTIN(Temporal##T##PrototypeId) { \
HandleScope scope(isolate); \
Handle<String> id; \
ASSIGN_RETURN_FAILURE_ON_EXCEPTION( \
isolate, id, Object::ToString(isolate, args.receiver())); \
return *id; \
}
#define TEMPORAL_TO_STRING(T) \
BUILTIN(Temporal##T##PrototypeToString) { \
HandleScope scope(isolate); \
const char* method = "Temporal." #T ".prototype.toString"; \
CHECK_RECEIVER(JSTemporal##T, t, method); \
Handle<Object> ret; \
ASSIGN_RETURN_FAILURE_ON_EXCEPTION( \
isolate, ret, JSTemporal##T::ToString(isolate, t, method)); \
return *ret; \
}
#define TEMPORAL_PROTOTYPE_METHOD0(T, METHOD, name) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "Temporal." #T ".prototype." #name; \
CHECK_RECEIVER(JSTemporal##T, obj, method); \
RETURN_RESULT_OR_FAILURE(isolate, JSTemporal##T ::METHOD(isolate, obj)); \
}
#define TEMPORAL_PROTOTYPE_METHOD1(T, METHOD, name) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "Temporal." #T ".prototype." #name; \
CHECK_RECEIVER(JSTemporal##T, obj, method); \
RETURN_RESULT_OR_FAILURE( \
isolate, \
JSTemporal##T ::METHOD(isolate, obj, args.atOrUndefined(isolate, 1))); \
}
#define TEMPORAL_PROTOTYPE_METHOD2(T, METHOD, name) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "Temporal." #T ".prototype." #name; \
CHECK_RECEIVER(JSTemporal##T, obj, method); \
RETURN_RESULT_OR_FAILURE( \
isolate, \
JSTemporal##T ::METHOD(isolate, obj, args.atOrUndefined(isolate, 1), \
args.atOrUndefined(isolate, 2))); \
}
#define TEMPORAL_PROTOTYPE_METHOD3(T, METHOD, name) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "Temporal." #T ".prototype." #name; \
CHECK_RECEIVER(JSTemporal##T, obj, method); \
RETURN_RESULT_OR_FAILURE( \
isolate, \
JSTemporal##T ::METHOD(isolate, obj, args.atOrUndefined(isolate, 1), \
args.atOrUndefined(isolate, 2), \
args.atOrUndefined(isolate, 3))); \
}
#define TEMPORAL_METHOD2(T, METHOD) \
BUILTIN(Temporal##T##METHOD) { \
HandleScope scope(isolate); \
RETURN_RESULT_OR_FAILURE( \
isolate, \
JSTemporal##T ::METHOD(isolate, args.atOrUndefined(isolate, 1), \
args.atOrUndefined(isolate, 2))); \
}
#define TEMPORAL_VALUE_OF(T) \
BUILTIN(Temporal##T##PrototypeValueOf) { \
HandleScope scope(isolate); \
THROW_NEW_ERROR_RETURN_FAILURE( \
isolate, NewTypeError(MessageTemplate::kDoNotUse, \
isolate->factory()->NewStringFromAsciiChecked( \
"Temporal." #T ".prototype.valueOf"), \
isolate->factory()->NewStringFromAsciiChecked( \
"use Temporal." #T \
".prototype.compare for comparison."))); \
}
#define TEMPORAL_GET_SMI(T, METHOD, field) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "get Temporal." #T ".prototype." #field; \
CHECK_RECEIVER(JSTemporal##T, obj, method); \
return Smi::FromInt(obj->field()); \
}
#define TEMPORAL_METHOD1(T, METHOD) \
BUILTIN(Temporal##T##METHOD) { \
HandleScope scope(isolate); \
RETURN_RESULT_OR_FAILURE( \
isolate, \
JSTemporal##T ::METHOD(isolate, args.atOrUndefined(isolate, 1))); \
}
#define TEMPORAL_GET(T, METHOD, field) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "get Temporal." #T ".prototype." #field; \
CHECK_RECEIVER(JSTemporal##T, obj, method); \
return obj->field(); \
}
#define TEMPORAL_GET_NUMBER_AFTER_DIVID(T, M, field, scale, name) \
BUILTIN(Temporal##T##Prototype##M) { \
HandleScope scope(isolate); \
const char* method = "get Temporal." #T ".prototype." #name; \
CHECK_RECEIVER(JSTemporal##T, handle, method); \
Handle<BigInt> value; \
ASSIGN_RETURN_FAILURE_ON_EXCEPTION( \
isolate, value, \
BigInt::Divide(isolate, Handle<BigInt>(handle->field(), isolate), \
BigInt::FromUint64(isolate, scale))); \
Handle<Object> number = BigInt::ToNumber(isolate, value); \
DCHECK(std::isfinite(number->Number())); \
return *number; \
}
#define TEMPORAL_GET_BIGINT_AFTER_DIVID(T, M, field, scale, name) \
BUILTIN(Temporal##T##Prototype##M) { \
HandleScope scope(isolate); \
const char* method = "get Temporal." #T ".prototype." #name; \
CHECK_RECEIVER(JSTemporal##T, handle, method); \
Handle<BigInt> value; \
ASSIGN_RETURN_FAILURE_ON_EXCEPTION( \
isolate, value, \
BigInt::Divide(isolate, Handle<BigInt>(handle->field(), isolate), \
BigInt::FromUint64(isolate, scale))); \
return *value; \
}
#define TEMPORAL_GET_BY_FORWARD_CALENDAR(T, METHOD, name) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "get Temporal." #T ".prototype." #name; \
CHECK_RECEIVER(JSTemporal##T, temporal_date, method); \
Handle<JSReceiver> calendar = handle(temporal_date->calendar(), isolate); \
RETURN_RESULT_OR_FAILURE(isolate, temporal::Calendar##METHOD( \
isolate, calendar, temporal_date)); \
}
#define TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(T, METHOD, name) \
BUILTIN(Temporal##T##Prototype##METHOD) { \
HandleScope scope(isolate); \
const char* method = "get Temporal." #T ".prototype." #name; \
/* 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporal \
* #T]]). */ \
CHECK_RECEIVER(JSTemporal##T, date_like, method); \
/* 3. Let calendar be temporalDate.[[Calendar]]. */ \
Handle<JSReceiver> calendar = handle(date_like->calendar(), isolate); \
/* 2. Return ? Invoke(calendar, "name", « dateLike »). */ \
RETURN_RESULT_OR_FAILURE( \
isolate, temporal::InvokeCalendarMethod( \
isolate, calendar, isolate->factory()->name##_string(), \
date_like)); \
}
// Now
TEMPORAL_NOW0(TimeZone)
TEMPORAL_NOW0(Instant)
TEMPORAL_NOW2(PlainDateTime)
TEMPORAL_NOW_ISO1(PlainDateTime)
TEMPORAL_NOW2(PlainDate)
TEMPORAL_NOW_ISO1(PlainDate)
// There is NO Temporal.now.plainTime
// See https://github.com/tc39/proposal-temporal/issues/1540
TEMPORAL_NOW_ISO1(PlainTime)
TEMPORAL_NOW2(ZonedDateTime)
TEMPORAL_NOW_ISO1(ZonedDateTime)
// PlainDate
BUILTIN(TemporalPlainDateConstructor) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(
isolate, JSTemporalPlainDate::Constructor(
isolate, args.target(), args.new_target(),
args.atOrUndefined(isolate, 1), // iso_year
args.atOrUndefined(isolate, 2), // iso_month
args.atOrUndefined(isolate, 3), // iso_day
args.atOrUndefined(isolate, 4))); // calendar_like
}
TEMPORAL_METHOD2(PlainDate, From)
TEMPORAL_GET(PlainDate, Calendar, calendar)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDate, Year, year)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDate, Month, month)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDate, MonthCode, monthCode)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDate, Day, day)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, DayOfWeek, dayOfWeek)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, DayOfYear, dayOfYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, WeekOfYear, weekOfYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, DaysInWeek, daysInWeek)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, DaysInMonth, daysInMonth)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, DaysInYear, daysInYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, MonthsInYear, monthsInYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDate, InLeapYear, inLeapYear)
TEMPORAL_PROTOTYPE_METHOD1(PlainDate, WithCalendar, withCalendar)
TEMPORAL_PROTOTYPE_METHOD0(PlainDate, GetISOFields, getISOFields)
TEMPORAL_VALUE_OF(PlainDate)
// PlainTime
BUILTIN(TemporalPlainTimeConstructor) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(isolate,
JSTemporalPlainTime::Constructor(
isolate, args.target(), args.new_target(),
args.atOrUndefined(isolate, 1), // hour
args.atOrUndefined(isolate, 2), // minute
args.atOrUndefined(isolate, 3), // second
args.atOrUndefined(isolate, 4), // millisecond
args.atOrUndefined(isolate, 5), // microsecond
args.atOrUndefined(isolate, 6))); // nanosecond
}
TEMPORAL_GET(PlainTime, Calendar, calendar)
TEMPORAL_GET_SMI(PlainTime, Hour, iso_hour)
TEMPORAL_GET_SMI(PlainTime, Minute, iso_minute)
TEMPORAL_GET_SMI(PlainTime, Second, iso_second)
TEMPORAL_GET_SMI(PlainTime, Millisecond, iso_millisecond)
TEMPORAL_GET_SMI(PlainTime, Microsecond, iso_microsecond)
TEMPORAL_GET_SMI(PlainTime, Nanosecond, iso_nanosecond)
TEMPORAL_METHOD2(PlainTime, From)
TEMPORAL_PROTOTYPE_METHOD0(PlainTime, GetISOFields, getISOFields)
TEMPORAL_VALUE_OF(PlainTime)
// PlainDateTime
BUILTIN(TemporalPlainDateTimeConstructor) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(
isolate, JSTemporalPlainDateTime::Constructor(
isolate, args.target(), args.new_target(),
args.atOrUndefined(isolate, 1), // iso_year
args.atOrUndefined(isolate, 2), // iso_month
args.atOrUndefined(isolate, 3), // iso_day
args.atOrUndefined(isolate, 4), // hour
args.atOrUndefined(isolate, 5), // minute
args.atOrUndefined(isolate, 6), // second
args.atOrUndefined(isolate, 7), // millisecond
args.atOrUndefined(isolate, 8), // microsecond
args.atOrUndefined(isolate, 9), // nanosecond
args.atOrUndefined(isolate, 10))); // calendar_like
}
TEMPORAL_GET(PlainDateTime, Calendar, calendar)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDateTime, Year, year)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDateTime, Month, month)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDateTime, MonthCode, monthCode)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDateTime, Day, day)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, DayOfWeek, dayOfWeek)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, DayOfYear, dayOfYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, WeekOfYear, weekOfYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, DaysInWeek, daysInWeek)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, DaysInMonth, daysInMonth)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, DaysInYear, daysInYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, MonthsInYear,
monthsInYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainDateTime, InLeapYear, inLeapYear)
TEMPORAL_PROTOTYPE_METHOD1(PlainDateTime, WithCalendar, withCalendar)
TEMPORAL_GET_SMI(PlainDateTime, Hour, iso_hour)
TEMPORAL_GET_SMI(PlainDateTime, Minute, iso_minute)
TEMPORAL_GET_SMI(PlainDateTime, Second, iso_second)
TEMPORAL_GET_SMI(PlainDateTime, Millisecond, iso_millisecond)
TEMPORAL_GET_SMI(PlainDateTime, Microsecond, iso_microsecond)
TEMPORAL_GET_SMI(PlainDateTime, Nanosecond, iso_nanosecond)
TEMPORAL_PROTOTYPE_METHOD0(PlainDateTime, GetISOFields, getISOFields)
TEMPORAL_VALUE_OF(PlainDateTime)
// PlainYearMonth
BUILTIN(TemporalPlainYearMonthConstructor) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(
isolate, JSTemporalPlainYearMonth::Constructor(
isolate, args.target(), args.new_target(),
args.atOrUndefined(isolate, 1), // iso_year
args.atOrUndefined(isolate, 2), // iso_month
args.atOrUndefined(isolate, 3), // calendar_like
args.atOrUndefined(isolate, 4))); // reference_iso_day
}
TEMPORAL_GET(PlainYearMonth, Calendar, calendar)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainYearMonth, Year, year)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainYearMonth, Month, month)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainYearMonth, MonthCode, monthCode)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainYearMonth, DaysInYear, daysInYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainYearMonth, DaysInMonth, daysInMonth)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainYearMonth, MonthsInYear,
monthsInYear)
TEMPORAL_GET_BY_INVOKE_CALENDAR_METHOD(PlainYearMonth, InLeapYear, inLeapYear)
TEMPORAL_PROTOTYPE_METHOD0(PlainYearMonth, GetISOFields, getISOFields)
TEMPORAL_VALUE_OF(PlainYearMonth)
// PlainMonthDay
BUILTIN(TemporalPlainMonthDayConstructor) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(
isolate, JSTemporalPlainMonthDay::Constructor(
isolate, args.target(), args.new_target(),
args.atOrUndefined(isolate, 1), // iso_month
args.atOrUndefined(isolate, 2), // iso_day
args.atOrUndefined(isolate, 3), // calendar_like
args.atOrUndefined(isolate, 4))); // reference_iso_year
}
TEMPORAL_GET(PlainMonthDay, Calendar, calendar)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainMonthDay, MonthCode, monthCode)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainMonthDay, Day, day)
TEMPORAL_PROTOTYPE_METHOD0(PlainMonthDay, GetISOFields, getISOFields)
TEMPORAL_VALUE_OF(PlainMonthDay)
// ZonedDateTime
#define TEMPORAL_ZONED_DATE_TIME_GET_PREPARE(M) \
HandleScope scope(isolate); \
const char* method = "get Temporal.ZonedDateTime.prototype." #M; \
/* 1. Let zonedDateTime be the this value. */ \
/* 2. Perform ? RequireInternalSlot(zonedDateTime, */ \
/* [[InitializedTemporalZonedDateTime]]). */ \
CHECK_RECEIVER(JSTemporalZonedDateTime, zoned_date_time, method); \
/* 3. Let timeZone be zonedDateTime.[[TimeZone]]. */ \
Handle<JSReceiver> time_zone = \
handle(zoned_date_time->time_zone(), isolate); \
/* 4. Let instant be ? */ \
/* CreateTemporalInstant(zonedDateTime.[[Nanoseconds]]). */ \
Handle<JSTemporalInstant> instant; \
ASSIGN_RETURN_FAILURE_ON_EXCEPTION( \
isolate, instant, \
temporal::CreateTemporalInstant( \
isolate, Handle<BigInt>(zoned_date_time->nanoseconds(), isolate))); \
/* 5. Let calendar be zonedDateTime.[[Calendar]]. */ \
Handle<JSReceiver> calendar = handle(zoned_date_time->calendar(), isolate); \
/* 6. Let temporalDateTime be ? */ \
/* BuiltinTimeZoneGetPlainDateTimeFor(timeZone, */ \
/* instant, calendar). */ \
Handle<JSTemporalPlainDateTime> temporal_date_time; \
ASSIGN_RETURN_FAILURE_ON_EXCEPTION( \
isolate, temporal_date_time, \
temporal::BuiltinTimeZoneGetPlainDateTimeFor( \
isolate, time_zone, instant, calendar, method));
#define TEMPORAL_ZONED_DATE_TIME_GET_INT_BY_FORWARD_TIME_ZONE(M, field) \
BUILTIN(TemporalZonedDateTimePrototype##M) { \
TEMPORAL_ZONED_DATE_TIME_GET_PREPARE(M) \
/* 7. Return 𝔽(temporalDateTime.[[ #field ]]). */ \
return Smi::FromInt(temporal_date_time->field()); \
}
BUILTIN(TemporalZonedDateTimeConstructor) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(
isolate, JSTemporalZonedDateTime::Constructor(
isolate, args.target(), args.new_target(),
args.atOrUndefined(isolate, 1), // epoch_nanoseconds
args.atOrUndefined(isolate, 2), // time_zone_like
args.atOrUndefined(isolate, 3))); // calendar_like
}
TEMPORAL_GET(ZonedDateTime, Calendar, calendar)
TEMPORAL_GET(ZonedDateTime, TimeZone, time_zone)
TEMPORAL_GET(ZonedDateTime, EpochNanoseconds, nanoseconds)
TEMPORAL_GET_NUMBER_AFTER_DIVID(ZonedDateTime, EpochSeconds, nanoseconds,
1000000000, epochSeconds)
TEMPORAL_GET_NUMBER_AFTER_DIVID(ZonedDateTime, EpochMilliseconds, nanoseconds,
1000000, epochMilliseconds)
TEMPORAL_GET_BIGINT_AFTER_DIVID(ZonedDateTime, EpochMicroseconds, nanoseconds,
1000, epochMicroseconds)
TEMPORAL_ZONED_DATE_TIME_GET_INT_BY_FORWARD_TIME_ZONE(Hour, iso_hour)
TEMPORAL_ZONED_DATE_TIME_GET_INT_BY_FORWARD_TIME_ZONE(Minute, iso_minute)
TEMPORAL_ZONED_DATE_TIME_GET_INT_BY_FORWARD_TIME_ZONE(Second, iso_second)
TEMPORAL_ZONED_DATE_TIME_GET_INT_BY_FORWARD_TIME_ZONE(Millisecond,
iso_millisecond)
TEMPORAL_ZONED_DATE_TIME_GET_INT_BY_FORWARD_TIME_ZONE(Microsecond,
iso_microsecond)
TEMPORAL_ZONED_DATE_TIME_GET_INT_BY_FORWARD_TIME_ZONE(Nanosecond,
iso_nanosecond)
TEMPORAL_PROTOTYPE_METHOD1(ZonedDateTime, WithCalendar, withCalendar)
TEMPORAL_PROTOTYPE_METHOD1(ZonedDateTime, WithTimeZone, withTimeZone)
TEMPORAL_PROTOTYPE_METHOD0(ZonedDateTime, ToPlainYearMonth, toPlainYearMonth)
TEMPORAL_PROTOTYPE_METHOD0(ZonedDateTime, ToPlainMonthDay, toPlainMonthDay)
TEMPORAL_PROTOTYPE_METHOD0(ZonedDateTime, GetISOFields, getISOFields)
TEMPORAL_VALUE_OF(ZonedDateTime)
// Duration
BUILTIN(TemporalDurationConstructor) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(
isolate, JSTemporalDuration::Constructor(
isolate, args.target(), args.new_target(),
args.atOrUndefined(isolate, 1), // years
args.atOrUndefined(isolate, 2), // months
args.atOrUndefined(isolate, 3), // weeks
args.atOrUndefined(isolate, 4), // days
args.atOrUndefined(isolate, 5), // hours
args.atOrUndefined(isolate, 6), // minutes
args.atOrUndefined(isolate, 7), // seconds
args.atOrUndefined(isolate, 8), // milliseconds
args.atOrUndefined(isolate, 9), // microseconds
args.atOrUndefined(isolate, 10))); // nanoseconds
}
TEMPORAL_GET(Duration, Years, years)
TEMPORAL_GET(Duration, Months, months)
TEMPORAL_GET(Duration, Weeks, weeks)
TEMPORAL_GET(Duration, Days, days)
TEMPORAL_GET(Duration, Hours, hours)
TEMPORAL_GET(Duration, Minutes, minutes)
TEMPORAL_GET(Duration, Seconds, seconds)
TEMPORAL_GET(Duration, Milliseconds, milliseconds)
TEMPORAL_GET(Duration, Microseconds, microseconds)
TEMPORAL_GET(Duration, Nanoseconds, nanoseconds)
TEMPORAL_PROTOTYPE_METHOD0(Duration, Sign, sign)
TEMPORAL_PROTOTYPE_METHOD0(Duration, Blank, blank)
TEMPORAL_PROTOTYPE_METHOD0(Duration, Negated, negated)
TEMPORAL_PROTOTYPE_METHOD0(Duration, Abs, abs)
TEMPORAL_VALUE_OF(Duration)
// Instant
TEMPORAL_CONSTRUCTOR1(Instant)
TEMPORAL_METHOD1(Instant, FromEpochSeconds)
TEMPORAL_METHOD1(Instant, FromEpochMilliseconds)
TEMPORAL_METHOD1(Instant, FromEpochMicroseconds)
TEMPORAL_METHOD1(Instant, FromEpochNanoseconds)
TEMPORAL_METHOD1(Instant, From)
TEMPORAL_VALUE_OF(Instant)
TEMPORAL_GET(Instant, EpochNanoseconds, nanoseconds)
TEMPORAL_GET_NUMBER_AFTER_DIVID(Instant, EpochSeconds, nanoseconds, 1000000000,
epochSeconds)
TEMPORAL_GET_NUMBER_AFTER_DIVID(Instant, EpochMilliseconds, nanoseconds,
1000000, epochMilliseconds)
TEMPORAL_GET_BIGINT_AFTER_DIVID(Instant, EpochMicroseconds, nanoseconds, 1000,
epochMicroseconds)
// Calendar
TEMPORAL_CONSTRUCTOR1(Calendar)
TEMPORAL_ID_BY_TO_STRING(Calendar)
TEMPORAL_PROTOTYPE_METHOD2(Calendar, DateFromFields, dateFromFields)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, DaysInMonth, daysInMonth)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, DaysInWeek, daysInWeek)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, DaysInYear, daysInYear)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, DayOfWeek, dayOfWeek)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, DayOfYear, dayOfYear)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, InLeapYear, inLeapYear)
TEMPORAL_PROTOTYPE_METHOD2(Calendar, MergeFields, mergeFields)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, MonthsInYear, monthsInYear)
TEMPORAL_PROTOTYPE_METHOD1(Calendar, Year, year)
TEMPORAL_TO_STRING(Calendar)
// #sec-temporal.calendar.from
BUILTIN(TemporalCalendarFrom) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(isolate, temporal::ToTemporalCalendar(
isolate, args.atOrUndefined(isolate, 1),
"Temporal.Calendar.from"));
}
// TimeZone
TEMPORAL_CONSTRUCTOR1(TimeZone)
TEMPORAL_ID_BY_TO_STRING(TimeZone)
TEMPORAL_TO_STRING(TimeZone)
// #sec-temporal.timezone.from
BUILTIN(TemporalTimeZoneFrom) {
HandleScope scope(isolate);
RETURN_RESULT_OR_FAILURE(isolate, temporal::ToTemporalTimeZone(
isolate, args.atOrUndefined(isolate, 1),
"Temporal.TimeZone.from"));
}
#ifdef V8_INTL_SUPPORT
// get Temporal.*.prototype.era/eraYear
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDate, Era, era)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDate, EraYear, eraYear)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDateTime, Era, era)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainDateTime, EraYear, eraYear)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainYearMonth, Era, era)
TEMPORAL_GET_BY_FORWARD_CALENDAR(PlainYearMonth, EraYear, eraYear)
#endif // V8_INTL_SUPPORT
} // namespace internal
} // namespace v8
|
// Copyright © 2017-2021 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include <TrustWalletCore/TWTHORChainSwap.h>
#include "proto/THORChainSwap.pb.h"
#include "proto/Ethereum.pb.h"
#include "proto/Binance.pb.h"
#include "Bitcoin/SegwitAddress.h"
#include "Bitcoin/Script.h"
#include <TrustWalletCore/TWCoinType.h>
#include <TrustWalletCore/TWAnySigner.h>
#include "PrivateKey.h"
#include "HexCoding.h"
#include "uint256.h"
#include "../interface/TWTestUtilities.h"
#include <gtest/gtest.h>
using namespace TW::THORChainSwap;
using namespace TW;
const auto Address1Bnb = "bnb1us47wdhfx08ch97zdueh3x3u5murfrx30jecrx";
const auto Address1Btc = "bc1qpjult34k9spjfym8hss2jrwjgf0xjf40ze0pp8";
const auto Address1Eth = "0xb9f5771c27664bf2282d98e09d7f50cec7cb01a7";
const auto VaultBnb = "bnb1n9esxuw8ca7ts8l6w66kdh800s09msvul6vlse";
const auto VaultBtc = "bc1q6m9u2qsu8mh8y7v8rr2ywavtj8g5arzlyhcej7";
const auto VaultEth = "0x1091c4De6a3cF09CdA00AbDAeD42c7c3B69C83EC";
const auto RouterEth = "0x42A5Ed456650a09Dc10EBc6361A7480fDd61f27B";
const Data TestKey1Bnb = parse_hex("bcf8b072560dda05122c99390def2c385ec400e1a93df0657a85cf6b57a715da");
const Data TestKey1Btc = parse_hex("13fcaabaf9e71ffaf915e242ec58a743d55f102cf836968e5bd4881135e0c52c");
const Data TestKey1Eth = parse_hex("4f96ed80e9a7555a6f74b3d658afdd9c756b0a40d4ca30c42c2039eb449bb904");
TEST(TWTHORChainSwap, SwapBtcToEth) {
// prepare swap input
Proto::SwapInput input;
input.set_from_chain(Proto::BTC);
input.set_from_address(Address1Btc);
Proto::Asset toAsset;
toAsset.set_chain(Proto::ETH);
toAsset.set_symbol("ETH");
toAsset.set_token_id("");
*input.mutable_to_asset() = toAsset;
input.set_to_address(Address1Eth);
input.set_vault_address(VaultBtc);
input.set_router_address("");
input.set_from_amount("1000000");
input.set_to_amount_limit("140000000000000000");
// serialize input
const auto inputData = input.SerializeAsString();
EXPECT_EQ(hex(inputData), "0801122a62633171706a756c7433346b3973706a66796d38687373326a72776a676630786a6634307a65307070381a0708021203455448222a3078623966353737316332373636346266323238326439386530396437663530636563376362303161372a2a62633171366d397532717375386d68387937763872723279776176746a38673561727a6c796863656a373a07313030303030304212313430303030303030303030303030303030");
const auto inputTWData = WRAPD(TWDataCreateWithBytes((const uint8_t *)inputData.data(), inputData.size()));
// invoke swap
const auto outputTWData = WRAPD(TWTHORChainSwapBuildSwap(inputTWData.get()));
const auto outputData = data(TWDataBytes(outputTWData.get()), TWDataSize(outputTWData.get()));
EXPECT_EQ(outputData.size(), 178);
// parse result in proto
Proto::SwapOutput outputProto;
EXPECT_TRUE(outputProto.ParseFromArray(outputData.data(), static_cast<int>(outputData.size())));
EXPECT_EQ(outputProto.from_chain(), Proto::BTC);
EXPECT_EQ(outputProto.to_chain(), Proto::ETH);
EXPECT_EQ(outputProto.error().code(), 0);
EXPECT_EQ(outputProto.error().message(), "");
EXPECT_TRUE(outputProto.has_bitcoin());
Bitcoin::Proto::SigningInput txInput = outputProto.bitcoin();
// tx input: check some fields
EXPECT_EQ(txInput.amount(), 1000000);
EXPECT_EQ(txInput.to_address(), "bc1q6m9u2qsu8mh8y7v8rr2ywavtj8g5arzlyhcej7");
EXPECT_EQ(txInput.change_address(), "bc1qpjult34k9spjfym8hss2jrwjgf0xjf40ze0pp8");
EXPECT_EQ(txInput.output_op_return(), "=:ETH.ETH:0xb9f5771c27664bf2282d98e09d7f50cec7cb01a7:140000000000000000");
EXPECT_EQ(txInput.coin_type(), 0);
// sign tx input for signed full tx
// set few fields before signing
txInput.set_byte_fee(20);
EXPECT_EQ(Bitcoin::SegwitAddress(PrivateKey(TestKey1Btc).getPublicKey(TWPublicKeyTypeSECP256k1), 0, "bc").string(), Address1Btc);
txInput.add_private_key(TestKey1Btc.data(), TestKey1Btc.size());
auto& utxo = *txInput.add_utxo();
Data utxoHash = parse_hex("1234000000000000000000000000000000000000000000000000000000005678");
utxo.mutable_out_point()->set_hash(utxoHash.data(), utxoHash.size());
utxo.mutable_out_point()->set_index(0);
utxo.mutable_out_point()->set_sequence(UINT32_MAX);
auto utxoScript = Bitcoin::Script::lockScriptForAddress(Address1Btc, TWCoinTypeBitcoin);
utxo.set_script(utxoScript.bytes.data(), utxoScript.bytes.size());
utxo.set_amount(50000000);
txInput.set_use_max_amount(false);
// sign and encode resulting input
{
Bitcoin::Proto::SigningOutput output;
ANY_SIGN(txInput, TWCoinTypeBitcoin);
EXPECT_EQ(output.error(), 0);
EXPECT_EQ(hex(output.encoded()), // printed using prettyPrintTransaction
"01000000" // version
"0001" // marker & flag
"01" // inputs
"1234000000000000000000000000000000000000000000000000000000005678" "00000000" "00" "" "ffffffff"
"03" // outputs
"40420f0000000000" "16" "0014d6cbc5021c3eee72798718d447758b91d14e8c5f"
"609deb0200000000" "16" "00140cb9f5c6b62c03249367bc20a90dd2425e6926af"
"0000000000000000" "42" "6a403d3a4554482e4554483a3078623966353737316332373636346266323238326439386530396437663530636563376362303161373a3134303030303030303030"
// witness
"02"
"47" "304402205de19c68b5ea683b9d701d45b09f96658088db76e59ad27bd7b8383ee5d484ec0220245459a4d6d679d8b457564fccc7ecc5831c7ebed49e0366c65ac031e8a5b49201"
"21" "021e582a887bd94d648a9267143eb600449a8d59a0db0653740b1378067a6d0cee"
"00000000" // nLockTime
);
}
}
TEST(TWTHORChainSwap, SwapEthBnb) {
// prepare swap input
Proto::SwapInput input;
input.set_from_chain(Proto::ETH);
input.set_from_address(Address1Eth);
Proto::Asset toAsset;
toAsset.set_chain(Proto::BNB);
toAsset.set_symbol("BNB");
toAsset.set_token_id("");
*input.mutable_to_asset() = toAsset;
input.set_to_address(Address1Bnb);
input.set_vault_address(VaultEth);
input.set_router_address(RouterEth);
input.set_from_amount("50000000000000000");
input.set_to_amount_limit("600003");
// serialize input
const auto inputData = input.SerializeAsString();
EXPECT_EQ(hex(inputData), "0802122a3078623966353737316332373636346266323238326439386530396437663530636563376362303161371a0708031203424e42222a626e62317573343777646866783038636839377a6475656833783375356d757266727833306a656372782a2a307831303931633444653661336346303943644130304162444165443432633763334236394338334543322a3078343241354564343536363530613039446331304542633633363141373438306644643631663237423a1135303030303030303030303030303030304206363030303033");
const auto inputTWData = WRAPD(TWDataCreateWithBytes((const uint8_t *)inputData.data(), inputData.size()));
// invoke swap
const auto outputTWData = WRAPD(TWTHORChainSwapBuildSwap(inputTWData.get()));
const auto outputData = data(TWDataBytes(outputTWData.get()), TWDataSize(outputTWData.get()));
EXPECT_EQ(outputData.size(), 311);
// parse result in proto
Proto::SwapOutput outputProto;
EXPECT_TRUE(outputProto.ParseFromArray(outputData.data(), static_cast<int>(outputData.size())));
EXPECT_EQ(outputProto.from_chain(), Proto::ETH);
EXPECT_EQ(outputProto.to_chain(), Proto::BNB);
EXPECT_EQ(outputProto.error().code(), 0);
EXPECT_EQ(outputProto.error().message(), "");
EXPECT_TRUE(outputProto.has_ethereum());
Ethereum::Proto::SigningInput txInput = outputProto.ethereum();
// sign tx input for signed full tx
// set few fields before signing
auto chainId = store(uint256_t(1));
txInput.set_chain_id(chainId.data(), chainId.size());
auto nonce = store(uint256_t(3));
txInput.set_nonce(nonce.data(), nonce.size());
auto gasPrice = store(uint256_t(30000000000));
txInput.set_gas_price(gasPrice.data(), gasPrice.size());
auto gasLimit = store(uint256_t(80000));
txInput.set_gas_limit(gasLimit.data(), gasLimit.size());
txInput.set_private_key("");
txInput.set_private_key(TestKey1Eth.data(), TestKey1Eth.size());
// sign and encode resulting input
Ethereum::Proto::SigningOutput output;
ANY_SIGN(txInput, TWCoinTypeEthereum);
EXPECT_EQ(hex(output.encoded()), "f90151038506fc23ac00830138809442a5ed456650a09dc10ebc6361a7480fdd61f27b87b1a2bc2ec50000b8e41fece7b40000000000000000000000001091c4de6a3cf09cda00abdaed42c7c3b69c83ec000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b1a2bc2ec500000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000003e535741503a424e422e424e423a626e62317573343777646866783038636839377a6475656833783375356d757266727833306a656372783a363030303033000025a06ae104be3201baca38315352f81fac70ca4dd47339981914e64e91149813e780a066a3f0b2c44ddf5a96a38481274f623f552a593d723237d6742185f4885c0064");
}
TEST(TWTHORChainSwap, SwapBnbBtc) {
// prepare swap input
Proto::SwapInput input;
input.set_from_chain(Proto::BNB);
input.set_from_address(Address1Bnb);
Proto::Asset toAsset;
toAsset.set_chain(Proto::BTC);
toAsset.set_symbol("BTC");
toAsset.set_token_id("");
*input.mutable_to_asset() = toAsset;
input.set_to_address(Address1Btc);
input.set_vault_address(VaultBnb);
input.set_router_address("");
input.set_from_amount("10000000");
input.set_to_amount_limit("10000000");
// serialize input
const auto inputData = input.SerializeAsString();
EXPECT_EQ(hex(inputData), "0803122a626e62317573343777646866783038636839377a6475656833783375356d757266727833306a656372781a0708011203425443222a62633171706a756c7433346b3973706a66796d38687373326a72776a676630786a6634307a65307070382a2a626e62316e396573787577386361377473386c367736366b64683830307330396d7376756c36766c73653a08313030303030303042083130303030303030");
const auto inputTWData = WRAPD(TWDataCreateWithBytes((const uint8_t *)inputData.data(), inputData.size()));
// invoke swap
const auto outputTWData = WRAPD(TWTHORChainSwapBuildSwap(inputTWData.get()));
const auto outputData = data(TWDataBytes(outputTWData.get()), TWDataSize(outputTWData.get()));
EXPECT_EQ(outputData.size(), 149);
// parse result in proto
Proto::SwapOutput outputProto;
EXPECT_TRUE(outputProto.ParseFromArray(outputData.data(), static_cast<int>(outputData.size())));
EXPECT_EQ(outputProto.from_chain(), Proto::BNB);
EXPECT_EQ(outputProto.to_chain(), Proto::BTC);
EXPECT_EQ(outputProto.error().code(), 0);
EXPECT_EQ(outputProto.error().message(), "");
EXPECT_TRUE(outputProto.has_binance());
Binance::Proto::SigningInput txInput = outputProto.binance();
// set few fields before signing
txInput.set_chain_id("Binance-Chain-Nile");
txInput.set_private_key(TestKey1Bnb.data(), TestKey1Bnb.size());
// sign and encode resulting input
Ethereum::Proto::SigningOutput output;
ANY_SIGN(txInput, TWCoinTypeBinance);
EXPECT_EQ(hex(output.encoded()), "8002f0625dee0a4c2a2c87fa0a220a14e42be736e933cf8b97c26f33789a3ca6f8348cd1120a0a03424e421080ade20412220a1499730371c7c77cb81ffa76b566dcef7c1e5dc19c120a0a03424e421080ade204126a0a26eb5ae9872103ea4b4bc12dc6f36a28d2c9775e01eef44def32cc70fb54f0e4177b659dbc0e1912404836ee8659caa86771281d3f104424d95977bdedf644ec8585f1674796fde525669a6d446f72da89ee90fb0e064473b0a2159a79630e081592c52948d03d67071a40535741503a4254432e4254433a62633171706a756c7433346b3973706a66796d38687373326a72776a676630786a6634307a65307070383a3130303030303030");
}
TEST(TWTHORChainSwap, NegativeInvalidInput) {
const auto inputData = parse_hex("00112233");
const auto inputTWData = WRAPD(TWDataCreateWithBytes((const uint8_t *)inputData.data(), inputData.size()));
const auto outputTWData = WRAPD(TWTHORChainSwapBuildSwap(inputTWData.get()));
const auto outputData = data(TWDataBytes(outputTWData.get()), TWDataSize(outputTWData.get()));
EXPECT_EQ(outputData.size(), 39);
EXPECT_EQ(hex(outputData), "1a2508021221436f756c64206e6f7420646573657269616c697a6520696e7075742070726f746f");
EXPECT_EQ(hex(data(std::string("Could not deserialize input proto"))), "436f756c64206e6f7420646573657269616c697a6520696e7075742070726f746f");
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: System.Security.Cryptography.X509Certificates
namespace System::Security::Cryptography::X509Certificates {
// Forward declaring type: X509KeyStorageFlags
struct X509KeyStorageFlags;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags, "System.Security.Cryptography.X509Certificates", "X509KeyStorageFlags");
// Type namespace: System.Security.Cryptography.X509Certificates
namespace System::Security::Cryptography::X509Certificates {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: System.Security.Cryptography.X509Certificates.X509KeyStorageFlags
// [TokenAttribute] Offset: FFFFFFFF
// [FlagsAttribute] Offset: FFFFFFFF
struct X509KeyStorageFlags/*, public System::Enum*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: X509KeyStorageFlags
constexpr X509KeyStorageFlags(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags DefaultKeySet
static constexpr const int DefaultKeySet = 0;
// Get static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags DefaultKeySet
static System::Security::Cryptography::X509Certificates::X509KeyStorageFlags _get_DefaultKeySet();
// Set static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags DefaultKeySet
static void _set_DefaultKeySet(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags value);
// static field const value: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags UserKeySet
static constexpr const int UserKeySet = 1;
// Get static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags UserKeySet
static System::Security::Cryptography::X509Certificates::X509KeyStorageFlags _get_UserKeySet();
// Set static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags UserKeySet
static void _set_UserKeySet(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags value);
// static field const value: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags MachineKeySet
static constexpr const int MachineKeySet = 2;
// Get static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags MachineKeySet
static System::Security::Cryptography::X509Certificates::X509KeyStorageFlags _get_MachineKeySet();
// Set static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags MachineKeySet
static void _set_MachineKeySet(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags value);
// static field const value: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags Exportable
static constexpr const int Exportable = 4;
// Get static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags Exportable
static System::Security::Cryptography::X509Certificates::X509KeyStorageFlags _get_Exportable();
// Set static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags Exportable
static void _set_Exportable(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags value);
// static field const value: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags UserProtected
static constexpr const int UserProtected = 8;
// Get static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags UserProtected
static System::Security::Cryptography::X509Certificates::X509KeyStorageFlags _get_UserProtected();
// Set static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags UserProtected
static void _set_UserProtected(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags value);
// static field const value: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags PersistKeySet
static constexpr const int PersistKeySet = 16;
// Get static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags PersistKeySet
static System::Security::Cryptography::X509Certificates::X509KeyStorageFlags _get_PersistKeySet();
// Set static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags PersistKeySet
static void _set_PersistKeySet(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags value);
// static field const value: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags EphemeralKeySet
static constexpr const int EphemeralKeySet = 32;
// Get static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags EphemeralKeySet
static System::Security::Cryptography::X509Certificates::X509KeyStorageFlags _get_EphemeralKeySet();
// Set static field: static public System.Security.Cryptography.X509Certificates.X509KeyStorageFlags EphemeralKeySet
static void _set_EphemeralKeySet(System::Security::Cryptography::X509Certificates::X509KeyStorageFlags value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // System.Security.Cryptography.X509Certificates.X509KeyStorageFlags
#pragma pack(pop)
static check_size<sizeof(X509KeyStorageFlags), 0 + sizeof(int)> __System_Security_Cryptography_X509Certificates_X509KeyStorageFlagsSizeCheck;
static_assert(sizeof(X509KeyStorageFlags) == 0x4);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
|
#include "ventilate_newuser.h"
#include "ui_ventilate_newuser.h"
#include <QDialog>
#include <QString>
#include <QMessageBox>
#include <QAbstractButton>
ventilate_newuser::ventilate_newuser(QWidget *parent) :
QDialog(parent),
ui(new Ui::ventilate_newuser)
{
ui->setupUi(this);
}
ventilate_newuser::~ventilate_newuser()
{
delete ui;
}
void ventilate_newuser::on_buttonBox_clicked(QAbstractButton *button)
{
if(button->text() == "Reset"){
ui->lnedConfirmEmail->clear();
ui->lnedConfirmPassword->clear();
ui->lnedEmail->clear();
ui->lnedPassword->clear();
ui->lnedUsername->clear();
ui->lblConfirmEmailContextInfo->clear();
ui->lblConfirmPasswordContextInfo->clear();
ui->lnedUsername->setFocus();
}
}
void ventilate_newuser::on_lnedUsername_textChanged(const QString &arg1)
{
if(arg1.length() >= 50){
ui->lblUsernameContextInfo->setText("<font color='#FFFFFF'>" + QString::number(64-arg1.length()) + " characters left.<font/>");
}else{
ui->lblUsernameContextInfo->setText("");
}
}
void ventilate_newuser::on_lnedConfirmPassword_textChanged(const QString &arg1)
{
if(arg1 != ui->lnedPassword->text()) ui->lblConfirmPasswordContextInfo->setText("<font color='#FFFFFF'>Passwords don't match.<font/>");
if(arg1 == ui->lnedPassword->text()) ui->lblConfirmPasswordContextInfo->setText("<font color='#FFFFFF'>Passwords match.<font/>");
}
void ventilate_newuser::on_lnedConfirmEmail_textChanged(const QString &arg1)
{
if(arg1 != ui->lnedEmail->text()) ui->lblConfirmEmailContextInfo->setText("<font color='#FFFFFF'>Emails don't match.<font/>");
if(arg1 == ui->lnedEmail->text()) ui->lblConfirmEmailContextInfo->setText("<font color='#FFFFFF'>Emails match.<font/>");
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "arrow/compute/kernels/common.h"
#include "arrow/util/int_util_internal.h"
#include "arrow/util/macros.h"
namespace arrow {
using internal::AddWithOverflow;
using internal::DivideWithOverflow;
using internal::MultiplyWithOverflow;
using internal::SubtractWithOverflow;
namespace compute {
namespace internal {
using applicator::ScalarBinaryEqualTypes;
using applicator::ScalarBinaryNotNullEqualTypes;
namespace {
template <typename T>
using is_unsigned_integer = std::integral_constant<bool, std::is_integral<T>::value &&
std::is_unsigned<T>::value>;
template <typename T>
using is_signed_integer =
std::integral_constant<bool, std::is_integral<T>::value && std::is_signed<T>::value>;
template <typename T>
using enable_if_signed_integer = enable_if_t<is_signed_integer<T>::value, T>;
template <typename T>
using enable_if_unsigned_integer = enable_if_t<is_unsigned_integer<T>::value, T>;
template <typename T>
using enable_if_integer =
enable_if_t<is_signed_integer<T>::value || is_unsigned_integer<T>::value, T>;
template <typename T>
using enable_if_floating_point = enable_if_t<std::is_floating_point<T>::value, T>;
template <typename T, typename Unsigned = typename std::make_unsigned<T>::type>
constexpr Unsigned to_unsigned(T signed_) {
return static_cast<Unsigned>(signed_);
}
struct Add {
template <typename T>
static constexpr enable_if_floating_point<T> Call(KernelContext*, T left, T right) {
return left + right;
}
template <typename T>
static constexpr enable_if_unsigned_integer<T> Call(KernelContext*, T left, T right) {
return left + right;
}
template <typename T>
static constexpr enable_if_signed_integer<T> Call(KernelContext*, T left, T right) {
return arrow::internal::SafeSignedAdd(left, right);
}
};
struct AddChecked {
template <typename T, typename Arg0, typename Arg1>
enable_if_integer<T> Call(KernelContext* ctx, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
T result = 0;
if (ARROW_PREDICT_FALSE(AddWithOverflow(left, right, &result))) {
ctx->SetStatus(Status::Invalid("overflow"));
}
return result;
}
template <typename T, typename Arg0, typename Arg1>
enable_if_floating_point<T> Call(KernelContext*, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
return left + right;
}
};
struct Subtract {
template <typename T>
static constexpr enable_if_floating_point<T> Call(KernelContext*, T left, T right) {
return left - right;
}
template <typename T>
static constexpr enable_if_unsigned_integer<T> Call(KernelContext*, T left, T right) {
return left - right;
}
template <typename T>
static constexpr enable_if_signed_integer<T> Call(KernelContext*, T left, T right) {
return arrow::internal::SafeSignedSubtract(left, right);
}
};
struct SubtractChecked {
template <typename T, typename Arg0, typename Arg1>
enable_if_integer<T> Call(KernelContext* ctx, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
T result = 0;
if (ARROW_PREDICT_FALSE(SubtractWithOverflow(left, right, &result))) {
ctx->SetStatus(Status::Invalid("overflow"));
}
return result;
}
template <typename T, typename Arg0, typename Arg1>
enable_if_floating_point<T> Call(KernelContext*, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
return left - right;
}
};
struct Multiply {
static_assert(std::is_same<decltype(int8_t() * int8_t()), int32_t>::value, "");
static_assert(std::is_same<decltype(uint8_t() * uint8_t()), int32_t>::value, "");
static_assert(std::is_same<decltype(int16_t() * int16_t()), int32_t>::value, "");
static_assert(std::is_same<decltype(uint16_t() * uint16_t()), int32_t>::value, "");
static_assert(std::is_same<decltype(int32_t() * int32_t()), int32_t>::value, "");
static_assert(std::is_same<decltype(uint32_t() * uint32_t()), uint32_t>::value, "");
static_assert(std::is_same<decltype(int64_t() * int64_t()), int64_t>::value, "");
static_assert(std::is_same<decltype(uint64_t() * uint64_t()), uint64_t>::value, "");
template <typename T>
static constexpr enable_if_floating_point<T> Call(KernelContext*, T left, T right) {
return left * right;
}
template <typename T>
static constexpr enable_if_unsigned_integer<T> Call(KernelContext*, T left, T right) {
return left * right;
}
template <typename T>
static constexpr enable_if_signed_integer<T> Call(KernelContext*, T left, T right) {
return to_unsigned(left) * to_unsigned(right);
}
// Multiplication of 16 bit integer types implicitly promotes to signed 32 bit
// integer. However, some inputs may nevertheless overflow (which triggers undefined
// behaviour). Therefore we first cast to 32 bit unsigned integers where overflow is
// well defined.
template <typename T = void>
static constexpr int16_t Call(KernelContext*, int16_t left, int16_t right) {
return static_cast<uint32_t>(left) * static_cast<uint32_t>(right);
}
template <typename T = void>
static constexpr uint16_t Call(KernelContext*, uint16_t left, uint16_t right) {
return static_cast<uint32_t>(left) * static_cast<uint32_t>(right);
}
};
struct MultiplyChecked {
template <typename T, typename Arg0, typename Arg1>
enable_if_integer<T> Call(KernelContext* ctx, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
T result = 0;
if (ARROW_PREDICT_FALSE(MultiplyWithOverflow(left, right, &result))) {
ctx->SetStatus(Status::Invalid("overflow"));
}
return result;
}
template <typename T, typename Arg0, typename Arg1>
enable_if_floating_point<T> Call(KernelContext*, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
return left * right;
}
};
struct Divide {
template <typename T, typename Arg0, typename Arg1>
static enable_if_floating_point<T> Call(KernelContext* ctx, Arg0 left, Arg1 right) {
return left / right;
}
template <typename T, typename Arg0, typename Arg1>
static enable_if_integer<T> Call(KernelContext* ctx, Arg0 left, Arg1 right) {
T result;
if (ARROW_PREDICT_FALSE(DivideWithOverflow(left, right, &result))) {
if (right == 0) {
ctx->SetStatus(Status::Invalid("divide by zero"));
} else {
result = 0;
}
}
return result;
}
};
struct DivideChecked {
template <typename T, typename Arg0, typename Arg1>
static enable_if_integer<T> Call(KernelContext* ctx, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
T result;
if (ARROW_PREDICT_FALSE(DivideWithOverflow(left, right, &result))) {
if (right == 0) {
ctx->SetStatus(Status::Invalid("divide by zero"));
} else {
ctx->SetStatus(Status::Invalid("overflow"));
}
}
return result;
}
template <typename T, typename Arg0, typename Arg1>
static enable_if_floating_point<T> Call(KernelContext* ctx, Arg0 left, Arg1 right) {
static_assert(std::is_same<T, Arg0>::value && std::is_same<T, Arg1>::value, "");
if (ARROW_PREDICT_FALSE(right == 0)) {
ctx->SetStatus(Status::Invalid("divide by zero"));
return 0;
}
return left / right;
}
};
// Generate a kernel given an arithmetic functor
template <template <typename... Args> class KernelGenerator, typename Op>
ArrayKernelExec NumericEqualTypesBinary(detail::GetTypeId get_id) {
switch (get_id.id) {
case Type::INT8:
return KernelGenerator<Int8Type, Int8Type, Op>::Exec;
case Type::UINT8:
return KernelGenerator<UInt8Type, UInt8Type, Op>::Exec;
case Type::INT16:
return KernelGenerator<Int16Type, Int16Type, Op>::Exec;
case Type::UINT16:
return KernelGenerator<UInt16Type, UInt16Type, Op>::Exec;
case Type::INT32:
return KernelGenerator<Int32Type, Int32Type, Op>::Exec;
case Type::UINT32:
return KernelGenerator<UInt32Type, UInt32Type, Op>::Exec;
case Type::INT64:
case Type::TIMESTAMP:
return KernelGenerator<Int64Type, Int64Type, Op>::Exec;
case Type::UINT64:
return KernelGenerator<UInt64Type, UInt64Type, Op>::Exec;
case Type::FLOAT:
return KernelGenerator<FloatType, FloatType, Op>::Exec;
case Type::DOUBLE:
return KernelGenerator<DoubleType, DoubleType, Op>::Exec;
default:
DCHECK(false);
return ExecFail;
}
}
template <typename Op>
std::shared_ptr<ScalarFunction> MakeArithmeticFunction(std::string name) {
auto func = std::make_shared<ScalarFunction>(name, Arity::Binary());
for (const auto& ty : NumericTypes()) {
auto exec = NumericEqualTypesBinary<ScalarBinaryEqualTypes, Op>(ty);
DCHECK_OK(func->AddKernel({ty, ty}, ty, exec));
}
return func;
}
// Like MakeArithmeticFunction, but for arithmetic ops that need to run
// only on non-null output.
template <typename Op>
std::shared_ptr<ScalarFunction> MakeArithmeticFunctionNotNull(std::string name) {
auto func = std::make_shared<ScalarFunction>(name, Arity::Binary());
for (const auto& ty : NumericTypes()) {
auto exec = NumericEqualTypesBinary<ScalarBinaryNotNullEqualTypes, Op>(ty);
DCHECK_OK(func->AddKernel({ty, ty}, ty, exec));
}
return func;
}
} // namespace
void RegisterScalarArithmetic(FunctionRegistry* registry) {
// ----------------------------------------------------------------------
auto add = MakeArithmeticFunction<Add>("add");
DCHECK_OK(registry->AddFunction(std::move(add)));
// ----------------------------------------------------------------------
auto add_checked = MakeArithmeticFunctionNotNull<AddChecked>("add_checked");
DCHECK_OK(registry->AddFunction(std::move(add_checked)));
// ----------------------------------------------------------------------
// subtract
auto subtract = MakeArithmeticFunction<Subtract>("subtract");
// Add subtract(timestamp, timestamp) -> duration
for (auto unit : AllTimeUnits()) {
InputType in_type(match::TimestampTypeUnit(unit));
auto exec =
NumericEqualTypesBinary<ScalarBinaryEqualTypes, Subtract>(Type::TIMESTAMP);
DCHECK_OK(subtract->AddKernel({in_type, in_type}, duration(unit), std::move(exec)));
}
DCHECK_OK(registry->AddFunction(std::move(subtract)));
// ----------------------------------------------------------------------
auto subtract_checked =
MakeArithmeticFunctionNotNull<SubtractChecked>("subtract_checked");
DCHECK_OK(registry->AddFunction(std::move(subtract_checked)));
// ----------------------------------------------------------------------
auto multiply = MakeArithmeticFunction<Multiply>("multiply");
DCHECK_OK(registry->AddFunction(std::move(multiply)));
// ----------------------------------------------------------------------
auto multiply_checked =
MakeArithmeticFunctionNotNull<MultiplyChecked>("multiply_checked");
DCHECK_OK(registry->AddFunction(std::move(multiply_checked)));
// ----------------------------------------------------------------------
auto divide = MakeArithmeticFunctionNotNull<Divide>("divide");
DCHECK_OK(registry->AddFunction(std::move(divide)));
// ----------------------------------------------------------------------
auto divide_checked = MakeArithmeticFunctionNotNull<DivideChecked>("divide_checked");
DCHECK_OK(registry->AddFunction(std::move(divide_checked)));
}
} // namespace internal
} // namespace compute
} // namespace arrow
|
#include <axisDrag.hpp>
AxisDrag::AxisDrag(GraphApp* app) :
Tool{app},
m_axis_status{std::vector<bool>(m_linkedApp->getAxis()->size(), false)}
{
auto vert_shader = gl::load_shader_from_file("shaders/axis.vert", GL_VERTEX_SHADER);
auto frag_shader = gl::load_shader_from_file("shaders/axis.frag", GL_FRAGMENT_SHADER);
m_program = gl::create_program({vert_shader, frag_shader});
// model relative to Polylines scale
m_draw_model = m_linkedApp->getModel();
// model relative to screen space
m_mouse_model = glm::scale(glm::mat4{1.0f}, glm::vec3{
1.0f / m_linkedApp->getModel()[0][0],
1.0f / m_linkedApp->getModel()[1][1],
1.0f / m_linkedApp->getModel()[2][2]}
);
// x coord span of axis rectangle
m_thickness = 0.05f;
m_default_color = glm::vec4(0.180, 0.215, 0.298, 0.2);
m_active_color = glm::vec4(0.180, 0.215, 0.298, 0.4);
// initialize axis order [0,1,2,3,...]
for (int i = 0; i < m_linkedApp->getAxis()->size(); i++) {
m_order.push_back(i);
}
initializeVertexBuffers();
initializeIndexBuffer();
}
AxisDrag::~AxisDrag() {
if (glIsBuffer(m_vbo)) {
glDeleteBuffers(1, &m_vbo);
}
if (glIsVertexArray(m_vao)) {
glDeleteVertexArrays(1, &m_vao);
}
if (glIsBuffer(m_ibo)) {
glDeleteBuffers(1, &m_ibo);
}
if (glIsProgram(m_program)) {
glDeleteProgram(m_program);
}
}
bool AxisDrag::draw() const {
glUseProgram(m_program);
gl::set_program_uniform(m_program, glGetUniformLocation(m_program, "transform"), m_draw_model);
gl::set_program_uniform(m_program, glGetUniformLocation(m_program, "default_color"), m_default_color);
gl::set_program_uniform(m_program, glGetUniformLocation(m_program, "active_color"), m_active_color);
glBindVertexArray(m_vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glDrawElements(GL_TRIANGLE_STRIP, m_indicies.size(), GL_UNSIGNED_SHORT, (const void*) 0);
return true;
}
bool AxisDrag::registerTool() {
return true;
}
bool AxisDrag::checkSelection() {
auto pos = m_linkedApp->mouse_pos();
float x = Utils::remap(pos.x, glm::vec2(0, m_linkedApp->resolution().x), glm::vec2(-1,1));
float y = Utils::remap(pos.y, glm::vec2(0, m_linkedApp->resolution().y), glm::vec2(-1,1));
auto ss_pos = m_mouse_model * glm::vec4(glm::vec2(x,y), 0, 1);
std::vector<bool> current (m_axis_status.size(), false);
// check for intersection with multiple axis
bool result = false;
for (int i = 0; i < m_axis_status.size(); i++) {
AABB axis_rect = AABB {
m_vertices[i * 4].pos, // upper left
m_vertices[i * 4 + 3].pos // lower right
};
if (Utils::insideAABB(ss_pos, axis_rect)) {
current[i] = true;
result = true;
}
else {
current[i] = false;
}
}
// if there is a diffrence to last check update colors
if (current != m_axis_status) {
m_axis_status = current;
updateColors();
}
return result;
}
void AxisDrag::updateColors() {
for (int i = 0; i < m_vertices.size(); i++) {
m_vertices[i].colorIndx = m_axis_status[(int)(i / 4)];
}
// sub only the 4 verts of selected axis
glNamedBufferSubData(m_vbo, 0, Utils::vectorsizeof(m_vertices), m_vertices.data());
}
bool AxisDrag::updateSelection(const glm::vec2& prev, const glm::vec2& current) {
bool moveing = false;
auto axis = *m_linkedApp->getAxis();
float scaled_prev_x = Utils::remap(prev.x, glm::vec2(0, m_linkedApp->resolution().x), glm::vec2(-1,1));
float scaled_currnet_x = Utils::remap(current.x, glm::vec2(0, m_linkedApp->resolution().x), glm::vec2(-1,1));
float x = scaled_currnet_x - scaled_prev_x;
for (int i = 0; i < m_axis_status.size(); i++) {
// move all selected axis by (mouse) delta
if (m_axis_status[i]) {
axis[i] += (m_mouse_model * glm::vec4(x, 0, 0, 1)).x;
moveing = true;
}
}
// re-sort axis since order might have changed
if (Utils::sortWithIndecies(axis, m_order)) {
// if order change, update vertices
m_linkedApp->updateOrder(m_order);
}
// update verts (axis_ssbo) and axis (verts for axis rect)
m_linkedApp->updateAxis(axis);
updateAxis(axis);
return moveing;
}
void AxisDrag::updateAxis(const std::vector<float>& axis) {
m_vertices.clear();
for (const auto& i : axis) {
m_vertices.push_back(AxisVertex{glm::vec2(i - m_thickness / 2, 1.05), 0});
m_vertices.push_back(AxisVertex{glm::vec2(i + m_thickness / 2, 1.05), 0});
m_vertices.push_back(AxisVertex{glm::vec2(i - m_thickness / 2, -1.05), 0});
m_vertices.push_back(AxisVertex{glm::vec2(i + m_thickness / 2, -1.05), 0});
}
glNamedBufferSubData(m_vbo, 0, Utils::vectorsizeof(m_vertices), m_vertices.data());
}
void AxisDrag::initializeVertexBuffers() {
// setup vertex array object and vertex buffer
glCreateVertexArrays(1, &m_vao);
glCreateBuffers(1, &m_vbo);
glVertexArrayVertexBuffer(m_vao, 0, m_vbo, 0, sizeof(AxisVertex));
GLuint pos_attrib_idx = 0;
glEnableVertexArrayAttrib(m_vao, pos_attrib_idx);
glVertexArrayAttribFormat(m_vao, pos_attrib_idx, 2, GL_FLOAT, false, offsetof(AxisVertex, pos));
glVertexArrayAttribBinding(m_vao, pos_attrib_idx, 0);
GLuint color_attrib_idx = 1;
glEnableVertexArrayAttrib(m_vao, color_attrib_idx);
glVertexArrayAttribFormat(m_vao, color_attrib_idx, 1, GL_FLOAT, false, offsetof(AxisVertex, colorIndx));
glVertexArrayAttribBinding(m_vao, color_attrib_idx, 0);
/** init indecies for MultiDrawArrays call
* 0 +----+ 1
* | |
* | |
* 2 +----+ 3
**/
for (const auto& i : *m_linkedApp->getAxis()) {
m_vertices.push_back(AxisVertex{glm::vec2(i - m_thickness / 2, 1.05), 0});
m_vertices.push_back(AxisVertex{glm::vec2(i + m_thickness / 2, 1.05), 0});
m_vertices.push_back(AxisVertex{glm::vec2(i - m_thickness / 2, -1.05), 0});
m_vertices.push_back(AxisVertex{glm::vec2(i + m_thickness / 2, -1.05), 0});
}
glNamedBufferData(m_vbo, Utils::vectorsizeof(m_vertices), m_vertices.data(), GL_DYNAMIC_DRAW);
}
void AxisDrag::initializeIndexBuffer() {
for (unsigned short i = 0; i < m_vertices.size(); i++) {
m_indicies.push_back(i);
// create degenerate triangles between quads
if ((i % 4 == 3 || i % 4 == 0) && i != 0 && i != m_vertices.size() - 1)
m_indicies.push_back(i);
}
// Bind to Element array buffer -> Indexing so DrawElements can be used
glGenBuffers(1, &m_ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, Utils::vectorsizeof(m_indicies), m_indicies.data(), GL_STATIC_DRAW);
}
|
#include<iostream>
using namespace std;
int main()
{
long double a,b; // float type variables
cout<<"Enter two numbers:"<<endl;
cout<<"First number: ";
cin>>a; // ">>" Extraction operator
cout<<"Second number: ";
cin>>b;
cout<<"The numbers are: "<<a<<" and "<<b<<endl; // Cascading operator "<<"
cout<<"\nsum = "<<a+b<<endl;
cout<<"Average = "<<(a+b)/2<<endl;
return 0;
}
|
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureToYUVPlanes.h"
#include "effects/GrSimpleTextureEffect.h"
#include "effects/GrYUVEffect.h"
#include "GrClip.h"
#include "GrContext.h"
#include "GrRenderTargetContext.h"
#include "GrPaint.h"
#include "GrTextureProvider.h"
namespace {
using MakeFPProc = sk_sp<GrFragmentProcessor> (*)(sk_sp<GrFragmentProcessor>,
SkYUVColorSpace colorSpace);
};
static bool convert_texture(GrTexture* src, GrRenderTargetContext* dst, int dstW, int dstH,
SkYUVColorSpace colorSpace, MakeFPProc proc) {
SkScalar xScale = SkIntToScalar(src->width()) / dstW / src->width();
SkScalar yScale = SkIntToScalar(src->height()) / dstH / src->height();
GrSamplerParams::FilterMode filter;
if (dstW == src->width() && dstW == src->height()) {
filter = GrSamplerParams::kNone_FilterMode;
} else {
filter = GrSamplerParams::kBilerp_FilterMode;
}
sk_sp<GrFragmentProcessor> fp(
GrSimpleTextureEffect::Make(src, nullptr, SkMatrix::MakeScale(xScale, yScale), filter));
if (!fp) {
return false;
}
fp = proc(std::move(fp), colorSpace);
if (!fp) {
return false;
}
GrPaint paint;
paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
paint.addColorFragmentProcessor(std::move(fp));
dst->drawRect(GrNoClip(), paint, SkMatrix::I(), SkRect::MakeIWH(dstW, dstH));
return true;
}
bool GrTextureToYUVPlanes(GrTexture* texture, const SkISize sizes[3], void* const planes[3],
const size_t rowBytes[3], SkYUVColorSpace colorSpace) {
if (GrContext* context = texture->getContext()) {
// Depending on the relative sizes of the y, u, and v planes we may do 1 to 3 draws/
// readbacks.
sk_sp<GrRenderTargetContext> yuvRenderTargetContext;
sk_sp<GrRenderTargetContext> yRenderTargetContext;
sk_sp<GrRenderTargetContext> uvRenderTargetContext;
sk_sp<GrRenderTargetContext> uRenderTargetContext;
sk_sp<GrRenderTargetContext> vRenderTargetContext;
// We issue draw(s) to convert from RGBA to Y, U, and V. All three planes may have different
// sizes however we optimize for two other cases - all planes are the same (1 draw to YUV),
// and U and V are the same but Y differs (2 draws, one for Y, one for UV).
if (sizes[0] == sizes[1] && sizes[1] == sizes[2]) {
yuvRenderTargetContext = context->makeRenderTargetContextWithFallback(
SkBackingFit::kApprox,
sizes[0].fWidth,
sizes[0].fHeight,
kRGBA_8888_GrPixelConfig,
nullptr);
if (!yuvRenderTargetContext) {
return false;
}
} else {
yRenderTargetContext = context->makeRenderTargetContextWithFallback(
SkBackingFit::kApprox,
sizes[0].fWidth,
sizes[0].fHeight,
kAlpha_8_GrPixelConfig,
nullptr);
if (!yRenderTargetContext) {
return false;
}
if (sizes[1] == sizes[2]) {
// TODO: Add support for GL_RG when available.
uvRenderTargetContext = context->makeRenderTargetContextWithFallback(
SkBackingFit::kApprox,
sizes[1].fWidth,
sizes[1].fHeight,
kRGBA_8888_GrPixelConfig,
nullptr);
if (!uvRenderTargetContext) {
return false;
}
} else {
uRenderTargetContext = context->makeRenderTargetContextWithFallback(
SkBackingFit::kApprox,
sizes[1].fWidth,
sizes[1].fHeight,
kAlpha_8_GrPixelConfig,
nullptr);
vRenderTargetContext = context->makeRenderTargetContextWithFallback(
SkBackingFit::kApprox,
sizes[2].fWidth,
sizes[2].fHeight,
kAlpha_8_GrPixelConfig,
nullptr);
if (!uRenderTargetContext || !vRenderTargetContext) {
return false;
}
}
}
// Do all the draws before any readback.
if (yuvRenderTargetContext) {
if (!convert_texture(texture, yuvRenderTargetContext.get(),
sizes[0].fWidth, sizes[0].fHeight,
colorSpace, GrYUVEffect::MakeRGBToYUV)) {
return false;
}
} else {
SkASSERT(yRenderTargetContext);
if (!convert_texture(texture, yRenderTargetContext.get(),
sizes[0].fWidth, sizes[0].fHeight,
colorSpace, GrYUVEffect::MakeRGBToY)) {
return false;
}
if (uvRenderTargetContext) {
if (!convert_texture(texture, uvRenderTargetContext.get(),
sizes[1].fWidth, sizes[1].fHeight,
colorSpace, GrYUVEffect::MakeRGBToUV)) {
return false;
}
} else {
SkASSERT(uRenderTargetContext && vRenderTargetContext);
if (!convert_texture(texture, uRenderTargetContext.get(),
sizes[1].fWidth, sizes[1].fHeight,
colorSpace, GrYUVEffect::MakeRGBToU)) {
return false;
}
if (!convert_texture(texture, vRenderTargetContext.get(),
sizes[2].fWidth, sizes[2].fHeight,
colorSpace, GrYUVEffect::MakeRGBToV)) {
return false;
}
}
}
if (yuvRenderTargetContext) {
SkASSERT(sizes[0] == sizes[1] && sizes[1] == sizes[2]);
sk_sp<GrTexture> yuvTex(yuvRenderTargetContext->asTexture());
SkASSERT(yuvTex);
SkISize yuvSize = sizes[0];
// We have no kRGB_888 pixel format, so readback rgba and then copy three channels.
SkAutoSTMalloc<128 * 128, uint32_t> tempYUV(yuvSize.fWidth * yuvSize.fHeight);
if (!yuvTex->readPixels(0, 0, yuvSize.fWidth, yuvSize.fHeight,
kRGBA_8888_GrPixelConfig, tempYUV.get(), 0)) {
return false;
}
size_t yRowBytes = rowBytes[0] ? rowBytes[0] : yuvSize.fWidth;
size_t uRowBytes = rowBytes[1] ? rowBytes[1] : yuvSize.fWidth;
size_t vRowBytes = rowBytes[2] ? rowBytes[2] : yuvSize.fWidth;
if (yRowBytes < (size_t)yuvSize.fWidth || uRowBytes < (size_t)yuvSize.fWidth ||
vRowBytes < (size_t)yuvSize.fWidth) {
return false;
}
for (int j = 0; j < yuvSize.fHeight; ++j) {
for (int i = 0; i < yuvSize.fWidth; ++i) {
// These writes could surely be made more efficient.
uint32_t y = GrColorUnpackR(tempYUV.get()[j * yuvSize.fWidth + i]);
uint32_t u = GrColorUnpackG(tempYUV.get()[j * yuvSize.fWidth + i]);
uint32_t v = GrColorUnpackB(tempYUV.get()[j * yuvSize.fWidth + i]);
uint8_t* yLoc = ((uint8_t*)planes[0]) + j * yRowBytes + i;
uint8_t* uLoc = ((uint8_t*)planes[1]) + j * uRowBytes + i;
uint8_t* vLoc = ((uint8_t*)planes[2]) + j * vRowBytes + i;
*yLoc = y;
*uLoc = u;
*vLoc = v;
}
}
return true;
} else {
SkASSERT(yRenderTargetContext);
sk_sp<GrTexture> yTex(yRenderTargetContext->asTexture());
SkASSERT(yTex);
if (!yTex->readPixels(0, 0, sizes[0].fWidth, sizes[0].fHeight,
kAlpha_8_GrPixelConfig, planes[0], rowBytes[0])) {
return false;
}
if (uvRenderTargetContext) {
SkASSERT(sizes[1].fWidth == sizes[2].fWidth);
sk_sp<GrTexture> uvTex(uvRenderTargetContext->asTexture());
SkASSERT(uvTex);
SkISize uvSize = sizes[1];
// We have no kRG_88 pixel format, so readback rgba and then copy two channels.
SkAutoSTMalloc<128 * 128, uint32_t> tempUV(uvSize.fWidth * uvSize.fHeight);
if (!uvTex->readPixels(0, 0, uvSize.fWidth, uvSize.fHeight,
kRGBA_8888_GrPixelConfig, tempUV.get(), 0)) {
return false;
}
size_t uRowBytes = rowBytes[1] ? rowBytes[1] : uvSize.fWidth;
size_t vRowBytes = rowBytes[2] ? rowBytes[2] : uvSize.fWidth;
if (uRowBytes < (size_t)uvSize.fWidth || vRowBytes < (size_t)uvSize.fWidth) {
return false;
}
for (int j = 0; j < uvSize.fHeight; ++j) {
for (int i = 0; i < uvSize.fWidth; ++i) {
// These writes could surely be made more efficient.
uint32_t u = GrColorUnpackR(tempUV.get()[j * uvSize.fWidth + i]);
uint32_t v = GrColorUnpackG(tempUV.get()[j * uvSize.fWidth + i]);
uint8_t* uLoc = ((uint8_t*)planes[1]) + j * uRowBytes + i;
uint8_t* vLoc = ((uint8_t*)planes[2]) + j * vRowBytes + i;
*uLoc = u;
*vLoc = v;
}
}
return true;
} else {
SkASSERT(uRenderTargetContext && vRenderTargetContext);
sk_sp<GrTexture> tex(uRenderTargetContext->asTexture());
SkASSERT(tex);
if (!tex->readPixels(0, 0, sizes[1].fWidth, sizes[1].fHeight,
kAlpha_8_GrPixelConfig, planes[1], rowBytes[1])) {
return false;
}
tex = vRenderTargetContext->asTexture();
SkASSERT(tex);
if (!tex->readPixels(0, 0, sizes[2].fWidth, sizes[2].fHeight,
kAlpha_8_GrPixelConfig, planes[2], rowBytes[2])) {
return false;
}
return true;
}
}
}
return false;
}
|
#include "Vertex.h"
|
#include "movegen.h"
#include <iostream>
int pawnPushes(const Board &b, std::vector<Move> &moves)
{
int moveCount = 0;
for (int i = 0; i < MAX_PAWNS; i++)
{
Square pawn = b.pawnSquares[i][b.side];
if (!pawn.isValid())
{
break;
}
uint8_t file = pawn.file();
uint8_t rank = pawn.rank();
if (rank == (b.side ? 6 : 1))
{
Square dest(file, rank + (b.side ? -2 : 2));
if (!(b.occupancyBoards[2] & dest.bitboard()))
{
moves.emplace_back(pawn, dest, 0x00);
moveCount++;
}
}
if (b.side ? (rank > 1) : (rank < 6))
{
Square dest(file, rank + (b.side ? -1 : 1));
if (!(b.occupancyBoards[2] & dest.bitboard()))
{
moves.emplace_back(pawn, dest, 0x00);
moveCount++;
}
}
else if (rank == (b.side ? 1 : 6))
{
Square dest(file, rank + (b.side
? -1
: 1));
if (!(b.occupancyBoards[2] & dest.bitboard()))
{
moves.emplace_back(pawn, dest, PROMOTE_KNIGHT_MASK);
moves.emplace_back(pawn, dest, PROMOTE_BISHOP_MASK);
moves.emplace_back(pawn, dest, PROMOTE_ROOK_MASK);
moves.emplace_back(pawn, dest, PROMOTE_QUEEN_MASK);
moveCount += 4;
}
}
}
return moveCount;
}
int pawnCaptures(const Board &b, std::vector<Move> &moves)
{
int moveCount = 0;
for (int i = 0; i < MAX_PAWNS; i++)
{
Square pawn = b.pawnSquares[i][b.side];
if (!pawn.isValid())
{
break;
}
uint8_t file = pawn.file();
uint8_t rank = pawn.rank();
uint8_t attackFile;
for (int direction = -1; direction < 2; direction += 2)
{
attackFile = file + direction;
if (attackFile < 0 || attackFile > 7)
{
continue;
}
Square attack(attackFile, rank + (b.side ? 1 : -1));
if (b.occupancyBoards[1 - b.side] & attack.bitboard())
{
if (b.side ? (rank > 1) : (rank < 6))
{
moves.emplace_back(pawn, attack, MOVE_CAPTURE_MASK);
moveCount++;
}
else if (b.side ? (rank == 1) : (rank == 6))
{
moves.emplace_back(pawn, attack, MOVE_CAPTURE_MASK | PROMOTE_KNIGHT_MASK);
moves.emplace_back(pawn, attack, MOVE_CAPTURE_MASK | PROMOTE_BISHOP_MASK);
moves.emplace_back(pawn, attack, MOVE_CAPTURE_MASK | PROMOTE_ROOK_MASK);
moves.emplace_back(pawn, attack, MOVE_CAPTURE_MASK | PROMOTE_QUEEN_MASK);
moveCount += 4;
}
}
}
}
return moveCount;
}
int pawnMoves(const Board &b, std::vector<Move> &moves)
{
return pawnPushes(b, moves) + pawnCaptures(b, moves);
}
int knightMoves(const Board &b, std::vector<Move> &moves)
{
constexpr int diffs[][2] = {{1, 2}, {1, -2}, {2, 1}, {-2, 1}, {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}};
int moveCount = 0;
for (int i = 0; i < MAX_KNIGHTS; i++)
{
Square knight = b.knightSquares[i][b.side];
if (!knight.isValid())
{
break;
}
for (auto &pair : diffs)
{
uint8_t file = knight.file() + pair[0];
uint8_t rank = knight.rank() + pair[1];
if (file < 0 || file > 7 || rank < 0 || rank > 7)
{
continue;
}
Square dest(file, rank);
if (b.occupancyBoards[1 - b.side] & dest.bitboard())
{
moves.emplace_back(knight, dest, MOVE_CAPTURE_MASK);
}
else if (!(b.occupancyBoards[b.side] & dest.bitboard()))
{
moves.emplace_back(knight, dest, 0x00);
}
}
}
return moveCount;
}
int bishopMoves(const Board &b, std::vector<Move> &moves)
{
constexpr int diffs[][2] = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {1, -1}, {2, -2}, {3, -3}, {4, -4}, {5, -5}, {6, -6}, {7, -7}, {-1, 1}, {-2, 2}, {-3, 3}, {-4, 4}, {-5, 5}, {-6, 6}, {-7, 7}, {-1, -1}, {-2, -2}, {-3, -3}, {-4, -4}, {-5, -5}, {-6, -6}, {-7, -7}};
int moveCount = 0;
for (int i = 0; i < MAX_BISHOPS; i++)
{
Square bishop = b.bishopSquares[i][b.side];
if (!bishop.isValid())
{
break;
}
for (auto &pair : diffs)
{
uint8_t file = bishop.file() + pair[0];
uint8_t rank = bishop.rank() + pair[1];
if (file < 0 || file > 7 || rank < 0 || rank > 7)
{
continue;
}
Square dest(file, rank);
if (b.occupancyBoards[1 - b.side] & dest.bitboard())
{
moves.emplace_back(bishop, dest, MOVE_CAPTURE_MASK);
}
else if (!(b.occupancyBoards[b.side] & dest.bitboard()))
{
moves.emplace_back(bishop, dest, 0x00);
}
}
}
return moveCount;
}
int rookMoves(const Board &b, std::vector<Move> &moves)
{
constexpr int diffs[][2] = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0}, {0, -1}, {0, -2}, {0, -3}, {0, -4}, {0, -5}, {0, -6}, {0, -7}, {-1, 0}, {-2, 0}, {-3, 0}, {-4, 0}, {-5, 0}, {-6, 0}, {-7, 0}};
int moveCount = 0;
for (int i = 0; i < MAX_ROOKS; i++)
{
Square rook = b.rookSquares[i][b.side];
if (!rook.isValid())
{
break;
}
for (auto &pair : diffs)
{
uint8_t file = rook.file() + pair[0];
uint8_t rank = rook.rank() + pair[1];
if (file < 0 || file > 7 || rank < 0 || rank > 7)
{
continue;
}
Square dest(file, rank);
if (b.occupancyBoards[1 - b.side] & dest.bitboard())
{
moves.emplace_back(rook, dest, MOVE_CAPTURE_MASK);
}
else if (!(b.occupancyBoards[b.side] & dest.bitboard()))
{
moves.emplace_back(rook, dest, 0x00);
}
}
}
return moveCount;
}
int queenMoves(const Board &b, std::vector<Move> &moves)
{
constexpr int diffs[][2] = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0}, {0, -1}, {0, -2}, {0, -3}, {0, -4}, {0, -5}, {0, -6}, {0, -7}, {-1, 0}, {-2, 0}, {-3, 0}, {-4, 0}, {-5, 0}, {-6, 0}, {-7, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {1, -1}, {2, -2}, {3, -3}, {4, -4}, {5, -5}, {6, -6}, {7, -7}, {-1, 1}, {-2, 2}, {-3, 3}, {-4, 4}, {-5, 5}, {-6, 6}, {-7, 7}, {-1, -1}, {-2, -2}, {-3, -3}, {-4, -4}, {-5, -5}, {-6, -6}, {-7, -7}};
int moveCount = 0;
for (int i = 0; i < MAX_QUEENS; i++)
{
Square queen = b.queenSquares[i][b.side];
if (!queen.isValid())
{
break;
}
for (auto &pair : diffs)
{
uint8_t file = queen.file() + pair[0];
uint8_t rank = queen.rank() + pair[1];
if (file < 0 || file > 7 || rank < 0 || rank > 7)
{
continue;
}
Square dest(file, rank);
if (b.occupancyBoards[1 - b.side] & dest.bitboard())
{
moves.emplace_back(queen, dest, MOVE_CAPTURE_MASK);
}
else if (!(b.occupancyBoards[b.side] & dest.bitboard()))
{
moves.emplace_back(queen, dest, 0x00);
}
}
}
return moveCount;
}
int kingMoves(const Board &b, std::vector<Move> &moves)
{
constexpr int diffs[][2] = {{1, 1}, {1, 0}, {1, -1}, {0, -1}, {0, 1}, {-1, -1}, {-1, 0}, {-1, 1}};
int moveCount = 0;
for (int i = 0; i < MAX_KINGS; i++)
{
Square king = b.kingSquares[i][b.side];
if (!king.isValid())
{
break;
}
for (auto &pair : diffs)
{
uint8_t file = king.file() + pair[0];
uint8_t rank = king.rank() + pair[1];
if (file < 0 || file > 7 || rank < 0 || rank > 7)
{
continue;
}
Square dest(file, rank);
if (b.occupancyBoards[1 - b.side] & dest.bitboard())
{
moves.emplace_back(king, dest, MOVE_CAPTURE_MASK);
}
else if (!(b.occupancyBoards[b.side] & dest.bitboard()))
{
moves.emplace_back(king, dest, 0x00);
}
}
}
return moveCount;
}
int allMoves(const Board &b, std::vector<Move> &moves)
{
return pawnMoves(b, moves) + knightMoves(b, moves) + bishopMoves(b, moves) + rookMoves(b, moves) + queenMoves(b, moves) + kingMoves(b, moves);
}
|
#include "itemcomparator.h"
#include "core/namespace.h"
#include "nsselecter.h"
namespace reindexer {
bool ItemComparator::operator()(const ItemRef &lhs, const ItemRef &rhs) const {
size_t firstDifferentExprIdx = 0;
int exprCmpRes = 0;
for (const auto &eR : ctx_.sortingContext.exprResults) {
if (eR[lhs.SortExprResultsIdx()] != eR[rhs.SortExprResultsIdx()]) {
exprCmpRes = (eR[lhs.SortExprResultsIdx()] > eR[rhs.SortExprResultsIdx()]) ? 1 : -1;
break;
}
++firstDifferentExprIdx;
}
assert(exprCmpRes == 0 || firstDifferentExprIdx < byExpr_.size());
size_t firstDifferentFieldIdx = 0;
int fieldsCmpRes = 0;
// do not perform comparation by indexes if not necessary
if (exprCmpRes == 0 || byExpr_[firstDifferentExprIdx].first != 0) {
fieldsCmpRes = ConstPayload(ns_.payloadType_, ns_.items_[lhs.Id()])
.Compare(ns_.items_[rhs.Id()], fields_, firstDifferentFieldIdx, collateOpts_);
assertf(fieldsCmpRes == 0 || firstDifferentFieldIdx < byIndex_.size(), "%d < %d\n", int(firstDifferentFieldIdx),
int(byIndex_.size()));
}
int cmpRes;
bool desc;
if (exprCmpRes != 0) {
if (fieldsCmpRes == 0 || byExpr_[firstDifferentExprIdx].first < byIndex_[firstDifferentFieldIdx].first) {
cmpRes = exprCmpRes;
desc = byExpr_[firstDifferentExprIdx].second;
} else {
cmpRes = fieldsCmpRes;
desc = byIndex_[firstDifferentFieldIdx].second;
}
} else if (fieldsCmpRes != 0) {
cmpRes = fieldsCmpRes;
desc = byIndex_[firstDifferentFieldIdx].second;
} else {
// If values are equal, then sort by row ID, to give consistent results
cmpRes = (lhs.Id() > rhs.Id()) ? 1 : ((lhs.Id() < rhs.Id()) ? -1 : 0);
desc = ctx_.sortingContext.entries[0].data->desc;
}
if (desc) {
return (cmpRes > 0);
} else {
return (cmpRes < 0);
}
}
class ItemComparator::BackInserter {
public:
explicit BackInserter(ItemComparator &comparator) : comparator_(comparator) {}
void expr(size_t i, bool desc) { comparator_.byExpr_.emplace_back(i, desc); }
void fields(const TagsPath &tp) { comparator_.fields_.push_back(std::move(tp)); }
void fields(int fieldIdx) { comparator_.fields_.push_back(fieldIdx); }
void index(size_t i, bool desc) { comparator_.byIndex_.emplace_back(i, desc); }
void collateOpts(const CollateOpts *opts) { comparator_.collateOpts_.emplace_back(opts); }
private:
ItemComparator &comparator_;
};
class ItemComparator::FrontInserter {
public:
FrontInserter(ItemComparator &comparator) : comparator_(comparator) {}
void expr(size_t i, bool desc) { comparator_.byExpr_.emplace(comparator_.byExpr_.begin(), i, desc); }
void fields(const TagsPath &tp) {
FieldsSet tmp;
tmp.push_back(tp);
for (const auto &f : comparator_.fields_) tmp.push_back(f);
std::swap(tmp, comparator_.fields_);
}
void fields(int fieldIdx) {
FieldsSet tmp;
tmp.push_back(fieldIdx);
for (const auto &f : comparator_.fields_) tmp.push_back(f);
std::swap(tmp, comparator_.fields_);
}
void index(size_t i, bool desc) { comparator_.byIndex_.emplace(comparator_.byIndex_.begin(), i, desc); }
void collateOpts(const CollateOpts *opts) { comparator_.collateOpts_.emplace(comparator_.collateOpts_.begin(), opts); }
private:
ItemComparator &comparator_;
};
template <typename Inserter>
void ItemComparator::bindOne(size_t index, const SortingContext::Entry &sortingCtx, Inserter insert, bool multiSort) {
if (sortingCtx.expression != SortingContext::Entry::NoExpression) {
insert.expr(index, sortingCtx.data->desc);
return;
}
int fieldIdx = sortingCtx.data->index;
if (fieldIdx == IndexValueType::SetByJsonPath || ns_.indexes_[fieldIdx]->Opts().IsSparse()) {
TagsPath tagsPath;
if (fieldIdx != IndexValueType::SetByJsonPath) {
const FieldsSet &fs = ns_.indexes_[fieldIdx]->Fields();
assert(fs.getTagsPathsLength() > 0);
tagsPath = fs.getTagsPath(0);
} else {
tagsPath = ns_.tagsMatcher_.path2tag(sortingCtx.data->expression);
}
if (fields_.contains(tagsPath)) {
throw Error(errQueryExec, "Can't sort by 2 equal indexes: %s", sortingCtx.data->expression);
}
insert.fields(tagsPath);
insert.index(index, sortingCtx.data->desc);
} else {
if (ns_.indexes_[fieldIdx]->Opts().IsArray()) {
throw Error(errQueryExec, "Sorting cannot be applied to array field.");
}
if (fieldIdx >= ns_.indexes_.firstCompositePos()) {
if (multiSort) {
throw Error(errQueryExec, "Multicolumn sorting cannot be applied to composite fields: %s", sortingCtx.data->expression);
}
fields_ = ns_.indexes_[fieldIdx]->Fields();
assert(byIndex_.empty());
byIndex_.resize(fields_.size(), {index, sortingCtx.data->desc});
} else {
if (fields_.contains(fieldIdx)) {
throw Error(errQueryExec, "You cannot sort by 2 same indexes: %s", sortingCtx.data->expression);
}
insert.fields(fieldIdx);
insert.index(index, sortingCtx.data->desc);
}
}
insert.collateOpts(sortingCtx.opts);
}
void ItemComparator::BindForForcedSort() {
const auto &entries = ctx_.sortingContext.entries;
const auto &exprResults = ctx_.sortingContext.exprResults;
assert(entries.size() >= exprResults.size());
byExpr_.reserve(exprResults.size());
byIndex_.reserve(entries.size() - exprResults.size());
const bool multiSort = entries.size() > 1;
for (size_t i = 1; i < entries.size(); ++i) {
bindOne(i, entries[i], BackInserter{*this}, multiSort);
}
assert(byIndex_.size() == fields_.size());
}
void ItemComparator::BindForGeneralSort() {
const auto &entries = ctx_.sortingContext.entries;
const auto &exprResults = ctx_.sortingContext.exprResults;
assert(entries.size() >= exprResults.size());
const bool multiSort = entries.size() > 1;
if (byExpr_.empty() && byIndex_.empty()) {
byExpr_.reserve(exprResults.size());
byIndex_.reserve(entries.size() - exprResults.size());
for (size_t i = 0; i < entries.size(); ++i) {
bindOne(i, entries[i], BackInserter{*this}, multiSort);
}
} else if (!entries.empty()) {
bindOne(0, entries[0], FrontInserter{*this}, multiSort);
}
assert(byExpr_.size() == exprResults.size());
assert(byIndex_.size() == fields_.size());
}
} // namespace reindexer
|
//=================================================================================================
/*!
// \file src/mathtest/smatdmatmult/MIbLDa.cpp
// \brief Source file for the MIbLDa sparse matrix/dense matrix multiplication math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. 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.
// 3. Neither the names of the Blaze development group 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/IdentityMatrix.h>
#include <blaze/math/LowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MIbLDa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using MIb = blaze::IdentityMatrix<TypeB>;
using LDa = blaze::LowerMatrix< blaze::DynamicMatrix<TypeA> >;
// Creator type definitions
using CMIb = blazetest::Creator<MIb>;
using CLDa = blazetest::Creator<LDa>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( i ), CLDa( i ) );
}
// Running tests with large matrices
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 31UL ), CLDa( 31UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 67UL ), CLDa( 67UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 127UL ), CLDa( 127UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 32UL ), CLDa( 32UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 64UL ), CLDa( 64UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 128UL ), CLDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *bitcoin_strings[] = {QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
" %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=firexcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"FireXCoin Alert\" admin@foo."
"com\n"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv6, "
"falling back to IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"An error occurred while setting up the RPC port %u for listening on IPv4: %s"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"You must set rpcpassword=<password> in the configuration file:\n"
"%s\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions."),
QT_TRANSLATE_NOOP("bitcoin-core", "FireXCoin version"),
QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or firexcoind"),
QT_TRANSLATE_NOOP("bitcoin-core", "List commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"),
QT_TRANSLATE_NOOP("bitcoin-core", "FireXCoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "This help message"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: firexcoin.conf)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: firexcoind.pid)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set database disk log size in megabytes (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"),
QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 7329 or testnet: 17329)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using internet relay chat (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Bind to given address. Use [host]:port notation for IPv6"),
QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Stake your coins to support network and gain reward (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Sync time with other nodes. Disable if time on your system is precise e.g. "
"syncing with NTP (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Sync checkpoints policy (default: strict)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: "
"86400)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Detach block and address databases. Increases shutdown time (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"When creating transactions, ignore inputs with value less than this "
"(default: 0.01)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"),
QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"),
QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"),
QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"),
QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Listen for JSON-RPC connections on <port> (default: 7330 or testnet: 17330)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Require a confirmations for change (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Enforce transaction scripts to use canonical PUSH operators (default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Execute command when a relevant alert is received (%s in cmd is replaced by "
"message)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 2500, 0 = all)"),
QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-6, default: 1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000?.dat file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: "
"27000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:"
"@STRENGTH)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mininput=<amount>: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside data directory %s."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Cannot obtain a lock on data directory %s. FireXCoin is probably already "
"running."),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying database integrity..."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error initializing database environment %s! To recover, BACKUP THAT "
"DIRECTORY, then remove everything from it except for wallet.dat."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("bitcoin-core", "Unable to sign checkpoint, wrong checkpointkey?\n"),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading blkindex.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of FireXCoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart FireXCoin to complete"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot initialize keypool"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Importing blockchain data file."),
QT_TRANSLATE_NOOP("bitcoin-core", "Importing bootstrap blockchain data file."),
QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: could not start node"),
QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Unable to bind to %s on this computer. FireXCoin is probably already running."),
QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction "),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet unlocked for staking only, unable to create transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: This transaction requires a transaction fee of at least %s because of "
"its amount, complexity, or use of recently received funds "),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Transaction creation failed "),
QT_TRANSLATE_NOOP("bitcoin-core", "Sending..."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Error: The transaction was rejected. This might happen if some of the coins "
"in your wallet were already spent, such as if you used a copy of wallet.dat "
"and coins were spent in the copy but not marked as spent here."),
QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"),
QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong FireXCoin will not work properly."),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("bitcoin-core", "WARNING: syncronized checkpoint violation detected, but skipped!"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Disk space is low!"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"WARNING: Invalid checkpoint found! Displayed transactions may not be "
"correct! You may need to upgrade, or notify developers."),
};
|
#include <mscorlib/System/mscorlib_System_Activator.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_ObjectHandle.h>
#include <mscorlib/System/mscorlib_System_Byte.h>
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_Binder.h>
#include <mscorlib/System/Globalization/mscorlib_System_Globalization_CultureInfo.h>
#include <mscorlib/System/Security/Policy/mscorlib_System_Security_Policy_Evidence.h>
#include <mscorlib/System/mscorlib_System_ActivationContext.h>
#include <mscorlib/System/mscorlib_System_AppDomain.h>
namespace mscorlib
{
namespace System
{
//Public Methods
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateComInstanceFrom(mscorlib::System::String assemblyName, mscorlib::System::String typeName)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameters__[0] = (MonoObject*)assemblyName;
__parameters__[1] = (MonoObject*)typeName;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateComInstanceFrom", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateComInstanceFrom(const char *assemblyName, const char *typeName)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateComInstanceFrom", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateComInstanceFrom(mscorlib::System::String assemblyName, mscorlib::System::String typeName, std::vector<mscorlib::System::Byte*> hashValue, mscorlib::System::Configuration::Assemblies::AssemblyHashAlgorithm::__ENUM__ hashAlgorithm)
{
MonoType *__parameter_types__[4];
void *__parameters__[4];
__parameter_types__[0] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameter_types__[2] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameter_types__[3] = Global::GetType(typeid(hashAlgorithm).name());
__parameters__[0] = (MonoObject*)assemblyName;
__parameters__[1] = (MonoObject*)typeName;
__parameters__[2] = Global::FromArray<mscorlib::System::Byte*>(hashValue, typeid(mscorlib::System::Byte).name());
mscorlib::System::Int32 __param_hashAlgorithm__ = hashAlgorithm;
__parameters__[3] = &__param_hashAlgorithm__;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateComInstanceFrom", NullMonoObject, 4, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateComInstanceFrom(const char *assemblyName, const char *typeName, std::vector<mscorlib::System::Byte*> hashValue, mscorlib::System::Configuration::Assemblies::AssemblyHashAlgorithm::__ENUM__ hashAlgorithm)
{
MonoType *__parameter_types__[4];
void *__parameters__[4];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Byte")), 1));
__parameter_types__[3] = Global::GetType(typeid(hashAlgorithm).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[2] = Global::FromArray<mscorlib::System::Byte*>(hashValue, typeid(mscorlib::System::Byte).name());
mscorlib::System::Int32 __param_hashAlgorithm__ = hashAlgorithm;
__parameters__[3] = &__param_hashAlgorithm__;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateComInstanceFrom", NullMonoObject, 4, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::String assemblyFile, mscorlib::System::String typeName)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(assemblyFile).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameters__[0] = (MonoObject*)assemblyFile;
__parameters__[1] = (MonoObject*)typeName;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(const char *assemblyFile, const char *typeName)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyFile);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::String assemblyFile, mscorlib::System::String typeName, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(assemblyFile).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameter_types__[2] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)assemblyFile;
__parameters__[1] = (MonoObject*)typeName;
__parameters__[2] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(const char *assemblyFile, const char *typeName, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyFile);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[2] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::String assemblyFile, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityInfo)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType(typeid(assemblyFile).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[8] = Global::GetType(typeid(securityInfo).name());
__parameters__[0] = (MonoObject*)assemblyFile;
__parameters__[1] = (MonoObject*)typeName;
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[8] = (MonoObject*)securityInfo;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(const char *assemblyFile, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityInfo)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[8] = Global::GetType(typeid(securityInfo).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyFile);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[8] = (MonoObject*)securityInfo;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::String assemblyName, mscorlib::System::String typeName)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameters__[0] = (MonoObject*)assemblyName;
__parameters__[1] = (MonoObject*)typeName;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(const char *assemblyName, const char *typeName)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::String assemblyName, mscorlib::System::String typeName, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameter_types__[2] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)assemblyName;
__parameters__[1] = (MonoObject*)typeName;
__parameters__[2] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(const char *assemblyName, const char *typeName, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[2] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::String assemblyName, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityInfo)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[8] = Global::GetType(typeid(securityInfo).name());
__parameters__[0] = (MonoObject*)assemblyName;
__parameters__[1] = (MonoObject*)typeName;
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[8] = (MonoObject*)securityInfo;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(const char *assemblyName, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityInfo)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[8] = Global::GetType(typeid(securityInfo).name());
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[8] = (MonoObject*)securityInfo;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::ActivationContext activationContext)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(activationContext).name());
__parameters__[0] = (MonoObject*)activationContext;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::ActivationContext activationContext, std::vector<mscorlib::System::String*> activationCustomData)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(activationContext).name());
__parameter_types__[1] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "String")), 1));
__parameters__[0] = (MonoObject*)activationContext;
__parameters__[1] = Global::FromArray<mscorlib::System::String*>(activationCustomData, typeid(mscorlib::System::String).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::AppDomain domain, mscorlib::System::String assemblyFile, mscorlib::System::String typeName)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType(typeid(assemblyFile).name());
__parameter_types__[2] = Global::GetType(typeid(typeName).name());
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = (MonoObject*)assemblyFile;
__parameters__[2] = (MonoObject*)typeName;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::AppDomain domain, const char *assemblyFile, const char *typeName)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = mono_string_new(Global::GetDomain(), assemblyFile);
__parameters__[2] = mono_string_new(Global::GetDomain(), typeName);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::AppDomain domain, mscorlib::System::String assemblyFile, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityAttributes)
{
MonoType *__parameter_types__[10];
void *__parameters__[10];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType(typeid(assemblyFile).name());
__parameter_types__[2] = Global::GetType(typeid(typeName).name());
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[9] = Global::GetType(typeid(securityAttributes).name());
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = (MonoObject*)assemblyFile;
__parameters__[2] = (MonoObject*)typeName;
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[9] = (MonoObject*)securityAttributes;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 10, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::AppDomain domain, const char *assemblyFile, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityAttributes)
{
MonoType *__parameter_types__[10];
void *__parameters__[10];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[9] = Global::GetType(typeid(securityAttributes).name());
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = mono_string_new(Global::GetDomain(), assemblyFile);
__parameters__[2] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[9] = (MonoObject*)securityAttributes;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 10, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::AppDomain domain, mscorlib::System::String assemblyName, mscorlib::System::String typeName)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[2] = Global::GetType(typeid(typeName).name());
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = (MonoObject*)assemblyName;
__parameters__[2] = (MonoObject*)typeName;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::AppDomain domain, const char *assemblyName, const char *typeName)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[2] = mono_string_new(Global::GetDomain(), typeName);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::AppDomain domain, mscorlib::System::String assemblyName, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityAttributes)
{
MonoType *__parameter_types__[10];
void *__parameters__[10];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[2] = Global::GetType(typeid(typeName).name());
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[9] = Global::GetType(typeid(securityAttributes).name());
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = (MonoObject*)assemblyName;
__parameters__[2] = (MonoObject*)typeName;
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[9] = (MonoObject*)securityAttributes;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 10, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::AppDomain domain, const char *assemblyName, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes, mscorlib::System::Security::Policy::Evidence securityAttributes)
{
MonoType *__parameter_types__[10];
void *__parameters__[10];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[9] = Global::GetType(typeid(securityAttributes).name());
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[2] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
__parameters__[9] = (MonoObject*)securityAttributes;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 10, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Object Activator::CreateInstance(mscorlib::System::Type type)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameters__[0] = (MonoObject*)type;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::CreateInstance(mscorlib::System::Type type, std::vector<mscorlib::System::Object*> args)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)type;
__parameters__[1] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::CreateInstance(mscorlib::System::Type type, std::vector<mscorlib::System::Object*> args, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[2] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)type;
__parameters__[1] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[2] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::CreateInstance(mscorlib::System::Type type, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture)
{
MonoType *__parameter_types__[5];
void *__parameters__[5];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[2] = Global::GetType(typeid(binder).name());
__parameter_types__[3] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[4] = Global::GetType(typeid(culture).name());
__parameters__[0] = (MonoObject*)type;
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[1] = &__param_bindingAttr__;
__parameters__[2] = (MonoObject*)binder;
__parameters__[3] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[4] = (MonoObject*)culture;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 5, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::CreateInstance(mscorlib::System::Type type, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[6];
void *__parameters__[6];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[2] = Global::GetType(typeid(binder).name());
__parameter_types__[3] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[4] = Global::GetType(typeid(culture).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)type;
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[1] = &__param_bindingAttr__;
__parameters__[2] = (MonoObject*)binder;
__parameters__[3] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[4] = (MonoObject*)culture;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 6, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::CreateInstance(mscorlib::System::Type type, mscorlib::System::Boolean nonPublic)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = Global::GetType(typeid(nonPublic).name());
__parameters__[0] = (MonoObject*)type;
__parameters__[1] = reinterpret_cast<void*>(nonPublic);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::GetObject(mscorlib::System::Type type, mscorlib::System::String url)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = Global::GetType(typeid(url).name());
__parameters__[0] = (MonoObject*)type;
__parameters__[1] = (MonoObject*)url;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "GetObject", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::GetObject(mscorlib::System::Type type, const char *url)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameters__[0] = (MonoObject*)type;
__parameters__[1] = mono_string_new(Global::GetDomain(), url);
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "GetObject", NullMonoObject, 2, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::GetObject(mscorlib::System::Type type, mscorlib::System::String url, mscorlib::System::Object state)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = Global::GetType(typeid(url).name());
__parameter_types__[2] = Global::GetType(typeid(state).name());
__parameters__[0] = (MonoObject*)type;
__parameters__[1] = (MonoObject*)url;
__parameters__[2] = (MonoObject*)state;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "GetObject", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Object Activator::GetObject(mscorlib::System::Type type, const char *url, mscorlib::System::Object state)
{
MonoType *__parameter_types__[3];
void *__parameters__[3];
__parameter_types__[0] = Global::GetType(typeid(type).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType(typeid(state).name());
__parameters__[0] = (MonoObject*)type;
__parameters__[1] = mono_string_new(Global::GetDomain(), url);
__parameters__[2] = (MonoObject*)state;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "GetObject", NullMonoObject, 3, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::String assemblyName, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[8];
void *__parameters__[8];
__parameter_types__[0] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)assemblyName;
__parameters__[1] = (MonoObject*)typeName;
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 8, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(const char *assemblyName, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[8];
void *__parameters__[8];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 8, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::AppDomain domain, mscorlib::System::String assemblyName, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType(typeid(assemblyName).name());
__parameter_types__[2] = Global::GetType(typeid(typeName).name());
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = (MonoObject*)assemblyName;
__parameters__[2] = (MonoObject*)typeName;
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstance(mscorlib::System::AppDomain domain, const char *assemblyName, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = mono_string_new(Global::GetDomain(), assemblyName);
__parameters__[2] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstance", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::String assemblyFile, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[8];
void *__parameters__[8];
__parameter_types__[0] = Global::GetType(typeid(assemblyFile).name());
__parameter_types__[1] = Global::GetType(typeid(typeName).name());
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)assemblyFile;
__parameters__[1] = (MonoObject*)typeName;
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 8, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(const char *assemblyFile, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[8];
void *__parameters__[8];
__parameter_types__[0] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[3] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[4] = Global::GetType(typeid(binder).name());
__parameter_types__[5] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[6] = Global::GetType(typeid(culture).name());
__parameter_types__[7] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = mono_string_new(Global::GetDomain(), assemblyFile);
__parameters__[1] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[2] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[3] = &__param_bindingAttr__;
__parameters__[4] = (MonoObject*)binder;
__parameters__[5] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[6] = (MonoObject*)culture;
__parameters__[7] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 8, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::AppDomain domain, mscorlib::System::String assemblyFile, mscorlib::System::String typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType(typeid(assemblyFile).name());
__parameter_types__[2] = Global::GetType(typeid(typeName).name());
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = (MonoObject*)assemblyFile;
__parameters__[2] = (MonoObject*)typeName;
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
mscorlib::System::Runtime::Remoting::ObjectHandle Activator::CreateInstanceFrom(mscorlib::System::AppDomain domain, const char *assemblyFile, const char *typeName, mscorlib::System::Boolean ignoreCase, mscorlib::System::Reflection::BindingFlags::__ENUM__ bindingAttr, mscorlib::System::Reflection::Binder binder, std::vector<mscorlib::System::Object*> args, mscorlib::System::Globalization::CultureInfo culture, std::vector<mscorlib::System::Object*> activationAttributes)
{
MonoType *__parameter_types__[9];
void *__parameters__[9];
__parameter_types__[0] = Global::GetType(typeid(domain).name());
__parameter_types__[1] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[2] = Global::GetType("mscorlib", "System", "String");
__parameter_types__[3] = Global::GetType(typeid(ignoreCase).name());
__parameter_types__[4] = Global::GetType(typeid(bindingAttr).name());
__parameter_types__[5] = Global::GetType(typeid(binder).name());
__parameter_types__[6] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameter_types__[7] = Global::GetType(typeid(culture).name());
__parameter_types__[8] = mono_class_get_type(mono_array_class_get(mono_class_from_mono_type(Global::GetType("mscorlib", "System", "Object")), 1));
__parameters__[0] = (MonoObject*)domain;
__parameters__[1] = mono_string_new(Global::GetDomain(), assemblyFile);
__parameters__[2] = mono_string_new(Global::GetDomain(), typeName);
__parameters__[3] = reinterpret_cast<void*>(ignoreCase);
mscorlib::System::Int32 __param_bindingAttr__ = bindingAttr;
__parameters__[4] = &__param_bindingAttr__;
__parameters__[5] = (MonoObject*)binder;
__parameters__[6] = Global::FromArray<mscorlib::System::Object*>(args, typeid(mscorlib::System::Object).name());
__parameters__[7] = (MonoObject*)culture;
__parameters__[8] = Global::FromArray<mscorlib::System::Object*>(activationAttributes, typeid(mscorlib::System::Object).name());
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "Activator", 0, NULL, "CreateInstanceFrom", NullMonoObject, 9, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Runtime::Remoting::ObjectHandle(__result__);
}
}
}
|
/*
11048 : 이동하기
URL : https://www.acmicpc.net/problem/11048
Input #1 :
3 4
1 2 3 4
0 0 0 5
9 8 7 6
Output #1 :
31
Input #2 :
3 3
1 0 0
0 1 0
0 0 1
Output #2 :
3
Input #3 :
4 3
1 2 3
6 5 4
7 8 9
12 11 10
Output #3 :
47
*/
#include <iostream>
#include <cstring>
#define MAX_N 1001
#define MAX_M 1001
int n;
int m;
int maze[MAX_N][MAX_M];
int dp[MAX_N][MAX_M];
int move(int x, int y)
{
if (x >= m)
{
return 0;
}
if (y >= n)
{
return 0;
}
if (dp[y][x] != -1)
{
return dp[y][x];
}
dp[y][x] = maze[y][x];
dp[y][x] += std::max(move(x + 1, y),
std::max(move(x, y + 1), move(x + 1, y + 1)));
return dp[y][x];
}
int main(int argc, char const *argv[])
{
std::memset(&(dp[0][0]), -1, sizeof(int) * MAX_N * MAX_M);
std::cin >> n;
std::cin >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
std::cin >> maze[i][j];
}
}
std::cout << move(0, 0);
return 0;
}
|
#include "common.h"
#include "../mocks.h"
using ::testing::Return;
using ::testing::_;
namespace bpftrace {
namespace test {
namespace codegen {
TEST(codegen, args_multiple_tracepoints)
{
auto bpftrace = get_mock_bpftrace();
test(*bpftrace,
"tracepoint:sched:sched_one,tracepoint:sched:sched_two { "
"@[args->common_field] = count(); }",
#if LLVM_VERSION_MAJOR > 6
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"tracepoint:sched:sched_one"(i8*) local_unnamed_addr section "s_tracepoint:sched:sched_one_1" {
entry:
%"@_val" = alloca i64, align 8
%"@_key" = alloca [8 x i8], align 8
%1 = ptrtoint i8* %0 to i64
%2 = add i64 %1, 8
%3 = inttoptr i64 %2 to i64*
%4 = load volatile i64, i64* %3, align 8
%5 = getelementptr inbounds [8 x i8], [8 x i8]* %"@_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %4, [8 x i8]* %"@_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i64, [8 x i8]*)*)(i64 %pseudo, [8 x i8]* nonnull %"@_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%cast = bitcast i8* %lookup_elem to i64*
%6 = load i64, i64* %cast, align 8
%phitmp = add i64 %6, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%7 = bitcast i64* %"@_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %7)
store i64 %lookup_elem_val.0, i64* %"@_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i64, [8 x i8]*, i64*, i64)*)(i64 %pseudo1, [8 x i8]* nonnull %"@_key", i64* nonnull %"@_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %7)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
define i64 @"tracepoint:sched:sched_two"(i8*) local_unnamed_addr section "s_tracepoint:sched:sched_two_2" {
entry:
%"@_val" = alloca i64, align 8
%"@_key" = alloca [8 x i8], align 8
%1 = ptrtoint i8* %0 to i64
%2 = add i64 %1, 16
%3 = inttoptr i64 %2 to i64*
%4 = load volatile i64, i64* %3, align 8
%5 = getelementptr inbounds [8 x i8], [8 x i8]* %"@_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %4, [8 x i8]* %"@_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i64, [8 x i8]*)*)(i64 %pseudo, [8 x i8]* nonnull %"@_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%cast = bitcast i8* %lookup_elem to i64*
%6 = load i64, i64* %cast, align 8
%phitmp = add i64 %6, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%7 = bitcast i64* %"@_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %7)
store i64 %lookup_elem_val.0, i64* %"@_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i64, [8 x i8]*, i64*, i64)*)(i64 %pseudo1, [8 x i8]* nonnull %"@_key", i64* nonnull %"@_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %7)
ret i64 0
}
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
#else
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"tracepoint:sched:sched_one"(i8*) local_unnamed_addr section "s_tracepoint:sched:sched_one_1" {
entry:
%"@_val" = alloca i64, align 8
%"@_key" = alloca [8 x i8], align 8
%1 = ptrtoint i8* %0 to i64
%2 = add i64 %1, 8
%3 = inttoptr i64 %2 to i64*
%4 = load volatile i64, i64* %3, align 8
%5 = getelementptr inbounds [8 x i8], [8 x i8]* %"@_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %4, [8 x i8]* %"@_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i64, [8 x i8]*)*)(i64 %pseudo, [8 x i8]* nonnull %"@_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%cast = bitcast i8* %lookup_elem to i64*
%6 = load i64, i64* %cast, align 8
%phitmp = add i64 %6, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%7 = bitcast i64* %"@_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %7)
store i64 %lookup_elem_val.0, i64* %"@_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i64, [8 x i8]*, i64*, i64)*)(i64 %pseudo1, [8 x i8]* nonnull %"@_key", i64* nonnull %"@_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %7)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
define i64 @"tracepoint:sched:sched_two"(i8*) local_unnamed_addr section "s_tracepoint:sched:sched_two_2" {
entry:
%"@_val" = alloca i64, align 8
%"@_key" = alloca [8 x i8], align 8
%1 = ptrtoint i8* %0 to i64
%2 = add i64 %1, 16
%3 = inttoptr i64 %2 to i64*
%4 = load volatile i64, i64* %3, align 8
%5 = getelementptr inbounds [8 x i8], [8 x i8]* %"@_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %4, [8 x i8]* %"@_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i64, [8 x i8]*)*)(i64 %pseudo, [8 x i8]* nonnull %"@_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%cast = bitcast i8* %lookup_elem to i64*
%6 = load i64, i64* %cast, align 8
%phitmp = add i64 %6, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%7 = bitcast i64* %"@_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %7)
store i64 %lookup_elem_val.0, i64* %"@_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i64, [8 x i8]*, i64*, i64)*)(i64 %pseudo1, [8 x i8]* nonnull %"@_key", i64* nonnull %"@_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %7)
ret i64 0
}
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
#endif
}
} // namespace codegen
} // namespace test
} // namespace bpftrace
|
// Scintilla source code edit control
/** @file ScintillaBase.cxx
** An enhanced subclass of Editor with calltips, autocomplete and context menu.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cmath>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <algorithm>
#include <memory>
#include "Platform.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "PropSetSimple.h"
//#include "CharacterCategory.h"
#include "LexerModule.h"
#include "Catalogue.h"
#include "Position.h"
#include "UniqueString.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "Selection.h"
#include "PositionCache.h"
#include "EditModel.h"
#include "MarginView.h"
#include "EditView.h"
#include "Editor.h"
#include "AutoComplete.h"
#include "ScintillaBase.h"
using namespace Scintilla;
ScintillaBase::ScintillaBase() noexcept {
#if SCI_EnablePopupMenu
displayPopupMenu = SC_POPUP_ALL;
#endif
listType = 0;
maxListWidth = 0;
multiAutoCMode = SC_MULTIAUTOC_ONCE;
#ifdef SCI_LEXER
Scintilla_LinkLexers();
#endif
}
ScintillaBase::~ScintillaBase() = default;
void ScintillaBase::Finalise() noexcept {
Editor::Finalise();
#if SCI_EnablePopupMenu
popup.Destroy();
#endif
}
void ScintillaBase::InsertCharacter(std::string_view sv, CharacterSource charSource) {
const bool isFillUp = ac.Active() && ac.IsFillUpChar(sv[0]);
if (!isFillUp) {
Editor::InsertCharacter(sv, charSource);
}
if (ac.Active()) {
AutoCompleteCharacterAdded(sv[0]);
// For fill ups add the character after the autocompletion has
// triggered so containers see the key so can display a calltip.
if (isFillUp) {
Editor::InsertCharacter(sv, charSource);
}
}
}
void ScintillaBase::Command(int cmdId) {
switch (cmdId) {
case idAutoComplete: // Nothing to do
break;
case idCallTip: // Nothing to do
break;
case idcmdUndo:
WndProc(SCI_UNDO, 0, 0);
break;
case idcmdRedo:
WndProc(SCI_REDO, 0, 0);
break;
case idcmdCut:
WndProc(SCI_CUT, 0, 0);
break;
case idcmdCopy:
WndProc(SCI_COPY, 0, 0);
break;
case idcmdPaste:
WndProc(SCI_PASTE, 0, 0);
break;
case idcmdDelete:
WndProc(SCI_CLEAR, 0, 0);
break;
case idcmdSelectAll:
WndProc(SCI_SELECTALL, 0, 0);
break;
}
}
int ScintillaBase::KeyCommand(unsigned int iMessage) {
// Most key commands cancel autocompletion mode
if (ac.Active()) {
switch (iMessage) {
// Except for these
case SCI_LINEDOWN:
AutoCompleteMove(1);
return 0;
case SCI_LINEUP:
AutoCompleteMove(-1);
return 0;
case SCI_PAGEDOWN:
AutoCompleteMove(ac.lb->GetVisibleRows());
return 0;
case SCI_PAGEUP:
AutoCompleteMove(-ac.lb->GetVisibleRows());
return 0;
case SCI_VCHOME:
AutoCompleteMove(-5000);
return 0;
case SCI_LINEEND:
AutoCompleteMove(5000);
return 0;
case SCI_DELETEBACK:
DelCharBack(true);
AutoCompleteCharacterDeleted();
EnsureCaretVisible();
return 0;
case SCI_DELETEBACKNOTLINE:
DelCharBack(false);
AutoCompleteCharacterDeleted();
EnsureCaretVisible();
return 0;
case SCI_TAB:
AutoCompleteCompleted(0, SC_AC_TAB);
return 0;
case SCI_NEWLINE:
AutoCompleteCompleted(0, SC_AC_NEWLINE);
return 0;
default:
AutoCompleteCancel();
}
}
if (ct.inCallTipMode) {
if (
(iMessage != SCI_CHARLEFT) &&
(iMessage != SCI_CHARLEFTEXTEND) &&
(iMessage != SCI_CHARRIGHT) &&
(iMessage != SCI_CHARRIGHTEXTEND) &&
(iMessage != SCI_EDITTOGGLEOVERTYPE) &&
(iMessage != SCI_DELETEBACK) &&
(iMessage != SCI_DELETEBACKNOTLINE)
) {
ct.CallTipCancel();
}
if ((iMessage == SCI_DELETEBACK) || (iMessage == SCI_DELETEBACKNOTLINE)) {
if (sel.MainCaret() <= ct.posStartCallTip) {
ct.CallTipCancel();
}
}
}
return Editor::KeyCommand(iMessage);
}
void ScintillaBase::ListNotify(ListBoxEvent *plbe) {
switch (plbe->event) {
case ListBoxEvent::EventType::selectionChange:
AutoCompleteSelection();
break;
case ListBoxEvent::EventType::doubleClick:
AutoCompleteCompleted(0, SC_AC_DOUBLECLICK);
break;
}
}
void ScintillaBase::AutoCompleteInsert(Sci::Position startPos, Sci::Position removeLen, const char *text, Sci::Position textLen) {
UndoGroup ug(pdoc);
if (multiAutoCMode == SC_MULTIAUTOC_ONCE) {
pdoc->DeleteChars(startPos, removeLen);
const Sci::Position lengthInserted = pdoc->InsertString(startPos, text, textLen);
SetEmptySelection(startPos + lengthInserted);
} else {
// SC_MULTIAUTOC_EACH
for (size_t r = 0; r < sel.Count(); r++) {
if (!RangeContainsProtected(sel.Range(r).Start().Position(),
sel.Range(r).End().Position())) {
Sci::Position positionInsert = sel.Range(r).Start().Position();
positionInsert = RealizeVirtualSpace(positionInsert, sel.Range(r).caret.VirtualSpace());
if (positionInsert - removeLen >= 0) {
positionInsert -= removeLen;
pdoc->DeleteChars(positionInsert, removeLen);
}
const Sci::Position lengthInserted = pdoc->InsertString(positionInsert, text, textLen);
if (lengthInserted > 0) {
sel.Range(r).caret.SetPosition(positionInsert + lengthInserted);
sel.Range(r).anchor.SetPosition(positionInsert + lengthInserted);
}
sel.Range(r).ClearVirtualSpace();
}
}
}
}
void ScintillaBase::AutoCompleteStart(Sci::Position lenEntered, const char *list) {
//Platform::DebugPrintf("AutoComplete %s\n", list);
ct.CallTipCancel();
if (ac.chooseSingle && (listType == 0)) {
if (list && !strchr(list, ac.GetSeparator())) {
const char *typeSep = strchr(list, ac.GetTypesep());
const Sci::Position lenInsert = typeSep ?
(typeSep - list) : strlen(list);
if (ac.ignoreCase) {
// May need to convert the case before invocation, so remove lenEntered characters
AutoCompleteInsert(sel.MainCaret() - lenEntered, lenEntered, list, lenInsert);
} else {
AutoCompleteInsert(sel.MainCaret(), 0, list + lenEntered, lenInsert - lenEntered);
}
ac.Cancel();
return;
}
}
ac.Start(wMain, idAutoComplete, sel.MainCaret(), PointMainCaret(),
lenEntered, vs.lineHeight, IsUnicodeMode(), technology);
const PRectangle rcClient = GetClientRectangle();
Point pt = LocationFromPosition(sel.MainCaret() - lenEntered);
PRectangle rcPopupBounds = wMain.GetMonitorRect(pt);
if (rcPopupBounds.Height() == 0)
rcPopupBounds = rcClient;
int heightLB = ac.heightLBDefault;
int widthLB = ac.widthLBDefault;
if (pt.x >= rcClient.right - widthLB) {
HorizontalScrollTo(static_cast<int>(xOffset + pt.x - rcClient.right + widthLB));
Redraw();
pt = PointMainCaret();
}
if (wMargin.Created()) {
pt = pt + GetVisibleOriginInMain();
}
PRectangle rcac;
rcac.left = pt.x - ac.lb->CaretFromEdge();
if (pt.y >= rcPopupBounds.bottom - heightLB && // Won't fit below.
pt.y >= (rcPopupBounds.bottom + rcPopupBounds.top) / 2) { // and there is more room above.
rcac.top = pt.y - heightLB;
if (rcac.top < rcPopupBounds.top) {
heightLB -= static_cast<int>(rcPopupBounds.top - rcac.top);
rcac.top = rcPopupBounds.top;
}
} else {
rcac.top = pt.y + vs.lineHeight;
}
rcac.right = rcac.left + widthLB;
rcac.bottom = static_cast<XYPOSITION>(std::min(static_cast<int>(rcac.top) + heightLB, static_cast<int>(rcPopupBounds.bottom)));
ac.lb->SetPositionRelative(rcac, &wMain);
ac.lb->SetFont(vs.styles[STYLE_DEFAULT].font);
ac.lb->SetColour(vs.styles[STYLE_DEFAULT].fore, vs.styles[STYLE_DEFAULT].back);
const unsigned int aveCharWidth = static_cast<unsigned int>(vs.styles[STYLE_DEFAULT].aveCharWidth);
ac.lb->SetAverageCharWidth(aveCharWidth);
ac.lb->SetDelegate(this);
ac.SetList(list ? list : "");
// Fiddle the position of the list so it is right next to the target and wide enough for all its strings
PRectangle rcList = ac.lb->GetDesiredRect();
const int heightAlloced = static_cast<int>(rcList.bottom - rcList.top);
widthLB = std::max(widthLB, static_cast<int>(rcList.right - rcList.left));
if (maxListWidth != 0)
widthLB = std::min(widthLB, static_cast<int>(aveCharWidth)*maxListWidth);
// Make an allowance for large strings in list
rcList.left = pt.x - ac.lb->CaretFromEdge();
rcList.right = rcList.left + widthLB;
if (((pt.y + vs.lineHeight) >= (rcPopupBounds.bottom - heightAlloced)) && // Won't fit below.
((pt.y + vs.lineHeight / 2) >= (rcPopupBounds.bottom + rcPopupBounds.top) / 2)) { // and there is more room above.
rcList.top = pt.y - heightAlloced;
} else {
rcList.top = pt.y + vs.lineHeight;
}
rcList.bottom = rcList.top + heightAlloced;
ac.lb->SetPositionRelative(rcList, &wMain);
ac.Show(true);
if (lenEntered != 0) {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCancel() noexcept {
if (ac.Active()) {
SCNotification scn = {};
scn.nmhdr.code = SCN_AUTOCCANCELLED;
scn.wParam = 0;
scn.listType = 0;
NotifyParent(scn);
}
ac.Cancel();
}
void ScintillaBase::AutoCompleteMove(int delta) {
ac.Move(delta);
}
void ScintillaBase::AutoCompleteMoveToCurrentWord() {
std::string wordCurrent = RangeText(ac.posStart - ac.startLen, sel.MainCaret());
ac.Select(wordCurrent.c_str());
}
void ScintillaBase::AutoCompleteSelection() {
const int item = ac.GetSelection();
std::string selected;
if (item != -1) {
selected = ac.GetValue(item);
}
SCNotification scn = {};
scn.nmhdr.code = SCN_AUTOCSELECTIONCHANGE;
scn.message = 0;
scn.wParam = listType;
scn.listType = listType;
const Sci::Position firstPos = ac.posStart - ac.startLen;
scn.position = firstPos;
scn.lParam = firstPos;
scn.text = selected.c_str();
NotifyParent(scn);
}
void ScintillaBase::AutoCompleteCharacterAdded(char ch) {
if (ac.IsFillUpChar(ch)) {
AutoCompleteCompleted(ch, SC_AC_FILLUP);
} else if (ac.IsStopChar(ch)) {
AutoCompleteCancel();
} else {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCharacterDeleted() {
if (sel.MainCaret() < ac.posStart - ac.startLen) {
AutoCompleteCancel();
} else if (ac.cancelAtStartPos && (sel.MainCaret() <= ac.posStart)) {
AutoCompleteCancel();
} else {
AutoCompleteMoveToCurrentWord();
}
SCNotification scn = {};
scn.nmhdr.code = SCN_AUTOCCHARDELETED;
scn.wParam = 0;
scn.listType = 0;
NotifyParent(scn);
}
void ScintillaBase::AutoCompleteCompleted(char ch, unsigned int completionMethod) {
const int item = ac.GetSelection();
if (item == -1) {
AutoCompleteCancel();
return;
}
const std::string selected = ac.GetValue(item);
ac.Show(false);
SCNotification scn = {};
scn.nmhdr.code = listType > 0 ? SCN_USERLISTSELECTION : SCN_AUTOCSELECTION;
scn.message = 0;
scn.ch = ch;
scn.listCompletionMethod = completionMethod;
scn.wParam = listType;
scn.listType = listType;
const Sci::Position firstPos = ac.posStart - ac.startLen;
scn.position = firstPos;
scn.lParam = firstPos;
scn.text = selected.c_str();
NotifyParent(scn);
if (!ac.Active())
return;
ac.Cancel();
if (listType > 0)
return;
Sci::Position endPos = sel.MainCaret();
if (ac.dropRestOfWord)
endPos = pdoc->ExtendWordSelect(endPos, 1, true);
if (endPos < firstPos)
return;
AutoCompleteInsert(firstPos, endPos - firstPos, selected.c_str(), selected.length());
SetLastXChosen();
scn.nmhdr.code = SCN_AUTOCCOMPLETED;
NotifyParent(scn);
}
int ScintillaBase::AutoCompleteGetCurrent() const noexcept {
if (!ac.Active())
return -1;
return ac.GetSelection();
}
int ScintillaBase::AutoCompleteGetCurrentText(char *buffer) const {
if (ac.Active()) {
const int item = ac.GetSelection();
if (item != -1) {
const std::string selected = ac.GetValue(item);
if (buffer != nullptr)
memcpy(buffer, selected.c_str(), selected.length() + 1);
return static_cast<int>(selected.length());
}
}
if (buffer != nullptr)
*buffer = '\0';
return 0;
}
void ScintillaBase::CallTipShow(Point pt, NotificationPosition notifyPos, const char *defn) {
ac.Cancel();
// If container knows about STYLE_CALLTIP then use it in place of the
// STYLE_DEFAULT for the face name, size and character set. Also use it
// for the foreground and background colour.
const int ctStyle = ct.UseStyleCallTip() ? STYLE_CALLTIP : STYLE_DEFAULT;
if (ct.UseStyleCallTip()) {
ct.SetForeBack(vs.styles[STYLE_CALLTIP].fore, vs.styles[STYLE_CALLTIP].back);
}
if (notifyPos == NotificationPosition::None) {
ct.innerMarginX = 12;
ct.innerMarginY = 10;
} else {
ct.innerMarginX = std::max(24, vs.lineHeight);
ct.innerMarginY = std::max(20, vs.lineHeight);
}
if (wMargin.Created()) {
pt = pt + GetVisibleOriginInMain();
}
PRectangle rc = ct.CallTipStart(sel.MainCaret(), pt,
vs.lineHeight,
defn,
vs.styles[ctStyle].fontName,
vs.styles[ctStyle].sizeZoomed,
CodePage(),
vs.styles[ctStyle].characterSet,
vs.technology,
vs.localeName.c_str(),
wMain);
// If the call-tip window would be out of the client
// space
const PRectangle rcClient = GetClientRectangle();
const int offset = vs.lineHeight + static_cast<int>(rc.Height());
// adjust so it displays above the text.
if (rc.bottom > rcClient.bottom && rc.Height() < rcClient.Height()) {
rc.top -= offset;
rc.bottom -= offset;
}
// adjust so it displays below the text.
if (rc.top < rcClient.top && rc.Height() < rcClient.Height()) {
rc.top += offset;
rc.bottom += offset;
}
if (notifyPos != NotificationPosition::None) {
const XYPOSITION height = rc.Height();
const XYPOSITION width = rc.Width();
switch (notifyPos) {
case NotificationPosition::BottomRight:
rc.bottom = rcClient.bottom - 4;
rc.top = rc.bottom - height;
rc.right = rcClient.right - 4;
rc.left = rc.right - width;
break;
case NotificationPosition::Center:
rc.top = (rcClient.top + rcClient.bottom - height)/2;
rc.bottom = rc.top + height;
rc.left = (rcClient.left + rcClient.right - width)/2;
rc.right = rc.left + width;
break;
default:
break;
}
}
// Now display the window.
CreateCallTipWindow(rc);
ct.wCallTip.SetPositionRelative(rc, &wMain);
ct.wCallTip.Show();
}
void ScintillaBase::CallTipClick() noexcept {
SCNotification scn = {};
scn.nmhdr.code = SCN_CALLTIPCLICK;
scn.position = ct.clickPlace;
NotifyParent(scn);
}
#if SCI_EnablePopupMenu
bool ScintillaBase::ShouldDisplayPopup(Point ptInWindowCoordinates) const noexcept {
return (displayPopupMenu == SC_POPUP_ALL ||
(displayPopupMenu == SC_POPUP_TEXT && !PointInSelMargin(ptInWindowCoordinates)));
}
void ScintillaBase::ContextMenu(Point pt) noexcept {
if (displayPopupMenu) {
const bool writable = !WndProc(SCI_GETREADONLY, 0, 0);
popup.CreatePopUp();
AddToPopUp("Undo", idcmdUndo, writable && pdoc->CanUndo());
AddToPopUp("Redo", idcmdRedo, writable && pdoc->CanRedo());
AddToPopUp("");
AddToPopUp("Cut", idcmdCut, writable && !sel.Empty());
AddToPopUp("Copy", idcmdCopy, !sel.Empty());
AddToPopUp("Paste", idcmdPaste, writable && WndProc(SCI_CANPASTE, 0, 0));
AddToPopUp("Delete", idcmdDelete, writable && !sel.Empty());
AddToPopUp("");
AddToPopUp("Select All", idcmdSelectAll);
popup.Show(pt, wMain);
}
}
#endif
void ScintillaBase::CancelModes() noexcept {
AutoCompleteCancel();
ct.CallTipCancel();
Editor::CancelModes();
}
void ScintillaBase::ButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers) {
CancelModes();
Editor::ButtonDownWithModifiers(pt, curTime, modifiers);
}
void ScintillaBase::RightButtonDownWithModifiers(Point pt, unsigned int curTime, int modifiers) {
CancelModes();
Editor::RightButtonDownWithModifiers(pt, curTime, modifiers);
}
namespace Scintilla {
class LexState : public LexInterface {
const LexerModule *lexCurrent;
void SetLexerModule(const LexerModule *lex);
PropSetSimple props;
int interfaceVersion;
public:
int lexLanguage;
explicit LexState(Document *pdoc_) noexcept;
void SetInstance(ILexer5 *instance_);
// Deleted so LexState objects can not be copied.
LexState(const LexState &) = delete;
LexState(LexState &&) = delete;
LexState &operator=(const LexState &) = delete;
LexState &operator=(LexState &&) = delete;
~LexState() noexcept override;
void SetLexer(uptr_t wParam);
void SetLexerLanguage(const char *languageName);
const char *DescribeWordListSets() const noexcept;
void SetWordList(int n, bool toLower, const char *wl);
int GetIdentifier() const noexcept;
const char *GetName() const noexcept;
void *PrivateCall(int operation, void *pointer);
const char *PropertyNames() const noexcept;
int PropertyType(const char *name) const;
const char *DescribeProperty(const char *name) const;
void PropSet(const char *key, const char *val);
const char *PropGet(const char *key) const;
int PropGetInt(const char *key, int defaultValue = 0) const;
size_t PropGetExpanded(const char *key, char *result) const;
int LineEndTypesSupported() const noexcept override;
int AllocateSubStyles(int styleBase, int numberStyles);
int SubStylesStart(int styleBase) const noexcept;
int SubStylesLength(int styleBase) const noexcept;
int StyleFromSubStyle(int subStyle) const noexcept;
int PrimaryStyleFromStyle(int style) const noexcept;
void FreeSubStyles() noexcept;
void SetIdentifiers(int style, const char *identifiers);
int DistanceToSecondaryStyles() const noexcept;
const char *GetSubStyleBases() const noexcept;
int NamedStyles() const noexcept;
const char *NameOfStyle(int style) const noexcept;
const char *TagsOfStyle(int style) const noexcept;
const char *DescriptionOfStyle(int style) const noexcept;
};
}
LexState::LexState(Document *pdoc_) noexcept : LexInterface(pdoc_) {
lexCurrent = nullptr;
performingStyle = false;
interfaceVersion = lvRelease4;
lexLanguage = SCLEX_CONTAINER;
}
LexState::~LexState() noexcept {
if (instance) {
instance->Release();
instance = nullptr;
}
}
void LexState::SetInstance(ILexer5 *instance_) {
if (instance) {
instance->Release();
instance = nullptr;
}
instance = instance_;
pdoc->LexerChanged();
}
LexState *ScintillaBase::DocumentLexState() {
if (!pdoc->GetLexInterface()) {
pdoc->SetLexInterface(std::make_unique<LexState>(pdoc));
}
return down_cast<LexState *>(pdoc->GetLexInterface());
}
void LexState::SetLexerModule(const LexerModule *lex) {
if (lex != lexCurrent) {
if (instance) {
instance->Release();
instance = nullptr;
}
interfaceVersion = lvRelease4;
lexCurrent = lex;
if (lexCurrent) {
instance = lexCurrent->Create();
interfaceVersion = instance->Version();
}
pdoc->LexerChanged();
}
}
void LexState::SetLexer(uptr_t wParam) {
lexLanguage = static_cast<int>(wParam);
if (lexLanguage == SCLEX_CONTAINER) {
SetLexerModule(nullptr);
} else {
const LexerModule *lex = Catalogue::Find(lexLanguage);
if (!lex)
lex = Catalogue::Find(SCLEX_NULL);
SetLexerModule(lex);
}
}
void LexState::SetLexerLanguage(const char *languageName) {
const LexerModule *lex = Catalogue::Find(languageName);
if (!lex)
lex = Catalogue::Find(SCLEX_NULL);
if (lex)
lexLanguage = lex->GetLanguage();
SetLexerModule(lex);
}
const char *LexState::DescribeWordListSets() const noexcept {
if (instance) {
return instance->DescribeWordListSets();
} else {
return nullptr;
}
}
void LexState::SetWordList(int n, bool toLower, const char *wl) {
if (instance) {
const Sci_Position firstModification = instance->WordListSet(n, toLower, wl);
if (firstModification >= 0) {
pdoc->ModifiedAt(firstModification);
}
}
}
int LexState::GetIdentifier() const noexcept {
if (lexCurrent) {
return lexCurrent->GetLanguage();
}
if (instance) {
if (instance->Version() >= lvRelease5) {
return instance->GetIdentifier();
}
}
return SCLEX_CONTAINER;
}
const char *LexState::GetName() const noexcept {
if (lexCurrent) {
return lexCurrent->languageName;
}
if (instance) {
if (instance->Version() >= lvRelease5) {
return instance->GetName();
}
}
return "";
}
void *LexState::PrivateCall(int operation, void *pointer) {
if (pdoc && instance) {
return instance->PrivateCall(operation, pointer);
} else {
return nullptr;
}
}
const char *LexState::PropertyNames() const noexcept {
if (instance) {
return instance->PropertyNames();
} else {
return nullptr;
}
}
int LexState::PropertyType(const char *name) const {
if (instance) {
return instance->PropertyType(name);
} else {
return SC_TYPE_BOOLEAN;
}
}
const char *LexState::DescribeProperty(const char *name) const {
if (instance) {
return instance->DescribeProperty(name);
} else {
return nullptr;
}
}
void LexState::PropSet(const char *key, const char *val) {
props.Set(key, val, strlen(key), strlen(val));
if (instance) {
const Sci_Position firstModification = instance->PropertySet(key, val);
if (firstModification >= 0) {
pdoc->ModifiedAt(firstModification);
}
}
}
const char *LexState::PropGet(const char *key) const {
return props.Get(key);
}
int LexState::PropGetInt(const char *key, int defaultValue) const {
return props.GetInt(key, defaultValue);
}
size_t LexState::PropGetExpanded(const char *key, char *result) const {
return props.GetExpanded(key, result);
}
int LexState::LineEndTypesSupported() const noexcept {
if (instance) {
return instance->LineEndTypesSupported();
}
return 0;
}
int LexState::AllocateSubStyles(int styleBase, int numberStyles) {
if (instance) {
return instance->AllocateSubStyles(styleBase, numberStyles);
}
return -1;
}
int LexState::SubStylesStart(int styleBase) const noexcept {
if (instance) {
return instance->SubStylesStart(styleBase);
}
return -1;
}
int LexState::SubStylesLength(int styleBase) const noexcept {
if (instance) {
return instance->SubStylesLength(styleBase);
}
return 0;
}
int LexState::StyleFromSubStyle(int subStyle) const noexcept {
if (instance) {
return instance->StyleFromSubStyle(subStyle);
}
return 0;
}
int LexState::PrimaryStyleFromStyle(int style) const noexcept {
if (instance) {
return instance->PrimaryStyleFromStyle(style);
}
return 0;
}
void LexState::FreeSubStyles() noexcept {
if (instance) {
instance->FreeSubStyles();
}
}
void LexState::SetIdentifiers(int style, const char *identifiers) {
if (instance) {
instance->SetIdentifiers(style, identifiers);
pdoc->ModifiedAt(0);
}
}
int LexState::DistanceToSecondaryStyles() const noexcept {
if (instance) {
return instance->DistanceToSecondaryStyles();
}
return 0;
}
const char *LexState::GetSubStyleBases() const noexcept {
if (instance) {
return instance->GetSubStyleBases();
}
return "";
}
int LexState::NamedStyles() const noexcept {
if (instance) {
return instance->NamedStyles();
} else {
return -1;
}
}
const char *LexState::NameOfStyle(int style) const noexcept {
if (instance) {
return instance->NameOfStyle(style);
} else {
return nullptr;
}
}
const char *LexState::TagsOfStyle(int style) const noexcept {
if (instance) {
return instance->TagsOfStyle(style);
} else {
return nullptr;
}
}
const char *LexState::DescriptionOfStyle(int style) const noexcept {
if (instance) {
return instance->DescriptionOfStyle(style);
} else {
return nullptr;
}
}
void ScintillaBase::NotifyStyleToNeeded(Sci::Position endStyleNeeded) {
if (DocumentLexState()->GetIdentifier() != SCLEX_CONTAINER) {
const Sci::Line lineEndStyled =
pdoc->SciLineFromPosition(pdoc->GetEndStyled());
const Sci::Position endStyled =
pdoc->LineStart(lineEndStyled);
DocumentLexState()->Colourise(endStyled, endStyleNeeded);
return;
}
Editor::NotifyStyleToNeeded(endStyleNeeded);
}
void ScintillaBase::NotifyLexerChanged(Document *, void *) {
vs.EnsureStyle(0xff);
}
sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
switch (iMessage) {
case SCI_AUTOCSHOW:
listType = 0;
AutoCompleteStart(wParam, ConstCharPtrFromSPtr(lParam));
break;
case SCI_AUTOCCANCEL:
ac.Cancel();
break;
case SCI_AUTOCACTIVE:
return ac.Active();
case SCI_AUTOCPOSSTART:
return ac.posStart;
case SCI_AUTOCCOMPLETE:
AutoCompleteCompleted(0, SC_AC_COMMAND);
break;
case SCI_AUTOCSETSEPARATOR:
ac.SetSeparator(static_cast<char>(wParam));
break;
case SCI_AUTOCGETSEPARATOR:
return ac.GetSeparator();
case SCI_AUTOCSTOPS:
ac.SetStopChars(ConstCharPtrFromSPtr(lParam));
break;
case SCI_AUTOCSELECT:
ac.Select(ConstCharPtrFromSPtr(lParam));
break;
case SCI_AUTOCGETCURRENT:
return AutoCompleteGetCurrent();
case SCI_AUTOCGETCURRENTTEXT:
return AutoCompleteGetCurrentText(CharPtrFromSPtr(lParam));
case SCI_AUTOCSETCANCELATSTART:
ac.cancelAtStartPos = wParam != 0;
break;
case SCI_AUTOCGETCANCELATSTART:
return ac.cancelAtStartPos;
case SCI_AUTOCSETFILLUPS:
ac.SetFillUpChars(ConstCharPtrFromSPtr(lParam));
break;
case SCI_AUTOCSETCHOOSESINGLE:
ac.chooseSingle = wParam != 0;
break;
case SCI_AUTOCGETCHOOSESINGLE:
return ac.chooseSingle;
case SCI_AUTOCSETIGNORECASE:
ac.ignoreCase = wParam != 0;
break;
case SCI_AUTOCGETIGNORECASE:
return ac.ignoreCase;
case SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR:
ac.ignoreCaseBehaviour = static_cast<unsigned int>(wParam);
break;
case SCI_AUTOCGETCASEINSENSITIVEBEHAVIOUR:
return ac.ignoreCaseBehaviour;
case SCI_AUTOCSETMULTI:
multiAutoCMode = static_cast<int>(wParam);
break;
case SCI_AUTOCGETMULTI:
return multiAutoCMode;
case SCI_AUTOCSETORDER:
ac.autoSort = static_cast<int>(wParam);
break;
case SCI_AUTOCGETORDER:
return ac.autoSort;
case SCI_USERLISTSHOW:
listType = static_cast<int>(wParam);
AutoCompleteStart(0, ConstCharPtrFromSPtr(lParam));
break;
case SCI_AUTOCSETAUTOHIDE:
ac.autoHide = wParam != 0;
break;
case SCI_AUTOCGETAUTOHIDE:
return ac.autoHide;
case SCI_AUTOCSETDROPRESTOFWORD:
ac.dropRestOfWord = wParam != 0;
break;
case SCI_AUTOCGETDROPRESTOFWORD:
return ac.dropRestOfWord;
case SCI_AUTOCSETMAXHEIGHT:
ac.lb->SetVisibleRows(static_cast<int>(wParam));
break;
case SCI_AUTOCGETMAXHEIGHT:
return ac.lb->GetVisibleRows();
case SCI_AUTOCSETMAXWIDTH:
maxListWidth = static_cast<int>(wParam);
break;
case SCI_AUTOCGETMAXWIDTH:
return maxListWidth;
case SCI_REGISTERIMAGE:
ac.lb->RegisterImage(static_cast<int>(wParam), ConstCharPtrFromSPtr(lParam));
break;
case SCI_REGISTERRGBAIMAGE:
ac.lb->RegisterRGBAImage(static_cast<int>(wParam), static_cast<int>(sizeRGBAImage.x), static_cast<int>(sizeRGBAImage.y),
ConstUCharPtrFromSPtr(lParam));
break;
case SCI_CLEARREGISTEREDIMAGES:
ac.lb->ClearRegisteredImages();
break;
case SCI_AUTOCSETTYPESEPARATOR:
ac.SetTypesep(static_cast<char>(wParam));
break;
case SCI_AUTOCGETTYPESEPARATOR:
return ac.GetTypesep();
case SCI_CALLTIPSHOW:
CallTipShow(LocationFromPosition(wParam), NotificationPosition::None,
ConstCharPtrFromSPtr(lParam));
break;
case SCI_SHOWNOTIFICATION:
CallTipShow(LocationFromPosition(0), static_cast<NotificationPosition>(wParam + 1),
ConstCharPtrFromSPtr(lParam));
break;
case SCI_CALLTIPCANCEL:
ct.CallTipCancel();
break;
case SCI_CALLTIPACTIVE:
return ct.inCallTipMode;
case SCI_CALLTIPPOSSTART:
return ct.posStartCallTip;
case SCI_CALLTIPSETPOSSTART:
ct.posStartCallTip = wParam;
break;
case SCI_CALLTIPSETHLT:
ct.SetHighlight(wParam, lParam);
break;
case SCI_CALLTIPSETBACK:
ct.colourBG = ColourDesired(static_cast<int>(wParam));
vs.styles[STYLE_CALLTIP].back = ct.colourBG;
InvalidateStyleRedraw();
break;
case SCI_CALLTIPSETFORE:
ct.colourUnSel = ColourDesired(static_cast<int>(wParam));
vs.styles[STYLE_CALLTIP].fore = ct.colourUnSel;
InvalidateStyleRedraw();
break;
case SCI_CALLTIPSETFOREHLT:
ct.colourSel = ColourDesired(static_cast<int>(wParam));
InvalidateStyleRedraw();
break;
case SCI_CALLTIPUSESTYLE:
ct.SetTabSize(static_cast<int>(std::lround(wParam * vs.aveCharWidth)));
InvalidateStyleRedraw();
break;
case SCI_CALLTIPSETPOSITION:
ct.SetPosition(wParam != 0);
InvalidateStyleRedraw();
break;
#if SCI_EnablePopupMenu
case SCI_USEPOPUP:
displayPopupMenu = static_cast<int>(wParam);
break;
#endif
case SCI_SETLEXER:
DocumentLexState()->SetLexer(static_cast<int>(wParam));
break;
case SCI_SETILEXER:
DocumentLexState()->SetInstance(reinterpret_cast<ILexer5 *>(lParam));
return 0;
case SCI_GETLEXER:
return DocumentLexState()->GetIdentifier();
case SCI_COLOURISE:
if (DocumentLexState()->lexLanguage == SCLEX_CONTAINER) {
pdoc->ModifiedAt(wParam);
NotifyStyleToNeeded((lParam == -1) ? pdoc->Length() : lParam);
} else {
DocumentLexState()->Colourise(wParam, lParam);
}
Redraw();
break;
case SCI_SETPROPERTY:
DocumentLexState()->PropSet(ConstCharPtrFromUPtr(wParam),
ConstCharPtrFromSPtr(lParam));
break;
case SCI_GETPROPERTY:
return StringResult(lParam, DocumentLexState()->PropGet(ConstCharPtrFromUPtr(wParam)));
case SCI_GETPROPERTYEXPANDED:
return DocumentLexState()->PropGetExpanded(ConstCharPtrFromUPtr(wParam),
CharPtrFromSPtr(lParam));
case SCI_GETPROPERTYINT:
return DocumentLexState()->PropGetInt(ConstCharPtrFromUPtr(wParam), static_cast<int>(lParam));
case SCI_SETKEYWORDS:
DocumentLexState()->SetWordList(static_cast<int>(wParam & KEYWORDSET_INDEXMASK), (wParam & KEYWORDSET_TOLOWER) != 0, ConstCharPtrFromSPtr(lParam));
break;
case SCI_SETLEXERLANGUAGE:
DocumentLexState()->SetLexerLanguage(ConstCharPtrFromSPtr(lParam));
break;
case SCI_GETLEXERLANGUAGE:
return StringResult(lParam, DocumentLexState()->GetName());
#if 0//def SCI_LEXER
case SCI_LOADLEXERLIBRARY:
ExternalLexerLoad(ConstCharPtrFromSPtr(lParam));
break;
#endif
case SCI_PRIVATELEXERCALL:
return reinterpret_cast<sptr_t>(
DocumentLexState()->PrivateCall(static_cast<int>(wParam), reinterpret_cast<void *>(lParam)));
#ifdef INCLUDE_DEPRECATED_FEATURES
case SCI_GETSTYLEBITSNEEDED:
return 8;
#endif
case SCI_PROPERTYNAMES:
return StringResult(lParam, DocumentLexState()->PropertyNames());
case SCI_PROPERTYTYPE:
return DocumentLexState()->PropertyType(ConstCharPtrFromUPtr(wParam));
case SCI_DESCRIBEPROPERTY:
return StringResult(lParam,
DocumentLexState()->DescribeProperty(ConstCharPtrFromUPtr(wParam)));
case SCI_DESCRIBEKEYWORDSETS:
return StringResult(lParam, DocumentLexState()->DescribeWordListSets());
case SCI_GETLINEENDTYPESSUPPORTED:
return DocumentLexState()->LineEndTypesSupported();
case SCI_ALLOCATESUBSTYLES:
return DocumentLexState()->AllocateSubStyles(static_cast<int>(wParam), static_cast<int>(lParam));
case SCI_GETSUBSTYLESSTART:
return DocumentLexState()->SubStylesStart(static_cast<int>(wParam));
case SCI_GETSUBSTYLESLENGTH:
return DocumentLexState()->SubStylesLength(static_cast<int>(wParam));
case SCI_GETSTYLEFROMSUBSTYLE:
return DocumentLexState()->StyleFromSubStyle(static_cast<int>(wParam));
case SCI_GETPRIMARYSTYLEFROMSTYLE:
return DocumentLexState()->PrimaryStyleFromStyle(static_cast<int>(wParam));
case SCI_FREESUBSTYLES:
DocumentLexState()->FreeSubStyles();
break;
case SCI_SETIDENTIFIERS:
DocumentLexState()->SetIdentifiers(static_cast<int>(wParam),
ConstCharPtrFromSPtr(lParam));
break;
case SCI_DISTANCETOSECONDARYSTYLES:
return DocumentLexState()->DistanceToSecondaryStyles();
case SCI_GETSUBSTYLEBASES:
return StringResult(lParam, DocumentLexState()->GetSubStyleBases());
case SCI_GETNAMEDSTYLES:
return DocumentLexState()->NamedStyles();
case SCI_NAMEOFSTYLE:
return StringResult(lParam, DocumentLexState()->
NameOfStyle(static_cast<int>(wParam)));
case SCI_TAGSOFSTYLE:
return StringResult(lParam, DocumentLexState()->
TagsOfStyle(static_cast<int>(wParam)));
case SCI_DESCRIPTIONOFSTYLE:
return StringResult(lParam, DocumentLexState()->
DescriptionOfStyle(static_cast<int>(wParam)));
default:
return Editor::WndProc(iMessage, wParam, lParam);
}
return 0;
}
|
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021 Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <sstream>
#include <Corrade/TestSuite/Tester.h>
#include <Corrade/Utility/DebugStl.h>
#include "Magnum/Vk/DeviceFeatures.h"
namespace Magnum { namespace Vk { namespace Test { namespace {
struct DeviceFeaturesTest: TestSuite::Tester {
explicit DeviceFeaturesTest();
void mapping();
void debugFeature();
void debugFeatures();
};
DeviceFeaturesTest::DeviceFeaturesTest() {
addTests({&DeviceFeaturesTest::mapping,
&DeviceFeaturesTest::debugFeature,
&DeviceFeaturesTest::debugFeatures});
}
void DeviceFeaturesTest::mapping() {
UnsignedInt firstUnhandled = 0xff;
UnsignedInt nextHandled = 0;
for(UnsignedInt i = 0; i <= 0xff; ++i) {
CORRADE_ITERATION(i);
const auto feature = DeviceFeature(i);
/* Each case verifies:
- that the entries are ordered by number by comparing a function to
expected result (so insertion here is done in proper place)
- that there was no gap (unhandled value inside the range)
- that the Debug output is equivalent to the name */
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wswitch"
#endif
switch(feature) {
#define _c(value, field) \
case DeviceFeature::value: { \
std::ostringstream out; \
Debug{&out, Debug::Flag::NoNewlineAtTheEnd} << DeviceFeature::value; \
CORRADE_COMPARE(out.str(), "Vk::DeviceFeature::" #value); \
CORRADE_COMPARE(nextHandled, i); \
CORRADE_COMPARE(firstUnhandled, 0xff); \
++nextHandled; \
continue; \
}
#define _cver(value, field, suffix, version) _c(value, field)
#define _cext(value, field, suffix, extension) _c(value, field)
#include "Magnum/Vk/Implementation/deviceFeatureMapping.hpp"
#undef _c
#undef _cver
#undef _cext
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
/* Not handled by any value, remember -- we might either be at the end
of the enum range (which is okay) or some value might be unhandled
here */
firstUnhandled = i;
}
CORRADE_COMPARE(firstUnhandled, 0xff);
}
void DeviceFeaturesTest::debugFeature() {
std::ostringstream out;
Debug{&out} << DeviceFeature::FullDrawIndexUnsignedInt << DeviceFeature::VulkanMemoryModel << DeviceFeature(0xab);
CORRADE_COMPARE(out.str(), "Vk::DeviceFeature::FullDrawIndexUnsignedInt Vk::DeviceFeature::VulkanMemoryModel Vk::DeviceFeature(0xab)\n");
}
void DeviceFeaturesTest::debugFeatures() {
std::ostringstream out;
Debug{&out} << (DeviceFeature::FullDrawIndexUnsignedInt|DeviceFeature::VulkanMemoryModel|DeviceFeature(0xab)|DeviceFeature(0xcc)) << DeviceFeatures{};
CORRADE_COMPARE(out.str(), "Vk::DeviceFeature::FullDrawIndexUnsignedInt|Vk::DeviceFeature::VulkanMemoryModel|Vk::DeviceFeature(0xab)|Vk::DeviceFeature(0xcc) Vk::DeviceFeatures{}\n");
}
}}}}
CORRADE_TEST_MAIN(Magnum::Vk::Test::DeviceFeaturesTest)
|
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2008 Live Networks, Inc. All rights reserved.
// Qualcomm "PureVoice" (aka. "QCELP") Audio RTP Sources
// Implementation
#include "QCELPAudioRTPSource.hh"
#include "MultiFramedRTPSource.hh"
#include "FramedFilter.hh"
#include <string.h>
#include <stdlib.h>
// This source is implemented internally by two separate sources:
// (i) a RTP source for the raw (interleaved) QCELP frames, and
// (ii) a deinterleaving filter that reads from this.
// Define these two new classes here:
class RawQCELPRTPSource: public MultiFramedRTPSource {
public:
static RawQCELPRTPSource* createNew(UsageEnvironment& env,
Groupsock* RTPgs,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency);
unsigned char interleaveL() const { return fInterleaveL; }
unsigned char interleaveN() const { return fInterleaveN; }
unsigned char& frameIndex() { return fFrameIndex; } // index within pkt
private:
RawQCELPRTPSource(UsageEnvironment& env, Groupsock* RTPgs,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency);
// called only by createNew()
virtual ~RawQCELPRTPSource();
private:
// redefined virtual functions:
virtual Boolean processSpecialHeader(BufferedPacket* packet,
unsigned& resultSpecialHeaderSize);
virtual char const* MIMEtype() const;
virtual Boolean hasBeenSynchronizedUsingRTCP();
private:
unsigned char fInterleaveL, fInterleaveN, fFrameIndex;
unsigned fNumSuccessiveSyncedPackets;
};
class QCELPDeinterleaver: public FramedFilter {
public:
static QCELPDeinterleaver* createNew(UsageEnvironment& env,
RawQCELPRTPSource* inputSource);
private:
QCELPDeinterleaver(UsageEnvironment& env,
RawQCELPRTPSource* inputSource);
// called only by "createNew()"
virtual ~QCELPDeinterleaver();
static void afterGettingFrame(void* clientData, unsigned frameSize,
unsigned numTruncatedBytes,
struct timeval presentationTime,
unsigned durationInMicroseconds);
void afterGettingFrame1(unsigned frameSize, struct timeval presentationTime);
private:
// Redefined virtual functions:
void doGetNextFrame();
private:
class QCELPDeinterleavingBuffer* fDeinterleavingBuffer;
Boolean fNeedAFrame;
};
////////// QCELPAudioRTPSource implementation //////////
FramedSource*
QCELPAudioRTPSource::createNew(UsageEnvironment& env,
Groupsock* RTPgs,
RTPSource*& resultRTPSource,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency) {
RawQCELPRTPSource* rawRTPSource;
resultRTPSource = rawRTPSource
= RawQCELPRTPSource::createNew(env, RTPgs, rtpPayloadFormat,
rtpTimestampFrequency);
if (resultRTPSource == NULL) return NULL;
QCELPDeinterleaver* deinterleaver
= QCELPDeinterleaver::createNew(env, rawRTPSource);
if (deinterleaver == NULL) {
Medium::close(resultRTPSource);
resultRTPSource = NULL;
}
return deinterleaver;
}
////////// QCELPBufferedPacket and QCELPBufferedPacketFactory //////////
// A subclass of BufferedPacket, used to separate out QCELP frames.
class QCELPBufferedPacket: public BufferedPacket {
public:
QCELPBufferedPacket(RawQCELPRTPSource& ourSource);
virtual ~QCELPBufferedPacket();
private: // redefined virtual functions
virtual unsigned nextEnclosedFrameSize(unsigned char*& framePtr,
unsigned dataSize);
private:
RawQCELPRTPSource& fOurSource;
};
class QCELPBufferedPacketFactory: public BufferedPacketFactory {
private: // redefined virtual functions
virtual BufferedPacket* createNewPacket(MultiFramedRTPSource* ourSource);
};
///////// RawQCELPRTPSource implementation ////////
RawQCELPRTPSource*
RawQCELPRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency) {
return new RawQCELPRTPSource(env, RTPgs, rtpPayloadFormat,
rtpTimestampFrequency);
}
RawQCELPRTPSource::RawQCELPRTPSource(UsageEnvironment& env,
Groupsock* RTPgs,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency)
: MultiFramedRTPSource(env, RTPgs, rtpPayloadFormat,
rtpTimestampFrequency,
new QCELPBufferedPacketFactory),
fInterleaveL(0), fInterleaveN(0), fFrameIndex(0),
fNumSuccessiveSyncedPackets(0) {
}
RawQCELPRTPSource::~RawQCELPRTPSource() {
}
Boolean RawQCELPRTPSource
::processSpecialHeader(BufferedPacket* packet,
unsigned& resultSpecialHeaderSize) {
unsigned char* headerStart = packet->data();
unsigned packetSize = packet->dataSize();
// First, check whether this packet's RTP timestamp is synchronized:
if (RTPSource::hasBeenSynchronizedUsingRTCP()) {
++fNumSuccessiveSyncedPackets;
} else {
fNumSuccessiveSyncedPackets = 0;
}
// There's a 1-byte header indicating the interleave parameters
if (packetSize < 1) return False;
// Get the interleaving parameters from the 1-byte header,
// and check them for validity:
unsigned char const firstByte = headerStart[0];
unsigned char const interleaveL = (firstByte&0x38)>>3;
unsigned char const interleaveN = firstByte&0x07;
#ifdef DEBUG
fprintf(stderr, "packetSize: %d, interleaveL: %d, interleaveN: %d\n", packetSize, interleaveL, interleaveN);
#endif
if (interleaveL > 5 || interleaveN > interleaveL) return False; //invalid
fInterleaveL = interleaveL;
fInterleaveN = interleaveN;
fFrameIndex = 0; // initially
resultSpecialHeaderSize = 1;
return True;
}
char const* RawQCELPRTPSource::MIMEtype() const {
return "audio/QCELP";
}
Boolean RawQCELPRTPSource::hasBeenSynchronizedUsingRTCP() {
// Don't report ourselves as being synchronized until we've received
// at least a complete interleave cycle of synchronized packets.
// This ensures that the receiver is currently getting a frame from
// a packet that was synchronized.
if (fNumSuccessiveSyncedPackets > (unsigned)(fInterleaveL+1)) {
fNumSuccessiveSyncedPackets = fInterleaveL+2; // prevents overflow
return True;
}
return False;
}
///// QCELPBufferedPacket and QCELPBufferedPacketFactory implementation
QCELPBufferedPacket::QCELPBufferedPacket(RawQCELPRTPSource& ourSource)
: fOurSource(ourSource) {
}
QCELPBufferedPacket::~QCELPBufferedPacket() {
}
unsigned QCELPBufferedPacket::
nextEnclosedFrameSize(unsigned char*& framePtr, unsigned dataSize) {
// The size of the QCELP frame is determined by the first byte:
if (dataSize == 0) return 0; // sanity check
unsigned char const firstByte = framePtr[0];
unsigned frameSize;
switch (firstByte) {
case 0: { frameSize = 1; break; }
case 1: { frameSize = 4; break; }
case 2: { frameSize = 8; break; }
case 3: { frameSize = 17; break; }
case 4: { frameSize = 35; break; }
default: { frameSize = 0; break; }
}
#ifdef DEBUG
fprintf(stderr, "QCELPBufferedPacket::nextEnclosedFrameSize(): frameSize: %d, dataSize: %d\n", frameSize, dataSize);
#endif
if (dataSize < frameSize) return 0;
++fOurSource.frameIndex();
return frameSize;
}
BufferedPacket* QCELPBufferedPacketFactory
::createNewPacket(MultiFramedRTPSource* ourSource) {
return new QCELPBufferedPacket((RawQCELPRTPSource&)(*ourSource));
}
///////// QCELPDeinterleavingBuffer /////////
// (used to implement QCELPDeinterleaver)
#define QCELP_MAX_FRAME_SIZE 35
#define QCELP_MAX_INTERLEAVE_L 5
#define QCELP_MAX_FRAMES_PER_PACKET 10
#define QCELP_MAX_INTERLEAVE_GROUP_SIZE \
((QCELP_MAX_INTERLEAVE_L+1)*QCELP_MAX_FRAMES_PER_PACKET)
class QCELPDeinterleavingBuffer {
public:
QCELPDeinterleavingBuffer();
virtual ~QCELPDeinterleavingBuffer();
void deliverIncomingFrame(unsigned frameSize,
unsigned char interleaveL,
unsigned char interleaveN,
unsigned char frameIndex,
unsigned short packetSeqNum,
struct timeval presentationTime);
Boolean retrieveFrame(unsigned char* to, unsigned maxSize,
unsigned& resultFrameSize, unsigned& resultNumTruncatedBytes,
struct timeval& resultPresentationTime);
unsigned char* inputBuffer() { return fInputBuffer; }
unsigned inputBufferSize() const { return QCELP_MAX_FRAME_SIZE; }
private:
class FrameDescriptor {
public:
FrameDescriptor();
virtual ~FrameDescriptor();
unsigned frameSize;
unsigned char* frameData;
struct timeval presentationTime;
};
// Use two banks of descriptors - one for incoming, one for outgoing
FrameDescriptor fFrames[QCELP_MAX_INTERLEAVE_GROUP_SIZE][2];
unsigned char fIncomingBankId; // toggles between 0 and 1
unsigned char fIncomingBinMax; // in the incoming bank
unsigned char fOutgoingBinMax; // in the outgoing bank
unsigned char fNextOutgoingBin;
Boolean fHaveSeenPackets;
u_int16_t fLastPacketSeqNumForGroup;
unsigned char* fInputBuffer;
struct timeval fLastRetrievedPresentationTime;
};
////////// QCELPDeinterleaver implementation /////////
QCELPDeinterleaver*
QCELPDeinterleaver::createNew(UsageEnvironment& env,
RawQCELPRTPSource* inputSource) {
return new QCELPDeinterleaver(env, inputSource);
}
QCELPDeinterleaver::QCELPDeinterleaver(UsageEnvironment& env,
RawQCELPRTPSource* inputSource)
: FramedFilter(env, inputSource),
fNeedAFrame(False) {
fDeinterleavingBuffer = new QCELPDeinterleavingBuffer();
}
QCELPDeinterleaver::~QCELPDeinterleaver() {
delete fDeinterleavingBuffer;
}
static unsigned const uSecsPerFrame = 20000; // 20 ms
void QCELPDeinterleaver::doGetNextFrame() {
// First, try getting a frame from the deinterleaving buffer:
if (fDeinterleavingBuffer->retrieveFrame(fTo, fMaxSize,
fFrameSize, fNumTruncatedBytes,
fPresentationTime)) {
// Success!
fNeedAFrame = False;
fDurationInMicroseconds = uSecsPerFrame;
// Call our own 'after getting' function. Because we're not a 'leaf'
// source, we can call this directly, without risking
// infinite recursion
afterGetting(this);
return;
}
// No luck, so ask our source for help:
fNeedAFrame = True;
if (!fInputSource->isCurrentlyAwaitingData()) {
fInputSource->getNextFrame(fDeinterleavingBuffer->inputBuffer(),
fDeinterleavingBuffer->inputBufferSize(),
afterGettingFrame, this,
FramedSource::handleClosure, this);
}
}
void QCELPDeinterleaver
::afterGettingFrame(void* clientData, unsigned frameSize,
unsigned /*numTruncatedBytes*/,
struct timeval presentationTime,
unsigned /*durationInMicroseconds*/) {
QCELPDeinterleaver* deinterleaver = (QCELPDeinterleaver*)clientData;
deinterleaver->afterGettingFrame1(frameSize, presentationTime);
}
void QCELPDeinterleaver
::afterGettingFrame1(unsigned frameSize, struct timeval presentationTime) {
RawQCELPRTPSource* source = (RawQCELPRTPSource*)fInputSource;
// First, put the frame into our deinterleaving buffer:
fDeinterleavingBuffer
->deliverIncomingFrame(frameSize, source->interleaveL(),
source->interleaveN(), source->frameIndex(),
source->curPacketRTPSeqNum(),
presentationTime);
// Then, try delivering a frame to the client (if he wants one):
if (fNeedAFrame) doGetNextFrame();
}
////////// QCELPDeinterleavingBuffer implementation /////////
QCELPDeinterleavingBuffer::QCELPDeinterleavingBuffer()
: fIncomingBankId(0), fIncomingBinMax(0),
fOutgoingBinMax(0), fNextOutgoingBin(0),
fHaveSeenPackets(False) {
fInputBuffer = new unsigned char[QCELP_MAX_FRAME_SIZE];
}
QCELPDeinterleavingBuffer::~QCELPDeinterleavingBuffer() {
delete[] fInputBuffer;
}
void QCELPDeinterleavingBuffer
::deliverIncomingFrame(unsigned frameSize,
unsigned char interleaveL,
unsigned char interleaveN,
unsigned char frameIndex,
unsigned short packetSeqNum,
struct timeval presentationTime) {
// First perform a sanity check on the parameters:
// (This is overkill, as the source should have already done this.)
if (frameSize > QCELP_MAX_FRAME_SIZE
|| interleaveL > QCELP_MAX_INTERLEAVE_L || interleaveN > interleaveL
|| frameIndex == 0 || frameIndex > QCELP_MAX_FRAMES_PER_PACKET) {
#ifdef DEBUG
fprintf(stderr, "QCELPDeinterleavingBuffer::deliverIncomingFrame() param sanity check failed (%d,%d,%d,%d)\n", frameSize, interleaveL, interleaveN, frameIndex);
#endif
exit(1);
}
// The input "presentationTime" was that of the first frame in this
// packet. Update it for the current frame:
unsigned uSecIncrement = (frameIndex-1)*(interleaveL+1)*uSecsPerFrame;
presentationTime.tv_usec += uSecIncrement;
presentationTime.tv_sec += presentationTime.tv_usec/1000000;
presentationTime.tv_usec = presentationTime.tv_usec%1000000;
// Next, check whether this packet is part of a new interleave group
if (!fHaveSeenPackets
|| seqNumLT(fLastPacketSeqNumForGroup, packetSeqNum)) {
// We've moved to a new interleave group
fHaveSeenPackets = True;
fLastPacketSeqNumForGroup = packetSeqNum + interleaveL - interleaveN;
// Switch the incoming and outgoing banks:
fIncomingBankId ^= 1;
unsigned char tmp = fIncomingBinMax;
fIncomingBinMax = fOutgoingBinMax;
fOutgoingBinMax = tmp;
fNextOutgoingBin = 0;
}
// Now move the incoming frame into the appropriate bin:
unsigned const binNumber
= interleaveN + (frameIndex-1)*(interleaveL+1);
FrameDescriptor& inBin = fFrames[binNumber][fIncomingBankId];
unsigned char* curBuffer = inBin.frameData;
inBin.frameData = fInputBuffer;
inBin.frameSize = frameSize;
inBin.presentationTime = presentationTime;
if (curBuffer == NULL) curBuffer = new unsigned char[QCELP_MAX_FRAME_SIZE];
fInputBuffer = curBuffer;
if (binNumber >= fIncomingBinMax) {
fIncomingBinMax = binNumber + 1;
}
}
Boolean QCELPDeinterleavingBuffer
::retrieveFrame(unsigned char* to, unsigned maxSize,
unsigned& resultFrameSize, unsigned& resultNumTruncatedBytes,
struct timeval& resultPresentationTime) {
if (fNextOutgoingBin >= fOutgoingBinMax) return False; // none left
FrameDescriptor& outBin = fFrames[fNextOutgoingBin][fIncomingBankId^1];
unsigned char* fromPtr;
unsigned char fromSize = outBin.frameSize;
outBin.frameSize = 0; // for the next time this bin is used
// Check whether this frame is missing; if so, return an 'erasure' frame:
unsigned char erasure = 14;
if (fromSize == 0) {
fromPtr = &erasure;
fromSize = 1;
// Compute this erasure frame's presentation time via extrapolation:
resultPresentationTime = fLastRetrievedPresentationTime;
resultPresentationTime.tv_usec += uSecsPerFrame;
if (resultPresentationTime.tv_usec >= 1000000) {
++resultPresentationTime.tv_sec;
resultPresentationTime.tv_usec -= 1000000;
}
} else {
// Normal case - a frame exists:
fromPtr = outBin.frameData;
resultPresentationTime = outBin.presentationTime;
}
fLastRetrievedPresentationTime = resultPresentationTime;
if (fromSize > maxSize) {
resultNumTruncatedBytes = fromSize - maxSize;
resultFrameSize = maxSize;
} else {
resultNumTruncatedBytes = 0;
resultFrameSize = fromSize;
}
memmove(to, fromPtr, resultFrameSize);
++fNextOutgoingBin;
return True;
}
QCELPDeinterleavingBuffer::FrameDescriptor::FrameDescriptor()
: frameSize(0), frameData(NULL) {
}
QCELPDeinterleavingBuffer::FrameDescriptor::~FrameDescriptor() {
delete[] frameData;
}
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using db = double;
using str = string; // yay python!
using pi = pair<int,int>;
using pl = pair<ll,ll>;
using pd = pair<db,db>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<db>;
using vs = vector<str>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vpd = vector<pd>;
#define tcT template<class T
// ^ lol this makes everything look weird but I'll try it
tcT> using V = vector<T>;
tcT, size_t SZ> using AR = array<T,SZ>;
// pairs
#define mp make_pair
#define f first
#define s second
// vectors
#define sz(x) (int)(x).size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define sor(x) sort(all(x))
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
// loops
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)
const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18; // not too close to LLONG_MAX
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1}; // for every grid problem!!
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());
// helper funcs
constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set
constexpr int bits(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up
ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down
tcT> bool ckmin(T& a, const T& b) {
return b < a ? a = b, 1 : 0; } // set a = min(a,b)
tcT> bool ckmax(T& a, const T& b) {
return a < b ? a = b, 1 : 0; }
#define tcTU tcT, class U
tcTU> T fstTrue(T lo, T hi, U f) {
hi ++; assert(lo <= hi); // assuming f is increasing
while (lo < hi) { // find first index such that f is true
T mid = lo+(hi-lo)/2;
f(mid) ? hi = mid : lo = mid+1;
}
return lo;
}
tcTU> T lstTrue(T lo, T hi, U f) {
lo --; assert(lo <= hi); // assuming f is decreasing
while (lo < hi) { // find first index such that f is true
T mid = lo+(hi-lo+1)/2;
f(mid) ? lo = mid : hi = mid-1;
}
return lo;
}
tcT> void remDup(vector<T>& v) { // sort and remove duplicates
sort(all(v)); v.erase(unique(all(v)),end(v)); }
tcTU> void erase(T& t, const U& u) { // don't erase
auto it = t.find(u); assert(it != end(t));
t.erase(u); } // element that doesn't exist from (multi)set
// INPUT
#define tcTUU tcT, class ...U
tcT> void re(complex<T>& c);
tcTU> void re(pair<T,U>& p);
tcT> void re(vector<T>& v);
tcT, size_t SZ> void re(AR<T,SZ>& a);
tcT> void re(T& x) { cin >> x; }
void re(db& d) { str t; re(t); d = stod(t); }
void re(ld& d) { str t; re(t); d = stold(t); }
tcTUU> void re(T& t, U&... u) { re(t); re(u...); }
tcT> void re(complex<T>& c) { T a,b; re(a,b); c = {a,b}; }
tcTU> void re(pair<T,U>& p) { re(p.f,p.s); }
tcT> void re(vector<T>& x) { trav(a,x) re(a); }
tcT, size_t SZ> void re(AR<T,SZ>& x) { trav(a,x) re(a); }
// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
str ts(bool b) {
#ifdef LOCAL
return b ? "true" : "false";
#else
return ts((int)b);
#endif
}
tcT> str ts(complex<T> c) {
stringstream ss; ss << c; return ss.str(); }
str ts(vector<bool> v) {
str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]);
res += "}"; return res; }
template<size_t SZ> str ts(bitset<SZ> b) {
str res = ""; F0R(i,SZ) res += char('0'+b[i]);
return res; }
tcTU> str ts(pair<T,U> p);
tcT> str ts(T v) { // containers with begin(), end()
#ifdef LOCAL
bool fst = 1; str res = "{";
for (const auto& x: v) {
if (!fst) res += ", ";
fst = 0; res += ts(x);
}
res += "}"; return res;
#else
bool fst = 1; str res = "";
for (const auto& x: v) {
if (!fst) res += " ";
fst = 0; res += ts(x);
}
return res;
#endif
}
tcTU> str ts(pair<T,U> p) {
#ifdef LOCAL
return "("+ts(p.f)+", "+ts(p.s)+")";
#else
return ts(p.f)+" "+ts(p.s);
#endif
}
// OUTPUT
tcT> void pr(T x) { cout << ts(x); }
tcTUU> void pr(const T& t, const U&... u) {
pr(t); pr(u...); }
void ps() { pr("\n"); } // print w/ spaces
tcTUU> void ps(const T& t, const U&... u) {
pr(t); if (sizeof...(u)) pr(" "); ps(u...); }
// DEBUG
void DBG() { cerr << "]" << endl; }
tcTUU> void DBG(const T& t, const U&... u) {
cerr << ts(t); if (sizeof...(u)) cerr << ", ";
DBG(u...); }
#ifdef LOCAL // compile with -DLOCAL, chk -> fake assert
#define dbg(...) cerr << "Line(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#define chk(...) if (!(__VA_ARGS__)) cerr << "Line(" << __LINE__ << ") -> function(" \
<< __FUNCTION__ << ") -> CHK FAILED: (" << #__VA_ARGS__ << ")" << "\n", exit(0);
#else
#define dbg(...) 0
#define chk(...) 0
#endif
// FILE I/O
void setIn(str s) { freopen(s.c_str(),"r",stdin); }
void setOut(str s) { freopen(s.c_str(),"w",stdout); }
void unsyncIO() { cin.tie(0)->sync_with_stdio(0); }
void setIO(str s = "") {
unsyncIO();
// cin.exceptions(cin.failbit);
// throws exception when do smth illegal
// ex. try to read letter into int
if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
}
int n;
void solve() {
re(n);
vi a(n),b(n),c(n); re(a,b,c);
vi ans = {a[0]};
FOR(i,1,n-1) {
if (a[i] == ans.bk) ans.pb(b[i]);
else ans.pb(a[i]);
}
if (a[n-1] == ans[0] || a[n-1] == ans.bk) {
if (b[n-1] == ans[0] || b[n-1] == ans.bk) {
ans.pb(c[n-1]);
} else ans.pb(b[n-1]);
} else {
ans.pb(a[n-1]);
}
trav(t,ans) pr(t,' ');
ps();
}
int main() {
setIO();
int T; re(T);
F0R(i,T) solve();
// you should actually read the stuff at the bottom
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/
|
// Copyright (c) 2018-2019 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
#include "Blueprints/AccelByteCategoryBlueprints.h"
#include "Api/AccelByteCategoryApi.h"
#include "Core/AccelByteSettings.h"
#include "Core/AccelByteCredentials.h"
#include "Core/AccelByteRegistry.h"
using AccelByte::Api::Category;
using AccelByte::FErrorHandler;
using AccelByte::THandler;
using AccelByte::Settings;
using AccelByte::Credentials;
void UAccelByteBlueprintsCategory::GetRootCategories(const FString& Language, const FGetRootCategoriesSuccess& OnSuccess, const FBlueprintErrorHandler& OnError)
{
FRegistry::Category.GetRootCategories(Language, THandler<TArray<FAccelByteModelsCategoryInfo>>::CreateLambda([OnSuccess](const TArray<FAccelByteModelsCategoryInfo>& Result)
{
OnSuccess.ExecuteIfBound(Result);
}),
FErrorHandler::CreateLambda([OnError](int32 ErrorCode, const FString& ErrorMessage)
{
OnError.ExecuteIfBound(ErrorCode, ErrorMessage);
}));
}
void UAccelByteBlueprintsCategory::GetCategory(const FString& CategoryPath, const FString& Language, const FGetCategorySuccess& OnSuccess, const FBlueprintErrorHandler& OnError)
{
FRegistry::Category.GetCategory(CategoryPath, Language, THandler<FAccelByteModelsCategoryInfo>::CreateLambda([OnSuccess](const FAccelByteModelsCategoryInfo& Result)
{
OnSuccess.ExecuteIfBound(Result);
}),
FErrorHandler::CreateLambda([OnError](int32 ErrorCode, const FString& ErrorMessage)
{
OnError.ExecuteIfBound(ErrorCode, ErrorMessage);
}));
}
void UAccelByteBlueprintsCategory::GetChildCategories(const FString& Language, const FString& CategoryPath, const FGetChildCategoriesSuccess& OnSuccess, const FBlueprintErrorHandler& OnError)
{
FRegistry::Category.GetChildCategories(Language, CategoryPath, THandler<TArray<FAccelByteModelsCategoryInfo>>::CreateLambda([OnSuccess](const TArray<FAccelByteModelsCategoryInfo>& Result)
{
OnSuccess.ExecuteIfBound(Result);
}),
FErrorHandler::CreateLambda([OnError](int32 ErrorCode, const FString& ErrorMessage)
{
OnError.ExecuteIfBound(ErrorCode, ErrorMessage);
}));
}
void UAccelByteBlueprintsCategory::GetDescendantCategories(const FString& Language, const FString& CategoryPath, const FGetDescendantCategoriesSuccess& OnSuccess, const FBlueprintErrorHandler& OnError)
{
FRegistry::Category.GetDescendantCategories(Language, CategoryPath, THandler<TArray<FAccelByteModelsCategoryInfo>>::CreateLambda([OnSuccess](const TArray<FAccelByteModelsCategoryInfo>& Result)
{
OnSuccess.ExecuteIfBound(Result);
}),
FErrorHandler::CreateLambda([OnError](int32 ErrorCode, const FString& ErrorMessage)
{
OnError.ExecuteIfBound(ErrorCode, ErrorMessage);
}));
}
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "Elastos.Droid.App.h"
#include "elastos/droid/media/projection/CMediaProjectionManager.h"
#include "elastos/droid/utility/CArrayMap.h"
using Elastos::Utility::IMap;
using Elastos::Droid::Utility::CArrayMap;
namespace Elastos {
namespace Droid {
namespace Media {
namespace Projection {
ECode CMediaProjectionManager::OnStartRunnable::Run()
{
return mCallback->OnStart(mInfo);
}
ECode CMediaProjectionManager::OnStopRunnable::Run()
{
return mCallback->OnStop(mInfo);
}
CAR_INTERFACE_IMPL(CMediaProjectionManager::CallbackDelegate, Object, IIMediaProjectionWatcherCallback)
CMediaProjectionManager::CallbackDelegate::CallbackDelegate(
/* [in] */ CMediaProjectionManager* host,
/* [in] */ IMediaProjectionManagerCallback * callback,
/* [in] */ IHandler * _handler)
{
mHost = host;
mCallback = callback;
AutoPtr<IHandler> handler = _handler;
if (handler == NULL) {
CHandler::New((IHandler**)&handler);
}
mHandler = handler;
}
ECode CMediaProjectionManager::CallbackDelegate::OnStart(
/* [in] */ IMediaProjectionInfo * info)
{
AutoPtr<OnStartRunnable> runnable = new OnStartRunnable(this, mCallback, info);
Boolean b;
mHandler->Post(runnable, &b);
return NOERROR;
}
ECode CMediaProjectionManager::CallbackDelegate::OnStop(
/* [in] */ IMediaProjectionInfo * info)
{
AutoPtr<OnStopRunnable> runnable = new OnStopRunnable(this, mCallback, info);
Boolean b;
mHandler->Post(runnable, &b);
return NOERROR;
}
String CMediaProjectionManager::TAG("MediaProjectionManager");
CAR_INTERFACE_IMPL(CMediaProjectionManager, Object, IMediaProjectionManager)
CAR_OBJECT_IMPL(CMediaProjectionManager)
CMediaProjectionManager::CMediaProjectionManager()
{
}
CMediaProjectionManager::~CMediaProjectionManager()
{
}
ECode CMediaProjectionManager::constructor(
/* [in] */ IContext * context)
{
mContext = context;
AutoPtr<IInterface> service = ServiceManager::GetService(IContext::MEDIA_PROJECTION_SERVICE);
mService = IIMediaProjectionManager::Probe(service.Get());
CArrayMap::New((IArrayMap**)&mCallbacks);
return NOERROR;
}
ECode CMediaProjectionManager::CreateScreenCaptureIntent(
/* [out] */ IIntent ** result)
{
VALIDATE_NOT_NULL(result)
AutoPtr<IIntent> i;
CIntent::New((IIntent**)&i);
i->SetClassName(String("Elastos.Droid.SystemUI"),
String("Elastos.Droid.SystemUI.Media.CMediaProjectionPermissionActivity"));
*result = i;
REFCOUNT_ADD(*result)
return NOERROR;
}
ECode CMediaProjectionManager::GetMediaProjection(
/* [in] */ Int32 resultCode,
/* [in] */ IIntent * resultData,
/* [out] */ IMediaProjection ** result)
{
VALIDATE_NOT_NULL(result)
*result = NULL;
if (resultCode != IActivity::RESULT_OK || resultData == NULL) {
return NOERROR;
}
AutoPtr<IBinder> projection;
assert(0);
// TODO: Need IIntent::GetIBinderExtra
// resultData->GetIBinderExtra(IMediaProjectionManager::EXTRA_MEDIA_PROJECTION, (IBinder**)&projection);
if (projection == NULL) {
return NOERROR;
}
return CMediaProjection::New(mContext, IIMediaProjection::Probe(projection), result);
}
ECode CMediaProjectionManager::GetActiveProjectionInfo(
/* [out] */ IMediaProjectionInfo ** result)
{
VALIDATE_NOT_NULL(result)
*result = NULL;
// try {
return mService->GetActiveProjectionInfo(result);
// } catch (RemoteException e) {
// Log.e(TAG, "Unable to get the active projection info", e);
// }
// return null;
}
ECode CMediaProjectionManager::StopActiveProjection()
{
// try {
return mService->StopActiveProjection();
// } catch (RemoteException e) {
// Log.e(TAG, "Unable to stop the currently active media projection", e);
// }
}
ECode CMediaProjectionManager::AddCallback(
/* [in] */ IMediaProjectionManagerCallback * callback,
/* [in] */ IHandler * handler)
{
if (callback == NULL) {
// throw new IllegalArgumentException("callback must not be null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<CallbackDelegate> delegate = new CallbackDelegate(this, callback, handler);
IMap::Probe(mCallbacks)->Put(callback, (IObject*)delegate);
// try {
mService->AddCallback(IIMediaProjectionWatcherCallback::Probe(delegate));
// } catch (RemoteException e) {
// Log.e(TAG, "Unable to add callbacks to MediaProjection service", e);
// }
return NOERROR;
}
ECode CMediaProjectionManager::RemoveCallback(
/* [in] */ IMediaProjectionManagerCallback * callback)
{
if (callback == NULL) {
// throw new IllegalArgumentException("callback must not be null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<IInterface> obj;
IMap::Probe(mCallbacks)->Remove(callback, (IInterface**)&obj);
AutoPtr<CallbackDelegate> delegate = (CallbackDelegate*)IObject::Probe(obj);
// try {
if (delegate != NULL) {
mService->RemoveCallback(IIMediaProjectionWatcherCallback::Probe(delegate));
}
// } catch (RemoteException e) {
// Log.e(TAG, "Unable to add callbacks to MediaProjection service", e);
// }
return NOERROR;
}
} // namespace Projection
} // namespace Media
} // namepsace Droid
} // namespace Elastos
|
/*=============================================================================
Copyright (c) 2001-2014 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include "vm.hpp"
namespace client
{
void vmachine::execute(std::vector<int> const& code)
{
auto pc = code.begin();
auto locals = stack.begin();
stack_ptr = stack.begin();
while (pc != code.end())
{
switch (*pc++)
{
case op_neg:
stack_ptr[-1] = -stack_ptr[-1];
break;
case op_add:
--stack_ptr;
stack_ptr[-1] += stack_ptr[0];
break;
case op_sub:
--stack_ptr;
stack_ptr[-1] -= stack_ptr[0];
break;
case op_mul:
--stack_ptr;
stack_ptr[-1] *= stack_ptr[0];
break;
case op_div:
--stack_ptr;
stack_ptr[-1] /= stack_ptr[0];
break;
case op_load:
*stack_ptr++ = locals[*pc++];
break;
case op_store:
--stack_ptr;
locals[*pc++] = stack_ptr[0];
break;
case op_int:
*stack_ptr++ = *pc++;
break;
case op_stk_adj:
stack_ptr = stack.begin() + *pc++;
break;
}
}
}
}
|
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/from_std_string_locale.hpp>
#include <fcppt/string.hpp>
#include <fcppt/public_config.hpp>
#if !defined(FCPPT_NARROW_STRING)
#include <fcppt/widen.hpp>
#endif
#include <fcppt/config/external_begin.hpp>
#include <locale>
#include <string_view>
#include <fcppt/config/external_end.hpp>
fcppt::string
fcppt::from_std_string_locale(
std::string_view const &_input,
std::locale const &
#if !defined(FCPPT_NARROW_STRING)
_locale
#endif
)
{
#if !defined(FCPPT_NARROW_STRING)
return
fcppt::widen(
_input,
_locale
);
#else
return
fcppt::string{
_input
};
#endif
}
|
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") // Hide console window
#include "ofMain.h"
#include "ofApp.h"
/*
* kinect2share
*
* Created by Ryan Webber
* http://www.DusXproductions.com
* https://github.com/rwebber
*
* The goal of this project is to make as many Kinect2 features available to creative platforms as possible,
* using open standards including OSC (opensoundcontrol), Spout, and NDI (https://www.newtek.com/ndi/).
*
* Specific care has been given to providing a demo file for use with the Isadora creativity server.
* The demo file provides basic functional examples that Isadora users can build upon.
* http://troikatronix.com/
*
* MIT License http://en.wikipedia.org/wiki/MIT_License
*
* This project is built using OpenFrameWorks and utilizes a number of amazing addons offered by the community.
* Please read the ReadMe file included in the github reprository, for details.
*/
//========================================================================
int main( ){
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
//ofSetupOpenGL(1024,768,OF_WINDOW); // <-------- setup the GL context
//ofRunApp(new ofApp());
// custom windows setup.
ofGLFWWindowSettings settings;
//settings.iconified = true;
settings.resizable = false;
settings.width = 1024;
settings.height = 768;
ofCreateWindow(settings);
return ofRunApp(new ofApp);
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fnet/frt/frt.h>
#include <vespa/fastos/app.h>
class Server : public FRT_Invokable
{
private:
Server(const Server &);
Server &operator=(const Server &);
public:
Server(FRT_Supervisor *s)
{
FRT_ReflectionBuilder rb(s);
//---------------------------------------------------------------------
rb.DefineMethod("inc", "i", "i",
FRT_METHOD(Server::rpc_inc), this);
rb.MethodDesc("Increase an integer value");
rb.ParamDesc("value", "initial value");
rb.ReturnDesc("result", "value + 1");
//---------------------------------------------------------------------
rb.DefineMethod("blob", "x", "x",
FRT_METHOD(Server::rpc_blob), this);
rb.MethodDesc("Send a copy of a blob back to the client");
rb.ParamDesc("blob", "the original blob");
rb.ReturnDesc("blob", "a copy of the original blob");
//---------------------------------------------------------------------
rb.DefineMethod("test", "iib", "i",
FRT_METHOD(Server::rpc_test), this);
rb.MethodDesc("Magic test method");
rb.ParamDesc("value", "the value");
rb.ParamDesc("error", "error code to set");
rb.ParamDesc("extra", "if not 0, add an extra return value");
rb.ReturnDesc("value", "the value");
//---------------------------------------------------------------------
}
void rpc_inc(FRT_RPCRequest *req)
{
req->GetReturn()->AddInt32(req->GetParams()->GetValue(0)._intval32 + 1);
}
void rpc_blob(FRT_RPCRequest *req)
{
req->GetReturn()->AddData(req->GetParams()->GetValue(0)._data._buf,
req->GetParams()->GetValue(0)._data._len);
}
void rpc_test(FRT_RPCRequest *req)
{
int value = req->GetParams()->GetValue(0)._intval32;
int error = req->GetParams()->GetValue(1)._intval32;
int extra = req->GetParams()->GetValue(2)._intval8;
req->GetReturn()->AddInt32(value);
if (extra != 0) {
req->GetReturn()->AddInt32(value);
}
if (error != 0) {
req->SetError(error, "Custom error");
}
}
};
class App : public FastOS_Application
{
public:
int Main() override;
};
int
App::Main()
{
if (_argc < 2) {
printf("usage: %s <listenspec>\n", _argv[0]);
return 1;
}
fnet::frt::StandaloneFRT frt;
Server server(&frt.supervisor());
frt.supervisor().Listen(_argv[1]);
frt.supervisor().GetTransport()->WaitFinished();
return 0;
}
int
main(int argc, char **argv)
{
App myapp;
return myapp.Entry(argc, argv);
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The Bobachain Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "noui.h"
#include "ui_interface.h"
#include "util.h"
#include <cstdio>
#include <stdint.h>
#include <string>
static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
bool fSecure = style & CClientUIInterface::SECURE;
style &= ~CClientUIInterface::SECURE;
std::string strCaption;
// Check for usage of predefined caption
switch (style) {
case CClientUIInterface::MSG_ERROR:
strCaption += _("Error");
break;
case CClientUIInterface::MSG_WARNING:
strCaption += _("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
strCaption += _("Information");
break;
default:
strCaption += caption; // Use supplied caption (can be empty)
}
if (!fSecure)
LogPrintf("%s: %s\n", strCaption, message);
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
static bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style)
{
return noui_ThreadSafeMessageBox(message, caption, style);
}
static void noui_InitMessage(const std::string& message)
{
LogPrintf("init message: %s\n", message);
}
void noui_connect()
{
// Connect bobachaind signal handlers
uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox);
uiInterface.ThreadSafeQuestion.connect(noui_ThreadSafeQuestion);
uiInterface.InitMessage.connect(noui_InitMessage);
}
|
//
// Copyright 2012 Chung-Lin Wen
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_LAB_HPP
#define BOOST_GIL_EXTENSION_TOOLBOX_COLOR_SPACES_LAB_HPP
#include <boost/gil/extension/toolbox/color_spaces/xyz.hpp>
#include <boost/gil/color_convert.hpp>
#include <boost/gil.hpp> // FIXME: Include what you use, not everything, even in extensions!
#include <boost/gil/detail/mp11.hpp>
namespace boost{ namespace gil {
/// \addtogroup ColorNameModel
/// \{
namespace lab_color_space
{
/// \brief Luminance
struct luminance_t {};
/// \brief a Color Component
struct a_color_opponent_t {};
/// \brief b Color Component
struct b_color_opponent_t {};
}
/// \}
/// \ingroup ColorSpaceModel
using lab_t = mp11::mp_list
<
lab_color_space::luminance_t,
lab_color_space::a_color_opponent_t,
lab_color_space::b_color_opponent_t
>;
/// \ingroup LayoutModel
using lab_layout_t = layout<lab_t>;
BOOST_GIL_DEFINE_ALL_TYPEDEFS(32f, float32_t, lab)
/// \ingroup ColorConvert
/// \brief LAB to XYZ
template <>
struct default_color_converter_impl< lab_t, xyz_t >
{
template <typename P1, typename P2>
void operator()( const P1& src, P2& dst ) const
{
using namespace lab_color_space;
using namespace xyz_color_space;
float32_t p = ((get_color(src, luminance_t()) + 16.f)/116.f);
get_color(dst, y_t()) =
1.f * powf(p, 3.f);
get_color(dst, x_t()) =
0.95047f * powf((p +
(get_color(src, a_color_opponent_t())/500.f)
), 3.f);
get_color(dst, z_t()) =
1.08883f * powf((p -
(get_color(src, b_color_opponent_t())/200.f)
), 3.f);
}
};
/// \ingroup ColorConvert
/// \brief XYZ to LAB
/// \note I assume \c xyz_t
template <>
struct default_color_converter_impl< xyz_t, lab_t >
{
private:
/// \ref http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_Lab.html
BOOST_FORCEINLINE
float32_t forward_companding(float32_t value) const
{
if (value > 216.f/24389.f)
{
return powf(value, 1.f/3.f);
}
else
{
return ((24389.f/27.f * value + 16.f)/116.f);
}
}
public:
template <typename P1, typename P2>
void operator()( const P1& src, P2& dst ) const
{
using namespace lab_color_space;
float32_t f_y =
forward_companding(
channel_convert<float32_t>(
get_color(src, xyz_color_space::y_t())
)
// / 1.f
);
float32_t f_x =
forward_companding(
channel_convert<float32_t>(
get_color(src, xyz_color_space::x_t())
)
* (1.f / 0.95047f) // if the compiler is smart, it should
// precalculate this, no?
);
float32_t f_z =
forward_companding(
channel_convert<float32_t>(
get_color(src, xyz_color_space::z_t())
)
* (1.f / 1.08883f) // if the compiler is smart, it should
// precalculate this, no?
);
get_color(dst, luminance_t()) =
116.f * f_y - 16.f;
get_color(dst, a_color_opponent_t()) =
500.f * (f_x - f_y);
get_color(dst, b_color_opponent_t()) =
200.f * (f_y - f_z);
}
};
/// \ingroup ColorConvert
/// \brief RGB to LAB
template <>
struct default_color_converter_impl< rgb_t, lab_t >
{
template <typename P1, typename P2>
void operator()( const P1& src, P2& dst ) const
{
using namespace lab_color_space;
xyz32f_pixel_t xyz32f_temp_pixel;
default_color_converter_impl<rgb_t, xyz_t>()(src, xyz32f_temp_pixel);
default_color_converter_impl<xyz_t, lab_t>()(xyz32f_temp_pixel, dst);
}
};
/// \ingroup ColorConvert
/// \brief LAB to RGB
template <>
struct default_color_converter_impl<lab_t,rgb_t>
{
template <typename P1, typename P2>
void operator()( const P1& src, P2& dst) const
{
using namespace lab_color_space;
xyz32f_pixel_t xyz32f_temp_pixel;
default_color_converter_impl<lab_t, xyz_t>()(src, xyz32f_temp_pixel);
default_color_converter_impl<xyz_t, rgb_t>()(xyz32f_temp_pixel, dst);
}
};
} // namespace gil
} // namespace boost
#endif
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/xdebug/xdebug_command.h"
#include "hphp/runtime/ext/xdebug/xdebug_hook_handler.h"
#include "hphp/runtime/ext/xdebug/xdebug_utils.h"
#include "hphp/runtime/ext/xdebug/php5_xdebug/xdebug_var.h"
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/runtime/base/file.h"
#include "hphp/runtime/base/static-string-table.h"
#include "hphp/runtime/base/string-util.h"
#include "hphp/runtime/base/php-globals.h"
#include "hphp/runtime/ext/std/ext_std_file.h"
#include "hphp/runtime/ext/std/ext_std_misc.h"
#include "hphp/runtime/ext/url/ext_url.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/system/constants.h"
namespace HPHP {
////////////////////////////////////////////////////////////////////////////////
// Commands
// COMMAND(NAME, CLASS)
// NAME is the command name
// CLASS is the corresponding class
#define COMMANDS \
COMMAND("status", StatusCmd) \
COMMAND("feature_get", FeatureGetCmd) \
COMMAND("feature_set", FeatureSetCmd) \
COMMAND("run", RunCmd) \
COMMAND("step_into", StepIntoCmd) \
COMMAND("step_out", StepOutCmd) \
COMMAND("step_over", StepOverCmd) \
COMMAND("stop", StopCmd) \
COMMAND("detach", DetachCmd) \
COMMAND("breakpoint_set", BreakpointSetCmd) \
COMMAND("breakpoint_get", BreakpointGetCmd) \
COMMAND("breakpoint_list", BreakpointListCmd) \
COMMAND("breakpoint_update", BreakpointUpdateCmd) \
COMMAND("breakpoint_remove", BreakpointRemoveCmd) \
COMMAND("stack_depth", StackDepthCmd) \
COMMAND("stack_get", StackGetCmd) \
COMMAND("context_names", ContextNamesCmd) \
COMMAND("context_get", ContextGetCmd) \
COMMAND("typemap_get", TypemapGetCmd) \
COMMAND("property_get", PropertyGetCmd) \
COMMAND("property_set", PropertySetCmd) \
COMMAND("property_value", PropertyGetCmd) \
COMMAND("source", SourceCmd) \
COMMAND("stdout", StdoutCmd) \
COMMAND("stderr", StderrCmd) \
COMMAND("eval", EvalCmd) \
COMMAND("xcmd_profiler_name_get", ProfilerNameGetCmd) \
////////////////////////////////////////////////////////////////////////////////
// Features
// See http://xdebug.org/docs-dbgp.php#feature-names for a complete list
// FEATURE(NAME, SUPPORTED, VALUE, FREE)
// NAME is the feature name
// SUPPORTED is whether or not the feature is supported
// VALUE is the value to add to the xml node
// FREE is whether or not the value should be freed
#define FEATURES \
FEATURE("breakpoint_languages", "0", nullptr, false) \
FEATURE("breakpoint_types", "1", \
"line conditional call return exception", false) \
FEATURE("data_encoding", "0", nullptr, false) \
FEATURE("encoding", "1", "iso-8859-1", false) \
FEATURE("language_name", "1", "PHP", false) \
FEATURE("language_supports_threads", "1", "0", false) \
FEATURE("language_version", "1", xdstrdup(HHVM_VERSION), true) \
FEATURE("max_children", "1", \
xdebug_sprintf("%d", m_server.m_maxChildren), true) \
FEATURE("max_data", "1", xdebug_sprintf("%d", m_server.m_maxData), true) \
FEATURE("max_depth", "1", xdebug_sprintf("%d", m_server.m_maxDepth), true) \
FEATURE("protocol_version", "1", DBGP_VERSION, false) \
FEATURE("supported_encodings", "1", "iso-8859-1", false) \
FEATURE("supports_async", "1", "0", false) \
FEATURE("supports_postmortem", "1", "1", false) \
FEATURE("show_hidden", "1", \
xdebug_sprintf("%d", m_server.m_showHidden), true) \
////////////////////////////////////////////////////////////////////////////////
// Helpers
// These are used a lot, prevent unnecessary verbosity
typedef XDebugServer::Status Status;
typedef XDebugServer::Reason Reason;
// Compiles the given evaluation string and returns its unit. Throws
// XDebugServer::ERROR_EVALUATING_CODE on failure.
static Unit* compile(const String& evalStr) {
Unit* unit = compile_string(evalStr.data(), evalStr.size());
if (unit == nullptr) {
throw XDebugServer::ERROR_EVALUATING_CODE;
}
unit->setInterpretOnly();
return unit;
}
// Compiles the given expression so that when evaluated the expression result
// is returned. Returns the corresponding unit.
static Unit* compile_expression(const String& expr) {
StringBuffer buf;
buf.printf("<?php return %s;", expr.data());
return compile(buf.detach());
}
// Evaluates the given unit at the given depth and returns the result or throws
// and error on failure.
static Variant do_eval(Unit* evalUnit, int depth) {
// Set the error reporting level to 0 to ensure non-fatal errors are hidden
RequestInjectionData& req_data = ThreadInfo::s_threadInfo->m_reqInjectionData;
int64_t old_level = req_data.getErrorReportingLevel();
req_data.setErrorReportingLevel(0);
// Do the eval
Variant result;
bool failure = g_context->evalPHPDebugger((TypedValue*) &result,
evalUnit, depth);
// Restore the error reporting level and then either return or throw
req_data.setErrorReportingLevel(old_level);
if (failure) {
throw XDebugServer::ERROR_EVALUATING_CODE;
}
return result;
}
// Same as do_eval(const Unit*, int) except that this evaluates a string
static Variant do_eval(const String& evalStr, int depth) {
return do_eval(compile(evalStr), depth);
}
// Helper for the breakpoint commands that returns an xml node containing
// breakpoint information
static xdebug_xml_node* breakpoint_xml_node(int id,
const XDebugBreakpoint& bp) {
// Initialize the xml node
xdebug_xml_node* xml = xdebug_xml_node_init("breakpoint");
xdebug_xml_add_attribute(xml, "id", id);
// It looks like php5 xdebug used to consider "temporary" as a state. It's
// changed everywhere except here in xdebug's code. An obvious improvement
// would to output an extra "temporary" attribute, but for now this logic
// just follows xdebug
if (bp.temporary) {
xdebug_xml_add_attribute(xml, "state", "temporary");
} else if (bp.enabled) {
xdebug_xml_add_attribute(xml, "state", "enabled");
} else {
xdebug_xml_add_attribute(xml, "state", "disabled");
}
// Add the hit condition and count
switch (bp.hitCondition) {
case XDebugBreakpoint::HitCondition::GREATER_OR_EQUAL:
xdebug_xml_add_attribute(xml, "hit_condition", ">=");
break;
case XDebugBreakpoint::HitCondition::EQUAL:
xdebug_xml_add_attribute(xml, "hit_condition", "==");
break;
case XDebugBreakpoint::HitCondition::MULTIPLE:
xdebug_xml_add_attribute(xml, "hit_condition", "%");
break;
}
xdebug_xml_add_attribute(xml, "hit_count", bp.hitCount);
// Add type specific info. Note that since we don't know the lifetime of the
// returned node all added breakpoint info is duplicated.
switch (bp.type) {
// Line breakpoints add a file, line, and possibly a condition
case XDebugBreakpoint::Type::LINE:
xdebug_xml_add_attribute(xml, "type", "line");
xdebug_xml_add_attribute_dup(xml, "filename",
XDebugUtils::pathToUrl(bp.fileName).data());
xdebug_xml_add_attribute(xml, "lineno", bp.line);
// Add the condition. cast is due to xml api
if (bp.conditionUnit != nullptr) {
xdebug_xml_node* expr_xml = xdebug_xml_node_init("expression");
xdebug_xml_add_text(expr_xml, xdstrdup(bp.condition.data()));
xdebug_xml_add_child(xml, expr_xml);
}
break;
// Exception breakpoints just add the type
case XDebugBreakpoint::Type::EXCEPTION:
xdebug_xml_add_attribute(xml, "type", "exception");
break;
// Call breakpoints add function + class (optionally)
case XDebugBreakpoint::Type::CALL:
xdebug_xml_add_attribute(xml, "type", "call");
xdebug_xml_add_attribute_dup(xml, "function", bp.funcName.data());
if (!bp.className.isNull()) {
xdebug_xml_add_attribute_dup(xml, "class",
bp.className.toString().data());
}
break;
// Return breakpoints add function + class (optionally)
case XDebugBreakpoint::Type::RETURN:
xdebug_xml_add_attribute(xml, "type", "return");
xdebug_xml_add_attribute_dup(xml, "function", bp.funcName.data());
if (!bp.className.isNull()) {
xdebug_xml_add_attribute_dup(xml, "class",
bp.className.toString().data());
}
break;
}
return xml;
}
// Given a symbol name and a depth, returns the symbol's value. Throws an error
// if the symbol is not found
static Variant find_symbol(const String& name, int depth) {
// Retrieve the symbol by treating it as an expression.
// NOTE: This does not match php5 xdebug. php5 xdebug allows 'special'
// semantics to select the symbol. However, there is no evidence so far of an
// IDE using these, plus they are not documented anywhere. Thus, this
// implementation just accepts php expressions.
Unit* eval_unit = compile_expression(name);
// If the result is unitialized, the property must be undefined
Variant result = do_eval(eval_unit, depth);
if (!result.isInitialized()) {
throw XDebugServer::ERROR_PROPERTY_NON_EXISTENT;
}
return result;
}
// $GLOBALS variable
const static StaticString s_GLOBALS("GLOBALS");
// Returns true if the given variable name is a superglobal. This matches
// BuiltinSymbols::IsSuperGlobal with the addition of $GLOBALS
bool is_superglobal(const String& name) {
return name == s_GLOBALS || BuiltinSymbols::IsSuperGlobal(name.toCppString());
}
////////////////////////////////////////////////////////////////////////////////
// status -i #
// Returns the status of the server
class StatusCmd : public XDebugCommand {
public:
StatusCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~StatusCmd() {}
bool isValidInStatus(Status status) const override {
return true;
}
void handleImpl(xdebug_xml_node& xml) override {
m_server.addStatus(xml);
}
};
////////////////////////////////////////////////////////////////////////////////
// feature_get -i # -n NAME
class FeatureGetCmd : public XDebugCommand {
public:
FeatureGetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// Feature name is required
if (args['n'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_feature = args['n'].toString().toCppString();
}
~FeatureGetCmd() {}
bool isValidInStatus(Status status) const override { return true; }
void handleImpl(xdebug_xml_node& xml) override {
// Set to true once we have a match. Const cast is needed due to xdebug
// xml api.
bool match = false;
xdebug_xml_add_attribute(&xml, "feature_name", m_feature.c_str());
// Check against the defined features
#define FEATURE(name, supported, val, free) \
if (!match && m_feature == name) { \
if (val != nullptr) { \
xdebug_xml_add_text(&xml, val, free); \
} \
xdebug_xml_add_attribute(&xml, "supported", supported); \
match = true; \
}
FEATURES
#undef FEATURE
// Check against the commands
#define COMMAND(name, className) \
if (!match && m_feature == name) { \
xdebug_xml_add_text(&xml, "1", 0); \
xdebug_xml_add_attribute(&xml, "supported", "1"); \
match = true; \
}
COMMANDS
#undef COMMAND
// Unknown feature name
if (!match) {
xdebug_xml_add_text(&xml, "0", 0);
xdebug_xml_add_attribute(&xml, "supported", "0");
}
}
private:
string m_feature;
};
////////////////////////////////////////////////////////////////////////////////
// feature_set -i # -n NAME -v VALUE
class FeatureSetCmd : public XDebugCommand {
public:
FeatureSetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// Feature name is required
if (args['n'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_feature = args['n'].toString().toCppString();
// Value is required
if (args['v'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_value = args['v'].toString().toCppString();
}
~FeatureSetCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
const char* value_str = m_value.c_str();
// These could be thrown into a macro, but there aren't very many cases
if (m_feature == "max_children") {
m_server.m_maxChildren = strtol(value_str, nullptr, 10);
} else if (m_feature == "max_data") {
m_server.m_maxData = strtol(value_str, nullptr, 10);
} else if (m_feature == "max_depth") {
m_server.m_maxDepth = strtol(value_str, nullptr, 10);
} else if (m_feature == "show_hidden") {
m_server.m_showHidden = strtol(value_str, nullptr, 10);
} else if (m_feature == "multiple_sessions") {
// php5 xdebug doesn't do anything here with this value, but it is doesn't
// throw an error, either
} else if (m_feature == "encoding") {
if (m_value != "iso-8859-1") {
throw XDebugServer::ERROR_ENCODING_NOT_SUPPORTED;
}
} else {
throw XDebugServer::ERROR_INVALID_ARGS;
}
// Const cast is needed due to xdebug xml api.
xdebug_xml_add_attribute(&xml, "feature", m_feature.c_str());
xdebug_xml_add_attribute(&xml, "success", "1");
}
private:
string m_feature;
string m_value;
};
////////////////////////////////////////////////////////////////////////////////
// run -i #
// Runs the program until a breakpoint is hit or the script is finished
class RunCmd : public XDebugCommand {
public:
RunCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~RunCmd() {}
// run never responds immediately
bool shouldRespond() const override { return false; }
bool shouldContinue() const override { return true; }
bool isValidInStatus(Status status) const override {
return
status == Status::STARTING ||
status == Status::STOPPING ||
status == Status::BREAK;
}
void handleImpl(xdebug_xml_node& xml) override {
// Get the server status
Status status;
Reason reason;
m_server.getStatus(status, reason);
// Modify the status
switch (status) {
case Status::STARTING:
case Status::BREAK:
m_server.setStatus(Status::RUNNING, Reason::OK);
break;
case Status::STOPPING:
m_server.setStatus(Status::DETACHED, Reason::OK);
break;
default:
throw Exception("Command 'run' invalid in this server state.");
}
// Call the debugger hook and continue
phpDebuggerContinue();
}
};
////////////////////////////////////////////////////////////////////////////////
// step_into -i #
// steps to the next statement, if there is a function call involved it will
// break on the first statement in that function
class StepIntoCmd : public XDebugCommand {
public:
StepIntoCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~StepIntoCmd() {}
// Respond on step break
bool shouldRespond() const override { return false; }
bool shouldContinue() const override { return true; }
bool isValidInStatus(Status status) const override {
return
status == Status::STARTING ||
status == Status::STOPPING ||
status == Status::BREAK;
}
void handleImpl(xdebug_xml_node& xml) override {
phpDebuggerStepIn();
}
};
////////////////////////////////////////////////////////////////////////////////
// step_out -i #
// steps out of the current scope and breaks on the statement after returning
// from the current function.
class StepOutCmd : public XDebugCommand {
public:
StepOutCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~StepOutCmd() {}
// Respond on step out break
bool shouldRespond() const override { return false; }
bool shouldContinue() const override { return true; }
bool isValidInStatus(Status status) const override {
return
status == Status::STARTING ||
status == Status::STOPPING ||
status == Status::BREAK;
}
void handleImpl(xdebug_xml_node& xml) override {
phpDebuggerStepOut();
}
};
////////////////////////////////////////////////////////////////////////////////
// step_over -i #
// steps to the next line. Steps over function calls.
class StepOverCmd : public XDebugCommand {
public:
StepOverCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~StepOverCmd() {}
// Respond on next break
bool shouldRespond() const override { return false; }
bool shouldContinue() const override { return true; }
bool isValidInStatus(Status status) const override {
return
status == Status::STARTING ||
status == Status::STOPPING ||
status == Status::BREAK;
}
void handleImpl(xdebug_xml_node& xml) override {
phpDebuggerNext();
}
};
////////////////////////////////////////////////////////////////////////////////
// stop -i #
// Stops execution of the script by exiting
class StopCmd : public XDebugCommand {
public:
StopCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~StopCmd() {}
bool isValidInStatus(Status status) const override { return true; }
void handleImpl(xdebug_xml_node& xml) override {
m_server.setStatus(Status::STOPPED, Reason::OK);
// We need to throw an exception, so this needs to be sent manually
m_server.addStatus(xml);
m_server.sendMessage(xml);
throw ExitException(0);
}
};
////////////////////////////////////////////////////////////////////////////////
// detach -i #
// Detaches the xdebug server. In php5 xdebug this just means the user cannot
// input commands.
class DetachCmd : public XDebugCommand {
public:
DetachCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~DetachCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
m_server.setStatus(Status::DETACHED, Reason::OK);
m_server.addStatus(xml);
}
};
////////////////////////////////////////////////////////////////////////////////
// breakpoint_set -i # [-t TYPE] [-s STATE] [-f FILENAME] [-n LINENO]
// [-m FUNCTION] [-x EXCEPTION] [-h HIT_VALUE]
// [-o HIT_CONDITION] [-r 0|1] [-- EXPRESSION]
// Adds a breakpoint
// Valid breakpoint strings
static const StaticString
s_LINE("line"),
s_CONDITIONAL("conditional"),
s_CALL("call"),
s_RETURN("return"),
s_EXCEPTION("exception"),
s_WATCH("watch"),
s_ENABLED("enabled"),
s_DISABLED("disabled"),
s_GREATER_OR_EQUAL(">="),
s_EQUAL("=="),
s_MOD("%");
class BreakpointSetCmd : public XDebugCommand {
public:
BreakpointSetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
XDebugBreakpoint& bp = m_breakpoint;
// Type is required
if (args['t'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
// Type: line|call|return|exception|conditional
String typeName = args['t'].toString();
if (typeName == s_LINE || typeName == s_CONDITIONAL) {
// Despite spec, line and conditional are the same in php5 xdebug
bp.type = XDebugBreakpoint::Type::LINE;
} else if (typeName == s_CALL) {
bp.type = XDebugBreakpoint::Type::CALL;
} else if (typeName == s_RETURN) {
bp.type = XDebugBreakpoint::Type::RETURN;
} else if (typeName == s_EXCEPTION) {
bp.type = XDebugBreakpoint::Type::EXCEPTION;
} else if (typeName == s_WATCH) {
throw XDebugServer::ERROR_BREAKPOINT_TYPE_NOT_SUPPORTED;
} else {
throw XDebugServer::ERROR_INVALID_ARGS;
}
// State: enabled|disabled
if (!args['s'].isNull()) {
String state = args['s'].toString();
if (state == s_ENABLED) {
bp.enabled = true;
} else if (state == s_DISABLED) {
bp.enabled = false;
} else {
throw XDebugServer::ERROR_INVALID_ARGS;
}
}
// Hit condition and value. php5 xdebug does not throw an error if only
// one of the two are provided
if (!args['h'].isNull() && !args['o'].isNull()) {
String condition = args['o'].toString();
String val = args['h'].toString();
if (condition == s_GREATER_OR_EQUAL) {
bp.hitCondition = XDebugBreakpoint::HitCondition::GREATER_OR_EQUAL;
} else if (condition == s_EQUAL) {
bp.hitCondition = XDebugBreakpoint::HitCondition::EQUAL;
} else if (condition == s_MOD) {
bp.hitCondition = XDebugBreakpoint::HitCondition::MULTIPLE;
} else {
throw XDebugServer::ERROR_INVALID_ARGS;
}
bp.hitValue = strtol(val.data(), nullptr, 10);
}
// Temporary: 0|1 -- xdebug actually just throws the passed in data into
// strtol.
if (!args['r'].isNull()) {
String temp = args['r'].toString();
m_breakpoint.temporary = (bool) strtol(temp.data(), nullptr, 10);
}
// Initialize line breakpoint
if (bp.type == XDebugBreakpoint::Type::LINE) {
// Grab the line #
if (args['n'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
bp.line = strtol(args['n'].toString().data(), nullptr, 10);
// Grab the file, use the current if none provided
if (args['f'].isNull()) {
StringData* filename = g_context->getContainingFileName();
if (filename == staticEmptyString()) {
throw XDebugServer::ERROR_STACK_DEPTH_INVALID;
}
bp.fileName = String(filename);
} else {
bp.fileName = XDebugUtils::pathFromUrl(args['f'].toString());
}
// Ensure consistency between filenames
bp.fileName = File::TranslatePath(bp.fileName);
// Create the condition unit if a condition string was supplied
if (!args['-'].isNull()) {
String condition = StringUtil::Base64Decode(args['-'].toString());
bp.condition = condition;
bp.conditionUnit = compile_expression(condition);
}
}
// Call and return type
if (bp.type == XDebugBreakpoint::Type::CALL ||
bp.type == XDebugBreakpoint::Type::RETURN) {
if (args['m'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
bp.funcName = args['m'].toString();
// This is in php5 xdebug, but not in the spec. If 'a' is passed, the
// value is expected to be a class name that will be prepended to the
// passed method name.
if (!args['a'].isNull()) {
bp.className = args['a'];
}
// Precompute full function name
bp.fullFuncName = bp.className.isNull() ?
bp.funcName : (bp.className.toString() + "::" + bp.funcName);
}
// Exception type
if (bp.type == XDebugBreakpoint::Type::EXCEPTION) {
if (args['x'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
bp.exceptionName = args['x'].toString();
return;
}
}
~BreakpointSetCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
// Add the breakpoint, write out the id
int id = XDEBUG_ADD_BREAKPOINT(m_breakpoint);
xdebug_xml_add_attribute(&xml, "id", id);
// Add the breakpoint state
if (m_breakpoint.enabled) {
xdebug_xml_add_attribute(&xml, "state", "enabled");
} else {
xdebug_xml_add_attribute(&xml, "state", "disabled");
}
}
private:
XDebugBreakpoint m_breakpoint;
};
////////////////////////////////////////////////////////////////////////////////
// breakpoint_get -i # -d ID
// Returns information about the breakpoint with the given id
class BreakpointGetCmd : public XDebugCommand {
public:
BreakpointGetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// Breakpoint id must be provided
if (args['d'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_id = strtol(args['d'].toString().data(), nullptr, 10);
}
~BreakpointGetCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
const XDebugBreakpoint* bp = XDEBUG_GET_BREAKPOINT(m_id);
if (bp == nullptr) {
throw XDebugServer::ERROR_NO_SUCH_BREAKPOINT;
}
xdebug_xml_add_child(&xml, breakpoint_xml_node(m_id, *bp));
}
private:
int m_id;
};
////////////////////////////////////////////////////////////////////////////////
// breakpoint_list -i #
// Returns all the registered breakpoints
class BreakpointListCmd : public XDebugCommand {
public:
BreakpointListCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~BreakpointListCmd() {}
bool isValidInStatus(Status status) const override { return true; }
void handleImpl(xdebug_xml_node& xml) override {
for (auto iter = XDEBUG_BREAKPOINTS.begin();
iter != XDEBUG_BREAKPOINTS.end(); ++iter) {
int id = iter->first;
const XDebugBreakpoint& bp = iter->second;
xdebug_xml_add_child(&xml, breakpoint_xml_node(id, bp));
}
}
};
////////////////////////////////////////////////////////////////////////////////
// breakpoint_update -i # -d id [-s STATE] [-n LINE] [-h HIT_VALUE]
// [-o HIT_CONDITION]
// Updates the breakpoint with the given id using the given arguments
class BreakpointUpdateCmd : public XDebugCommand {
public:
BreakpointUpdateCmd(XDebugServer& server,
const String& cmd,
const Array& args)
: XDebugCommand(server, cmd, args) {
// Breakpoint id must be provided
if (args['d'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_id = strtol(args['d'].toString().data(), nullptr, 10);
// Grab the new state if it was passed
if (!args['s'].isNull()) {
String state = args['s'].toString();
if (state == s_ENABLED) {
m_enabled = true;
} else if (state == s_DISABLED) {
m_enabled = false;
} else {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_hasEnabled = true;
}
// Grab the new line if it was passed
if (!args['n'].isNull()) {
m_hasLine = true;
m_line = strtol(args['n'].toString().data(), nullptr, 10);
}
// Grab the new hit value if it was passed
if (!args['h'].isNull()) {
m_hasHitValue = true;
m_hitValue = strtol(args['h'].toString().data(), nullptr, 10);
}
// Grab the hit condition if it was passed
if (!args['o'].isNull()) {
String condition = args['o'].toString();
if (condition == s_GREATER_OR_EQUAL) {
m_hitCondition = XDebugBreakpoint::HitCondition::GREATER_OR_EQUAL;
} else if (condition == s_EQUAL) {
m_hitCondition = XDebugBreakpoint::HitCondition::EQUAL;
} else if (condition == s_MOD) {
m_hitCondition = XDebugBreakpoint::HitCondition::MULTIPLE;
} else {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_hasHitCondition = true;
}
}
~BreakpointUpdateCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
// Need to grab the breakpoint to send back the breakpoint info
const XDebugBreakpoint* bp = XDEBUG_GET_BREAKPOINT(m_id);
if (bp == nullptr) {
throw XDebugServer::ERROR_NO_SUCH_BREAKPOINT;
}
// If any of the updates fails an error is thrown
if (m_hasEnabled &&
!s_xdebug_breakpoints->updateBreakpointState(m_id, m_enabled)) {
throw XDebugServer::ERROR_BREAKPOINT_INVALID;
}
if (m_hasHitCondition &&
!s_xdebug_breakpoints->updateBreakpointHitCondition(m_id,
m_hitCondition)) {
throw XDebugServer::ERROR_BREAKPOINT_INVALID;
}
if (m_hasHitValue &&
!s_xdebug_breakpoints->updateBreakpointHitValue(m_id, m_hitValue)) {
throw XDebugServer::ERROR_BREAKPOINT_INVALID;
}
if (m_hasLine &&
!s_xdebug_breakpoints->updateBreakpointLine(m_id, m_line)) {
throw XDebugServer::ERROR_BREAKPOINT_INVALID;
}
// Add the breakpoint info. php5 xdebug does this, the spec does
// not specify this.
xdebug_xml_node* node = breakpoint_xml_node(m_id, *bp);
xdebug_xml_add_child(&xml, node);
}
private:
int m_id;
// Options that can be passed
bool m_hasEnabled = false;
bool m_hasLine = false;
bool m_hasHitValue = false;
bool m_hasHitCondition = false;
// Valid if the corresponding boolean is true
bool m_enabled;
int m_line;
int m_hitValue;
XDebugBreakpoint::HitCondition m_hitCondition;
};
////////////////////////////////////////////////////////////////////////////////
// breakpoint_remove -i # -d ID
// Removes the breakpoint with the given id
class BreakpointRemoveCmd : public XDebugCommand {
public:
BreakpointRemoveCmd(XDebugServer& server,
const String& cmd,
const Array& args)
: XDebugCommand(server, cmd, args) {
// Breakpoint id must be provided
if (args['d'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_id = strtol(args['d'].toString().data(), nullptr, 10);
}
~BreakpointRemoveCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
const XDebugBreakpoint* bp = XDEBUG_GET_BREAKPOINT(m_id);
if (bp == nullptr) {
throw XDebugServer::ERROR_NO_SUCH_BREAKPOINT;
}
// spec doesn't specify this, but php5 xdebug sends back breakpoint info
xdebug_xml_node* node = breakpoint_xml_node(m_id, *bp);
xdebug_xml_add_child(&xml, node);
// The breakpoint is deleted, so this has to be last
XDEBUG_REMOVE_BREAKPOINT(m_id);
}
private:
int m_id;
};
////////////////////////////////////////////////////////////////////////////////
// stack_depth -i #
// Returns the current stack depth
class StackDepthCmd : public XDebugCommand {
public:
StackDepthCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~StackDepthCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
int depth = XDebugUtils::stackDepth();
xdebug_xml_add_attribute(&xml, "depth", depth);
}
};
////////////////////////////////////////////////////////////////////////////////
// stack_get -i # [-d DEPTH]
// Returns the stack at the given depth, or the entire stack if no depth is
// provided
const static StaticString s_FILE("file");
class StackGetCmd : public XDebugCommand {
public:
StackGetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// Grab the optional depth argument
if (!args['d'].isNull()) {
m_clientDepth = strtol(args['d'].toString().data(), nullptr, 10);
if (m_clientDepth < 0 || m_clientDepth > XDebugUtils::stackDepth()) {
throw XDebugServer::ERROR_STACK_DEPTH_INVALID;
}
}
}
~StackGetCmd() {}
bool isValidInStatus(Status status) const override { return true; }
void handleImpl(xdebug_xml_node& xml) override {
// Iterate up the stack. We need to keep track of both the frame actrec and
// our current depth in case the client passed us a depth
Offset offset;
int depth = 0;
for (const ActRec* fp = g_context->getStackFrame();
fp != nullptr && (m_clientDepth == -1 || depth <= m_clientDepth);
fp = g_context->getPrevVMStateUNSAFE(fp, &offset), depth++) {
// If a depth was provided, we're only interested in that depth
if (m_clientDepth < 0 || depth == m_clientDepth) {
xdebug_xml_node* frame = getFrame(fp, offset, depth);
xdebug_xml_add_child(&xml, frame);
}
}
}
private:
// Returns the xml node for the given stack frame. If level is non-zero,
// offset is the current offset within the frame
xdebug_xml_node* getFrame(const ActRec* fp, Offset offset, int level) {
const auto func = fp->func();
const auto unit = fp->unit();
// Compute the function name. php5 xdebug includes names for each type of
// include, we don't have access to that
const char* func_name =
func->isPseudoMain() ?
(g_context->getPrevVMStateUNSAFE(fp) == nullptr ? "{main}" : "include") :
func->fullName()->data();
// Create the frame node
xdebug_xml_node* node = xdebug_xml_node_init("stack");
xdebug_xml_add_attribute(node, "where", func_name);
xdebug_xml_add_attribute(node, "level", level);
xdebug_xml_add_attribute(node, "type", "file");
// Grab the file/line for the frame. For level 0, this is the current
// file/line, for all other frames this is the stored file/line #
String file =
XDebugUtils::pathToUrl(String(unit->filepath()->data(), CopyString));
int line = level == 0 ? g_context->getLine() : unit->getLineNumber(offset);
// Add the call file/line. Duplication is necessary due to xml api
xdebug_xml_add_attribute_dup(node, "filename", file.data());
xdebug_xml_add_attribute(node, "lineno", line);
return node;
}
private:
int m_clientDepth = -1; // If >= 0, depth of the stack frame the client wants
};
////////////////////////////////////////////////////////////////////////////////
// context_names -i # [-d DEPTH]
// Returns the names of the currently available contexts at the given depth
// These match php5 xdebug. Adding contexts such as class would make sense
enum class XDebugContext : int {
LOCAL = 0, // need to start from 0 for komodo
SUPERGLOBALS = 1,
USER_CONSTANTS = 2
};
class ContextNamesCmd : public XDebugCommand {
public:
ContextNamesCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~ContextNamesCmd() {}
bool isValidInStatus(Status status) const override { return true; }
void handleImpl(xdebug_xml_node& xml) override {
xdebug_xml_node* child = xdebug_xml_node_init("context");
xdebug_xml_add_attribute(child, "name", "Locals");
xdebug_xml_add_attribute(child, "id",
static_cast<int>(XDebugContext::LOCAL));
xdebug_xml_add_child(&xml, child);
child = xdebug_xml_node_init("context");
xdebug_xml_add_attribute(child, "name", "Superglobals");
xdebug_xml_add_attribute(child, "id",
static_cast<int>(XDebugContext::SUPERGLOBALS));
xdebug_xml_add_child(&xml, child);
child = xdebug_xml_node_init("context");
xdebug_xml_add_attribute(child, "name", "User defined constants");
xdebug_xml_add_attribute(child, "id",
static_cast<int>(XDebugContext::USER_CONSTANTS));
xdebug_xml_add_child(&xml, child);
}
};
////////////////////////////////////////////////////////////////////////////////
// context_get -i # [-d DEPTH] [-c CONTEXT]
// Returns the variables in scope within the passed context
// Needed to look up user constants
const static StaticString s_USER("user");
class ContextGetCmd : public XDebugCommand {
public:
ContextGetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// Grab the context if it was passed
if (!args['c'].isNull()) {
int context = args['c'].toInt32();
switch (context) {
case static_cast<int>(XDebugContext::LOCAL):
case static_cast<int>(XDebugContext::SUPERGLOBALS):
case static_cast<int>(XDebugContext::USER_CONSTANTS):
m_context = static_cast<XDebugContext>(context);
break;
default:
throw XDebugServer::ERROR_INVALID_ARGS;
}
}
// Grab the depth if it was provided
if (!args['d'].isNull()) {
m_depth = strtol(args['d'].toString().data(), nullptr, 10);
} else {
m_depth = 0;
}
}
~ContextGetCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
// Setup the variable exporter
XDebugExporter exporter;
exporter.max_depth = m_server.m_maxDepth;
exporter.max_children = m_server.m_maxChildren;
exporter.max_data = m_server.m_maxData;
exporter.page = 0;
// Grab from the requested context
switch (m_context) {
case XDebugContext::SUPERGLOBALS: {
// Iterate through the globals, filtering out non-superglobals
Array globals = php_globals_as_array();
for (ArrayIter iter(globals); iter; ++iter) {
String name = iter.first();
if (!is_superglobal(name)) {
continue;
}
xdebug_xml_node* node =
xdebug_get_value_xml_node(iter.first().toString().data(),
iter.second(), XDebugVarType::Normal,
exporter);
xdebug_xml_add_child(&xml, node);
}
break;
}
case XDebugContext::USER_CONSTANTS: {
Array constants = lookupDefinedConstants(true)[s_USER].toArray();
for (ArrayIter iter(constants); iter; ++iter) {
xdebug_xml_node* node =
xdebug_get_value_xml_node(iter.first().toString().data(),
iter.second(), XDebugVarType::Normal,
exporter);
xdebug_xml_add_child(&xml, node);
}
break;
}
case XDebugContext::LOCAL: {
// Grab the in scope variables
VarEnv* var_env = g_context->getVarEnv(m_depth);
if (var_env == nullptr) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
// Add each variable, filtering out superglobals
Array vars = var_env->getDefinedVariables();
for (ArrayIter iter(vars); iter; ++iter) {
String name = iter.first().toString();
if (is_superglobal(name)) {
continue;
}
xdebug_xml_node* node =
xdebug_get_value_xml_node(name.data(), iter.second(),
XDebugVarType::Normal, exporter);
xdebug_xml_add_child(&xml, node);
}
break;
}
}
}
private:
XDebugContext m_context = XDebugContext::LOCAL;
int m_depth = 0;
};
////////////////////////////////////////////////////////////////////////////////
// typemap_get -i #
// Returns the types supported as well their corresponding xml schema
// Taken from php5 xdebug
// Fields are common name, lang name, and schema
#define XDEBUG_TYPES_COUNT 8
static const char* s_TYPEMAP[XDEBUG_TYPES_COUNT][3] = {
{"bool", "bool", "xsd:boolean"},
{"int", "int", "xsd:decimal"},
{"float", "float", "xsd:double"},
{"string", "string", "xsd:string"},
{"null", "null", nullptr},
{"hash", "array", nullptr},
{"object", "object", nullptr},
{"resource", "resource", nullptr}
};
class TypemapGetCmd : public XDebugCommand {
public:
TypemapGetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~TypemapGetCmd() {}
bool isValidInStatus(Status status) const override { return true; }
void handleImpl(xdebug_xml_node& xml) override {
// Add the schema
xdebug_xml_add_attribute(&xml, "xmlns:xsi",
"http://www.w3.org/2001/XMLSchema-instance");
xdebug_xml_add_attribute(&xml, "xmlns:xsd",
"http://www.w3.org/2001/XMLSchema");
// Add the types. Casts are necessary due to xml api
for (int i = 0; i < XDEBUG_TYPES_COUNT; i++) {
xdebug_xml_node* type = xdebug_xml_node_init("map");
xdebug_xml_add_attribute(type, "name", s_TYPEMAP[i][1]);
xdebug_xml_add_attribute(type, "type", s_TYPEMAP[i][0]);
if (s_TYPEMAP[i][2]) {
xdebug_xml_add_attribute(type, "xsi:type", s_TYPEMAP[i][2]);
}
xdebug_xml_add_child(&xml, type);
}
}
};
////////////////////////////////////////////////////////////////////////////////
// property_get -i # -n LONGNAME [-d DEPTH] [-c CONTEXT] [-m MAX_DATA] [-p PAGE]
// Note that the spec mentioned a 'k' and 'a', php5 xdebug does not support it
// Gets the specified property value
//
// property_value
// The dbgp spec specifies property_value as property_get, except that the
// entire value is always returned. But in php5 xdebug, property_value is
// exactly the same as property_get, without support for the constant context.
// Presumably because that context was added later, as the constant context
// is left out in other arbitrary places as well. So in this implementation,
// property_value is implemented as property_get
class PropertyGetCmd : public XDebugCommand {
public:
PropertyGetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// A name is required
if (args['n'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_name = args['n'].toString();
// Grab the context if it provided
if (!args['c'].isNull()) {
int context = strtol(args['c'].toString().data(), nullptr, 10);
switch (context) {
case static_cast<int>(XDebugContext::LOCAL):
case static_cast<int>(XDebugContext::SUPERGLOBALS):
case static_cast<int>(XDebugContext::USER_CONSTANTS):
m_context = static_cast<XDebugContext>(context);
break;
default:
throw XDebugServer::ERROR_INVALID_ARGS;
}
}
// Grab the depth if it is provided
if (!args['d'].isNull()) {
m_depth = strtol(args['d'].toString().data(), nullptr, 10);
}
// Grab the page if it was provided
if (!args['p'].isNull()) {
m_page = strtol(args['p'].toString().data(), nullptr, 10);
}
// Grab the max data if it was provided
if (!args['m'].isNull()) {
m_maxData= strtol(args['m'].toString().data(), nullptr, 10);
}
}
~PropertyGetCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
// Get the correct stack frame
ActRec* fp = g_context->getStackFrame();
for (int depth = 0; fp != nullptr && depth < m_depth;
depth++, fp = g_context->getPrevVMStateUNSAFE(fp)) {}
// If we don't have an actrec, the stack depth was invalid
if (fp == nullptr) {
throw XDebugServer::ERROR_STACK_DEPTH_INVALID;
}
// Setup the variable exporter
XDebugExporter exporter;
exporter.max_depth = m_maxDepth;
exporter.max_children = m_maxChildren;
exporter.max_data = m_maxData;
exporter.page = m_page;
switch (m_context) {
// Globals and superglobals can be fetched by finding the symbol
case XDebugContext::LOCAL:
case XDebugContext::SUPERGLOBALS: {
Variant val = find_symbol(m_name, m_depth);
xdebug_xml_node* node = xdebug_get_value_xml_node(m_name.data(), val,
XDebugVarType::Normal,
exporter);
xdebug_xml_add_child(&xml, node);
break;
}
// Grab the the constant, f_constant throws a warning on failure so
// we ensure it's defined before grabbing it
case XDebugContext::USER_CONSTANTS: {
if (!f_defined(m_name)) {
throw XDebugServer::ERROR_PROPERTY_NON_EXISTENT;
}
// php5 xdebug adds "constant" facet, but this is not in the spec
xdebug_xml_node* node =
xdebug_get_value_xml_node(m_name.data(), f_constant(m_name),
XDebugVarType::Constant, exporter);
xdebug_xml_add_attribute(node, "facet", "constant");
xdebug_xml_add_child(&xml, node);
break;
}
}
}
private:
String m_name;
XDebugContext m_context = XDebugContext::LOCAL;
int m_depth = 0; // desired stack depth
int m_maxDepth = m_server.m_maxDepth; // max property depth
int m_maxData = m_server.m_maxData;
int m_maxChildren = m_server.m_maxChildren;
int m_page = 0;
};
////////////////////////////////////////////////////////////////////////////////
// property_set -i # -n LONGNAME [-d DEPTH] [-t TYPE] -- DATA
// Sets the given property to the given value. In php5 xdebug, the semantics of
// this command relating to whether or a not a datatype (-t) is passed are very
// strange, but in this implementation the IDE can assume DATA can be any
// expression and LONGNAME must be some (possibly new) variable.
// Allowed datatypes for property_set
static const StaticString
s_BOOL("bool"),
s_INT("int"),
s_FLOAT("float"),
s_STRING("string");
class PropertySetCmd : public XDebugCommand {
public:
PropertySetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// A name is required
if (args['n'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_symbol = args['n'].toString();
// Data must be provided
if (args['-'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_newValue = StringUtil::Base64Decode(args['-'].toString());
// A datatype and depth can be provided
m_type = args['t'];
if (!args['d'].isNull()) {
m_depth = strtol(args['d'].toString().data(), nullptr, 10);
if (m_depth < 0 || m_depth > XDebugUtils::stackDepth()) {
throw XDebugServer::ERROR_STACK_DEPTH_INVALID;
}
}
}
~PropertySetCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
// Create the evaluation string buffer and store the symbol name
StringBuffer buf;
buf.printf("<?php %s = ", m_symbol.data());
// If a datatype was passed, add the appropriate type cast
if (!m_type.isNull()) {
String type = m_type.toString();
if (type == s_BOOL) {
buf.printf("(bool) ");
} else if (type == s_INT) {
buf.printf("(int) ");
} else if (type == s_FLOAT) {
buf.printf("(float) ");
} else if (type == s_STRING) {
buf.printf("(string) ");
}
}
// Add the value and create the evaluation string
buf.printf("(%s);", m_newValue.data());
String eval_str = buf.detach();
// Perform the evaluation at the given depth. Though this is inconsistent
// with errors in property_get and eval, php5 xdebug sends back success = 0
// on failure, not an error.
try {
do_eval(eval_str, m_depth);
xdebug_xml_add_attribute(&xml, "success", "1");
} catch (...) {
xdebug_xml_add_attribute(&xml, "success", "0");
}
}
private:
String m_symbol;
String m_newValue;
Variant m_type ; // datatype name
int m_depth = 0; // desired stack depth
};
////////////////////////////////////////////////////////////////////////////////
// source -i # [-f FILE] [-b BEGIN] [-e END]
// Grabs the given source file starting at the optionally given begin and end
// lines.
class SourceCmd : public XDebugCommand {
public:
SourceCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// Either grab the passed filename or get the current one
if (args['f'].isNull()) {
StringData* filename_data = g_context->getContainingFileName();
if (filename_data == staticEmptyString()) {
throw XDebugServer::ERROR_STACK_DEPTH_INVALID;
}
m_filename = String(filename_data);
} else {
m_filename = XDebugUtils::pathFromUrl(args['f'].toString());
}
m_filename = File::TranslatePath(m_filename); // canonicolize path
// Grab and 0-index the begin line
if (!args['b'].isNull()) {
m_beginLine = strtol(args['b'].toString().data(), nullptr, 10) - 1;
}
// Grab and 0-index the end line
if (!args['e'].isNull()) {
m_endLine = strtol(args['e'].toString().data(), nullptr, 10) - 1;
}
}
~SourceCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
// Grab the file as an array
Variant file = HHVM_FN(file)(m_filename);
if (!file.isArray()) {
throw XDebugServer::ERROR_CANT_OPEN_FILE;
}
Array source = file.toArray();
// Compute the begin/end line
if (m_beginLine < 0) {
m_beginLine = 0;
}
if (m_endLine < 0) {
m_endLine = source.size() - 1;
}
// Compute the source string. The initial size is arbitrary, we just guess
// 80 characters per line
StringBuffer buf((m_endLine - m_beginLine) * 80);
ArrayIter iter(source); iter.setPos(m_beginLine);
for (int i = m_beginLine; i <= m_endLine && iter; i++, ++iter) {
buf.append(iter.second());
}
m_source = buf.detach(); // To keep alive as long as command is alive
// Attach the source, const cast is due to xml interface
xdebug_xml_add_text_ex(&xml, const_cast<char*>(m_source.data()),
m_source.size(), 0, 1);
}
private:
String m_filename;
String m_source;
int m_beginLine = 0;
int m_endLine = -1;
};
////////////////////////////////////////////////////////////////////////////////
// stdout -i # -c 0|1|2
// Redirect or copy stdout to the client
// Helper called on stdout write when we have redirected it with the stdout
// command. Once installed, this continues until it is either explicitly
// uninstalled, or if there is no longer an xdebug server.
static void onStdoutWrite(const char* bytes, int len, void* copy) {
if (XDEBUG_GLOBAL(Server) == nullptr) {
g_context->setStdout(nullptr, nullptr);
}
XDEBUG_GLOBAL(Server)->sendStream("stdout", bytes, len);
// If copy is true, we also copy the data to stdout
if ((bool) copy) {
write(fileno(stdout), bytes, len);
}
}
class StdoutCmd : public XDebugCommand {
public:
StdoutCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// "c" must be provided
if (args['c'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
// Only several types of modes are allowed
int mode = strtol(args['c'].toString().data(), nullptr, 10);
switch (mode) {
case MODE_DISABLE:
case MODE_COPY:
case MODE_REDIRECT:
m_mode = static_cast<Mode>(mode);
break;
default:
throw XDebugServer::ERROR_INVALID_ARGS;
}
}
~StdoutCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
switch (m_mode) {
case MODE_DISABLE:
g_context->setStdout(nullptr, nullptr);
break;
case MODE_COPY:
g_context->setStdout(onStdoutWrite, (void*) true);
break;
case MODE_REDIRECT:
g_context->setStdout(onStdoutWrite, (void*) false);
break;
default:
throw Exception("Invalid mode type");
}
xdebug_xml_add_attribute(&xml, "success", "1");
}
private:
enum Mode {
MODE_DISABLE = 0,
MODE_COPY = 1,
MODE_REDIRECT = 2
};
Mode m_mode;
};
////////////////////////////////////////////////////////////////////////////////
// stderr -i #
// This "required" dbgp-core feature is not implemented by php5 xdebug :)
class StderrCmd : public XDebugCommand {
public:
StderrCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~StderrCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
xdebug_xml_add_attribute(&xml, "success", "0");
}
};
////////////////////////////////////////////////////////////////////////////////
// eval -i # [-p PAGE] -- DATA
// Evaluate an expression within the given exeuction context. Note that php5
// xdebug claims non-expressions are allowed in their eval code, but the
// implementation calls zend_eval_string which wraps EXPR in "return EXPR;"
class EvalCmd : public XDebugCommand {
public:
EvalCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {
// An evaluation string must be provided
if (args['-'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
String encoded_expr = args['-'].toString();
m_evalUnit = compile_expression(StringUtil::Base64Decode(encoded_expr));
// A page can optionally be provided
if (!args['p'].isNull()) {
m_page = strtol(args['p'].toString().data(), nullptr, 10);
}
}
~EvalCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
Variant result = do_eval(m_evalUnit, 0);
// Construct the exporter
XDebugExporter exporter;
exporter.max_depth = m_server.m_maxDepth;
exporter.max_children = m_server.m_maxChildren;
exporter.max_data = m_server.m_maxData;
exporter.page = m_page;
// Create the xml node
xdebug_xml_node* node = xdebug_get_value_xml_node(nullptr, result,
XDebugVarType::Normal,
exporter);
xdebug_xml_add_child(&xml, node);
}
private:
Unit* m_evalUnit;
int m_page = 0;
};
////////////////////////////////////////////////////////////////////////////////
// xcmd_profiler_name_get -i #
// Returns the profiler filename if profiling has started
class ProfilerNameGetCmd : public XDebugCommand {
public:
ProfilerNameGetCmd(XDebugServer& server, const String& cmd, const Array& args)
: XDebugCommand(server, cmd, args) {}
~ProfilerNameGetCmd() {}
void handleImpl(xdebug_xml_node& xml) override {
Variant filename = HHVM_FN(xdebug_get_profiler_filename)();
if (!filename.isString()) {
throw XDebugServer::ERROR_PROFILING_NOT_STARTED;
}
xdebug_xml_add_text(&xml, xdstrdup(filename.toString().data()));
}
};
////////////////////////////////////////////////////////////////////////////////
// XDebugCommand implementation
XDebugCommand::XDebugCommand(XDebugServer& server,
const String& cmd,
const Array& args)
: m_server(server), m_commandStr(cmd) {
// A transaction id must be provided
if (args['i'].isNull()) {
throw XDebugServer::ERROR_INVALID_ARGS;
}
m_transactionId = args['i'].toString();
}
bool XDebugCommand::handle(xdebug_xml_node& response) {
m_server.addCommand(response, *this);
handleImpl(response);
return shouldContinue();
}
XDebugCommand* XDebugCommand::fromString(XDebugServer& server,
const String& cmdStr,
const Array& args) {
// Match will be set true once there is a match.
bool match = false;
string cmd_cpp = cmdStr.toCppString();
// Check each command
XDebugCommand* cmd;
#define COMMAND(name, className) \
if (!match && cmd_cpp == name) { \
cmd = new className(server, cmdStr, args); \
match = true; \
}
COMMANDS
#undef COMMAND
// php5 xdebug throws an unimplemented error when no valid match is found
if (!match) {
throw XDebugServer::ERROR_UNIMPLEMENTED;
}
// Ensure this command is valid in the given server status
Status status; Reason reason;
server.getStatus(status, reason);
if (!cmd->isValidInStatus(status)) {
delete cmd;
throw XDebugServer::ERROR_COMMAND_UNAVAILABLE;
}
return cmd;
}
///////////////////////////////////////////////////////////////////////////////
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.