text
string
size
int64
token_count
int64
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> #include <deque> #include <algorithm> #include <climits> #include <chrono> #include "InstructionScheduler.h" std::string getInputAsString(std::string); std::vector<std::string> getInputPerLines(std::string); /******************************************************** * Day 7 Puzzle: * Using an OO approach to have objects for each task * and each worker. To to its morphological creation * the solution is not clean at all but at least it works * at is. Many things should be improved in multiple ways */ int main() { auto start = std::chrono::high_resolution_clock::now(); std::string str; std::ifstream input; std::vector<std::string> lines; InstructionScheduler scheduler = InstructionScheduler(); // Load input as Single String //str = getInputAsString("input_Day7_test.txt"); // Get Input as vector of lines lines = getInputPerLines("input_Day7.txt"); for (int i = 0; i < lines.size(); ++i) { std::string before, after; before = lines[i][5]; after = lines[i][36]; // Create Instructions scheduler.addInstruction(before, after); //scheduler.printInstructions(); } // Schedule Instructions PART ONE std::cout << std::endl << "PART ONE: " << std::endl; scheduler.getSchedule(); auto finishONE = std::chrono::high_resolution_clock::now(); // Schedule Instructions PART TWO std::cout << std::endl << "PART TWO: " << std::endl; //scheduler.getTimedSchedule(2); // for testData scheduler.getTimedSchedule(5); auto finishTWO = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsedONE = finishONE - start; std::chrono::duration<double> elapsedTWO = finishTWO - finishONE; std::cout << "Elapsed time: P1: " << elapsedONE.count() * 1000 << "ms P2: " << elapsedTWO.count() * 1000 << "ms" << std::endl; return 0; } /****************************** * INPUT HELPER FUNCTIONS * ******************************/ std::string getInputAsString(std::string fileName) { std::string str; // Open File std::ifstream in(fileName); if (!in.is_open() || !in.good()) { std::cout << "Failed to open input" << std::endl; return 0; } // Create String str.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); in.close(); return str; } std::vector<std::string> getInputPerLines(std::string fileName) { std::vector<std::string> lines; std::string line; // Open File std::ifstream in(fileName); if (!in.is_open() || !in.good()) { std::cout << "Failed to open input" << std::endl; } // Create Vector of lines while (getline(in, line)) { lines.push_back(line); } in.close(); return lines; }
2,726
966
/* * Copyright 2008-2013 NVIDIA Corporation * Modifications Copyright© 2019 Advanced Micro Devices, Inc. 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 <thrust/functional.h> #include <thrust/sort.h> #include "test_header.hpp" template <typename T, unsigned int N> void _TestStableSortWithLargeKeys(void) { size_t n = (128 * 1024) / sizeof(FixedVector<T, N>); thrust::host_vector<FixedVector<T, N>> h_keys(n); for(size_t i = 0; i < n; i++) h_keys[i] = FixedVector<T, N>(rand()); thrust::device_vector<FixedVector<T, N>> d_keys = h_keys; thrust::stable_sort(h_keys.begin(), h_keys.end()); thrust::stable_sort(d_keys.begin(), d_keys.end()); ASSERT_EQ_QUIET(h_keys, d_keys); } TEST(StableSortLargeTests, TestStableSortWithLargeKeys) { _TestStableSortWithLargeKeys<int, 1>(); _TestStableSortWithLargeKeys<int, 2>(); _TestStableSortWithLargeKeys<int, 4>(); _TestStableSortWithLargeKeys<int, 8>(); // STREAM HPC investigate and fix `error: local memory limit exceeded` // (make block size smaller for large keys and values in rocPRIM) #if THRUST_DEVICE_SYSTEM != THRUST_DEVICE_SYSTEM_HIP _TestStableSortWithLargeKeys<int, 16>(); _TestStableSortWithLargeKeys<int, 32>(); _TestStableSortWithLargeKeys<int, 64>(); _TestStableSortWithLargeKeys<int, 128>(); _TestStableSortWithLargeKeys<int, 256>(); _TestStableSortWithLargeKeys<int, 512>(); _TestStableSortWithLargeKeys<int, 1024>(); // XXX these take too long to compile // _TestStableSortWithLargeKeys<int, 2048>(); // _TestStableSortWithLargeKeys<int, 4096>(); // _TestStableSortWithLargeKeys<int, 8192>(); #endif }
2,215
813
/* * An example of an asynchronous C++ node addon. * Provided by paulhauner https://github.com/paulhauner * License: MIT * Tested in node.js v4.4.2 LTS in Ubuntu Linux */ #include <nan.h> #include <node.h> #include <uv.h> #include <iostream> #include <unistd.h> #include <string.h> using namespace std; namespace asyncAddon { using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; using v8::Persistent; using v8::Exception; /** * Work structure is be used to pass the callback function and data * from the initiating function to the function which triggers the callback. */ struct Work { uv_work_t request; Persistent<Function> callback; int error; string key; string salt; string result; }; /** * WorkAsync function is the "middle" function which does the work. * After the WorkAsync function is called, the WorkAsyncComplete function * is called. */ static void WorkAsync(uv_work_t *req) { Work *work = static_cast<Work *>(req->data); const char *key = work->key.c_str(); const char *salt = work->salt.c_str(); char* res = crypt(key, salt); char* error; if (res != NULL) { work->error = 0; work->result.assign(res); } else { work->error = errno; error = strerror(errno); work->result.assign(error); } } /** * WorkAsyncComplete function is called once we are ready to trigger the callback * function in JS. */ static void WorkAsyncComplete(uv_work_t *req,int status) { Isolate * isolate = Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); Work *work = static_cast<Work *>(req->data); Local<v8::Context> context = isolate -> GetCurrentContext() ; Local<Value> recv = Undefined( isolate ) ; const int error = work->error; const char *result = work->result.c_str(); if(error == 0) { Local<Value> argv[2] = { Undefined(isolate), String::NewFromUtf8(isolate, result, v8::NewStringType::kNormal).ToLocalChecked() }; // https://stackoverflow.com/questions/13826803/calling-javascript-function-from-a-c-callback-in-v8/28554065#28554065 Local<Function>::New(isolate, work->callback)->Call(context, recv, 2, argv); } else { Local<Value> argv[1] = { String::NewFromUtf8(isolate, result, v8::NewStringType::kNormal).ToLocalChecked() }; // https://stackoverflow.com/questions/13826803/calling-javascript-function-from-a-c-callback-in-v8/28554065#28554065 Local<Function>::New(isolate, work->callback)->Call(context, recv, 1, argv); } work->callback.Reset(); delete work; } /** * Crypt3Async is the initial function called from JS. This function returns * immediately, however starts a uv task which later calls the callback function */ void Crypt3Async(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Work * work = new Work(); work->request.data = work; if (args.Length() < 3) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments", v8::NewStringType::kNormal).ToLocalChecked())); return; } if (!args[0]->IsString() || !args[1]->IsString() || !args[2]->IsFunction() ) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments", v8::NewStringType::kNormal).ToLocalChecked())); return; } Nan::Utf8String v8key(args[0]); string key = std::string(*v8key); work->key = key; Nan::Utf8String v8salt(args[1]); string salt = std::string(*v8salt); work->salt = salt; // args[2] is where we pick the callback function out of the JS function params. // Because we chose args[2], we must supply the callback fn as the first parameter Local<Function> callback = Local<Function>::Cast(args[2]); work->callback.Reset(isolate, callback); uv_queue_work(uv_default_loop(), &work->request, WorkAsync, WorkAsyncComplete); args.GetReturnValue().Set(Undefined(isolate)); } /** * init function declares what we will make visible to node */ void init(Local<Object> exports) { NODE_SET_METHOD(exports, "crypt", Crypt3Async); } NODE_MODULE(asyncAddon, init) }
4,218
1,552
#include<bits/stdc++.h> #define fo(i, n) for(int i = 1; i < n; i++) using namespace std ; #define deb(x) {cout << #x << " " << x << endl ;} int max_contiguos_subarray(vector<int> &nums) { stack<int> cached ; cached.push(nums[0]) ; int n = nums.size() ; int cnt = INT_MIN, t = 0 ; if(is_sorted(nums.begin(), nums.end(), less<int>{})) return nums.size() ; if(is_sorted(nums.begin(), nums.end(), greater<int>{})) return 0 ; fo(i, n) { if (cached.top() > nums[i] ) { t = cached.size() ; while(!cached.empty()) { cached.pop() ; } cached.push(nums[i]) ; } if (cached.top() < nums[i]) { cached.push(nums[i]) ; int l = cached.size() ; cnt = max(cnt, l) ; } } return max(cnt, t); } int main(int argc, char const *argv[]){ ios::sync_with_stdio(0) ; vector<int> nums{60, 45, 48, 52}; cout << go(nums) ; return 0; }
947
396
/*! @brief value&lt;void&gt; @file nodamushi/svd/value/void_value.hpp */ /* * These codes are licensed under CC0. * http://creativecommons.org/publicdomain/zero/1.0/ */ #ifndef NODAMUSHI_SVD_VALUE_VOID_VALUE_HPP #define NODAMUSHI_SVD_VALUE_VOID_VALUE_HPP # include "nodamushi/svd/value.hpp" namespace nodamushi{ namespace svd{ // void template<bool attribute,bool r,char... name>struct value<void,attribute,r,name...> { using type = void; static constexpr bool REQUIRED=false; static constexpr bool ATTRIBUTE=attribute; constexpr bool empty()const noexcept{return true;} constexpr operator bool()const noexcept{return false;} constexpr bool check_require()const noexcept{return true;} constexpr bool is_required()const noexcept{return false;} constexpr bool is_attribute()const noexcept{return attribute;} int operator*()const noexcept{return 0;} int get()const noexcept{return 0;} NODAMUSHI_CONSTEXPR_STRING get_name()const noexcept { # if __cplusplus >= 201703 return get_const_string<name...>(); # else const char arr[] = {name...,'\0'}; return std::string(arr); # endif } }; }}// end namespace nodamushi::svd #endif // NODAMUSHI_SVD_VALUE_VOID_VALUE_HPP
1,209
439
// -*- C++ -*- // // $Id: OS_NS_sys_select.inl 2179 2013-05-28 22:16:51Z mesnierp $ #include "ace/OS_NS_errno.h" #include "ace/OS_NS_macros.h" #include "ace/Time_Value.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL // It would be really cool to add another version of select that would // function like the one we're defending against below! ACE_INLINE int ACE_OS::select (int width, fd_set *rfds, fd_set *wfds, fd_set *efds, const ACE_Time_Value *timeout) { ACE_OS_TRACE ("ACE_OS::select"); #if defined (ACE_HAS_NONCONST_SELECT_TIMEVAL) // We must defend against non-conformity! timeval copy; timeval *timep = 0; if (timeout != 0) { copy = *timeout; timep = &copy; } else timep = 0; #else const timeval *timep = (timeout == 0 ? (const timeval *)0 : *timeout); #endif /* ACE_HAS_NONCONST_SELECT_TIMEVAL */ #if defined (ACE_LACKS_SELECT) ACE_UNUSED_ARG (width); ACE_UNUSED_ARG (rfds); ACE_UNUSED_ARG (wfds); ACE_UNUSED_ARG (efds); ACE_UNUSED_ARG (timeout); ACE_NOTSUP_RETURN (-1); #else ACE_SOCKCALL_RETURN (::select (width, rfds, wfds, efds, timep), int, -1); #endif } ACE_INLINE int ACE_OS::select (int width, fd_set *rfds, fd_set *wfds, fd_set *efds, const ACE_Time_Value &timeout) { ACE_OS_TRACE ("ACE_OS::select"); #if defined (ACE_HAS_NONCONST_SELECT_TIMEVAL) # define ___ACE_TIMEOUT &copy timeval copy = timeout; #else # define ___ACE_TIMEOUT timep const timeval *timep = timeout; #endif /* ACE_HAS_NONCONST_SELECT_TIMEVAL */ #if defined (ACE_LACKS_SELECT) ACE_UNUSED_ARG (width); ACE_UNUSED_ARG (rfds); ACE_UNUSED_ARG (wfds); ACE_UNUSED_ARG (efds); ACE_UNUSED_ARG (timeout); ACE_NOTSUP_RETURN (-1); #else ACE_SOCKCALL_RETURN (::select (width, rfds, wfds, efds, ___ACE_TIMEOUT), int, -1); #endif #undef ___ACE_TIMEOUT } ACE_END_VERSIONED_NAMESPACE_DECL
1,938
851
/* High Performance Astrophysical Reconstruction and Processing (HARP) (c) 2014-2015, The Regents of the University of California, through Lawrence Berkeley National Laboratory. See top level LICENSE file for details. */ #include <harp_mpi_internal.hpp> using namespace std; using namespace harp; mpi_spec_p harp::mpi_load_spec ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_spec_p ( new mpi_spec ( comm, type, props ) ); } mpi_image_p harp::mpi_load_image ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_image_p ( new mpi_image ( comm, type, props ) ); } mpi_psf_p harp::mpi_load_psf ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_psf_p ( new mpi_psf ( comm, type, props ) ); } mpi_targets_p harp::mpi_load_targets ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_targets_p ( new mpi_targets ( comm, type, props ) ); } harp::mpi_group::mpi_group ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { load ( comm, tree ); } void harp::mpi_group::load ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { handle_.reset(); boost::property_tree::ptree psf_tree = tree.get_child ( "psf" ); handle_ = mpi_load_psf ( comm, psf_tree ); imgs_.clear(); boost::property_tree::ptree::const_iterator v = tree.begin(); while ( v != tree.end() ) { if ( v->first == "image" ) { imgs_.push_back ( mpi_load_image ( comm, v->second ) ); } ++v; } return; } std::list < mpi_group_p > harp::mpi_load_groups ( boost::mpi::communicator const & comm, std::string const & path ) { // Read JSON into a property tree boost::property_tree::ptree tree; boost::property_tree::json_parser::read_json ( path, tree ); std::list < mpi_group_p > ret; boost::property_tree::ptree::const_iterator v = tree.begin(); while ( v != tree.end() ) { if ( v->first == "group" ) { ret.push_back ( mpi_group_p ( new mpi_group ( comm, v->second ) ) ); } ++v; } return ret; }
2,713
999
// Copyright 1996-2020 Cyberbotics 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 "WbSupportPolygonRepresentation.hpp" #include "WbMathsUtilities.hpp" #include "WbPolygon.hpp" #include "WbRotation.hpp" #include "WbWrenRenderingContext.hpp" #include "WbWrenShaders.hpp" #include <wren/config.h> #include <wren/dynamic_mesh.h> #include <wren/material.h> #include <wren/node.h> #include <wren/renderable.h> #include <wren/scene.h> #include <wren/static_mesh.h> #include <wren/transform.h> // Colors used by support polygon representation in RGBA format // note: alpha = 1.0f -> full transparency static const float STABLE_POLYGON_COLOR[4] = {0.6f, 0.9f, 0.6f, 0.5f}; static const float STABLE_POLYGON_OUTLINE_COLOR[4] = {0.2f, 1.0f, 0.2f, 0.5f}; static const float STABLE_CENTER_OF_MASS_COLOR[4] = {0.5f, 1.0f, 0.5f, 0.0f}; static const float UNSTABLE_POLYGON_COLOR[4] = {0.9f, 0.6f, 0.6f, 0.5f}; static const float UNSTABLE_POLYGON_OUTLINE_COLOR[4] = {1.0f, 0.2f, 0.1f, 0.5f}; static const float UNSTABLE_CENTER_OF_MASS_COLOR[4] = {1.0f, 0.2f, 0.2f, 0.0f}; WbSupportPolygonRepresentation::WbSupportPolygonRepresentation() { mTransform = wr_transform_new(); mCenterOfMassTransform = wr_transform_new(); mPolygonMesh = wr_dynamic_mesh_new(false, false, false); mPolygonOutlineMesh = wr_dynamic_mesh_new(false, false, false); const float vertices[12] = {-1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f}; mCenterOfMassMesh = wr_static_mesh_line_set_new(4, vertices, NULL); mPolygonMaterial = wr_phong_material_new(); wr_material_set_default_program(mPolygonMaterial, WbWrenShaders::simpleShader()); wr_phong_material_set_color(mPolygonMaterial, STABLE_POLYGON_COLOR); wr_phong_material_set_transparency(mPolygonMaterial, STABLE_POLYGON_COLOR[3]); mPolygonOutlineMaterial = wr_phong_material_new(); wr_material_set_default_program(mPolygonOutlineMaterial, WbWrenShaders::lineSetShader()); wr_phong_material_set_color(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR); wr_phong_material_set_transparency(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR[3]); mCenterOfMassMaterial = wr_phong_material_new(); wr_material_set_default_program(mCenterOfMassMaterial, WbWrenShaders::lineSetShader()); wr_phong_material_set_color(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR); wr_phong_material_set_transparency(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR[3]); mPolygonRenderable = wr_renderable_new(); wr_renderable_set_mesh(mPolygonRenderable, WR_MESH(mPolygonMesh)); wr_renderable_set_drawing_order(mPolygonRenderable, WR_RENDERABLE_DRAWING_ORDER_AFTER_1); wr_renderable_set_material(mPolygonRenderable, mPolygonMaterial, NULL); wr_renderable_set_visibility_flags(mPolygonRenderable, WbWrenRenderingContext::VF_SELECTED_OUTLINE); wr_renderable_set_face_culling(mPolygonRenderable, false); wr_renderable_set_drawing_mode(mPolygonRenderable, WR_RENDERABLE_DRAWING_MODE_TRIANGLE_FAN); mPolygonOutlineRenderable = wr_renderable_new(); wr_renderable_set_mesh(mPolygonOutlineRenderable, WR_MESH(mPolygonOutlineMesh)); wr_renderable_set_drawing_order(mPolygonOutlineRenderable, WR_RENDERABLE_DRAWING_ORDER_AFTER_1); wr_renderable_set_drawing_mode(mPolygonOutlineRenderable, WR_RENDERABLE_DRAWING_MODE_LINES); wr_renderable_set_material(mPolygonOutlineRenderable, mPolygonOutlineMaterial, NULL); wr_renderable_set_visibility_flags(mPolygonRenderable, WbWrenRenderingContext::VF_SELECTED_OUTLINE); mCenterOfMassRenderable = wr_renderable_new(); wr_renderable_set_mesh(mCenterOfMassRenderable, WR_MESH(mCenterOfMassMesh)); wr_renderable_set_drawing_order(mCenterOfMassRenderable, WR_RENDERABLE_DRAWING_ORDER_AFTER_1); wr_renderable_set_drawing_mode(mCenterOfMassRenderable, WR_RENDERABLE_DRAWING_MODE_LINES); wr_renderable_set_material(mCenterOfMassRenderable, mCenterOfMassMaterial, NULL); wr_renderable_set_visibility_flags(mCenterOfMassRenderable, WbWrenRenderingContext::VF_SELECTED_OUTLINE); const float s = 0.1f * wr_config_get_line_scale(); const float scale[3] = {s, s, s}; wr_transform_set_scale(mCenterOfMassTransform, scale); wr_transform_attach_child(mTransform, WR_NODE(mPolygonRenderable)); wr_transform_attach_child(mTransform, WR_NODE(mPolygonOutlineRenderable)); wr_transform_attach_child(mCenterOfMassTransform, WR_NODE(mCenterOfMassRenderable)); WrTransform *root = wr_scene_get_root(wr_scene_get_instance()); wr_transform_attach_child(mTransform, WR_NODE(mCenterOfMassTransform)); wr_transform_attach_child(root, WR_NODE(mTransform)); wr_node_set_visible(WR_NODE(mTransform), false); } WbSupportPolygonRepresentation::~WbSupportPolygonRepresentation() { cleanup(); } void WbSupportPolygonRepresentation::show(bool visible) { wr_node_set_visible(WR_NODE(mTransform), visible); } static void addVertex(WrDynamicMesh *mesh, int index, float x, float y, float z) { const float vertex[3] = {x, y, z}; wr_dynamic_mesh_add_vertex(mesh, vertex); wr_dynamic_mesh_add_index(mesh, index); } void WbSupportPolygonRepresentation::draw(const WbPolygon &p, float y, const WbVector3 &globalCenterOfMass, const WbVector3 *worldBasis) { const int size = p.actualSize(); wr_dynamic_mesh_clear(mPolygonMesh); wr_dynamic_mesh_clear(mPolygonOutlineMesh); // No contact points if (size == 0) { show(false); return; } show(true); const double globalComX = globalCenterOfMass.dot(worldBasis[X]); const double globalComZ = globalCenterOfMass.dot(worldBasis[Z]); const bool stable = p.contains(globalComX, globalComZ); // Set materials if (stable) { wr_phong_material_set_color(mPolygonMaterial, STABLE_POLYGON_COLOR); wr_phong_material_set_color(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR); wr_phong_material_set_color(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR); wr_phong_material_set_transparency(mPolygonMaterial, STABLE_POLYGON_COLOR[3]); wr_phong_material_set_transparency(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR[3]); wr_phong_material_set_transparency(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR[3]); } else { wr_phong_material_set_color(mPolygonMaterial, UNSTABLE_POLYGON_COLOR); wr_phong_material_set_color(mPolygonOutlineMaterial, UNSTABLE_POLYGON_OUTLINE_COLOR); wr_phong_material_set_color(mCenterOfMassMaterial, UNSTABLE_CENTER_OF_MASS_COLOR); wr_phong_material_set_transparency(mPolygonMaterial, UNSTABLE_POLYGON_COLOR[3]); wr_phong_material_set_transparency(mPolygonOutlineMaterial, UNSTABLE_POLYGON_OUTLINE_COLOR[3]); wr_phong_material_set_transparency(mCenterOfMassMaterial, UNSTABLE_CENTER_OF_MASS_COLOR[3]); } // Set orientations WbRotation rotation(worldBasis[X], worldBasis[Y], worldBasis[Z]); rotation.normalize(); float orientation[4]; rotation.toFloatArray(orientation); wr_transform_set_orientation(mTransform, orientation); // Set the projected center of mass position const float position[3] = {static_cast<float>(globalComX), y, static_cast<float>(globalComZ)}; wr_transform_set_position(mCenterOfMassTransform, position); const float l = wr_config_get_line_scale() * WbWrenRenderingContext::SOLID_LINE_SCALE_FACTOR; // A single contact point if (size == 1) { addVertex(mPolygonOutlineMesh, 0, p[0].x() - l, y, p[0].y()); addVertex(mPolygonOutlineMesh, 1, p[0].x() + l, y, p[0].y()); addVertex(mPolygonOutlineMesh, 2, p[0].x(), y, p[0].y() - l); addVertex(mPolygonOutlineMesh, 3, p[0].x(), y, p[0].y() + l); addVertex(mPolygonOutlineMesh, 4, p[0].x(), y - l, p[0].y()); addVertex(mPolygonOutlineMesh, 5, p[0].x(), y + l, p[0].y()); return; } // Draws the outline int vertexCounter = 0; const int sizeMinusOne = size - 1; for (int i = 0; i < sizeMinusOne; ++i) { addVertex(mPolygonOutlineMesh, vertexCounter++, p[i].x(), y, p[i].y()); addVertex(mPolygonOutlineMesh, vertexCounter++, p[i + 1].x(), y, p[i + 1].y()); } if (size > 2) { // Closes the edge loop addVertex(mPolygonOutlineMesh, vertexCounter++, p[sizeMinusOne].x(), y, p[sizeMinusOne].y()); addVertex(mPolygonOutlineMesh, vertexCounter++, p[0].x(), y, p[0].y()); } else return; // Draws the filled polygon addVertex(mPolygonMesh, 0, p[0].x(), y, p[0].y()); addVertex(mPolygonMesh, 1, p[1].x(), y, p[1].y()); addVertex(mPolygonMesh, 2, p[2].x(), y, p[2].y()); // Draw one side (face culling disabled) for (int i = 3; i <= sizeMinusOne; i++) addVertex(mPolygonMesh, i, p[i].x(), y, p[i].y()); } void WbSupportPolygonRepresentation::setScale(const float *scale) { wr_transform_set_scale(mCenterOfMassTransform, scale); } void WbSupportPolygonRepresentation::cleanup() { wr_node_delete(WR_NODE(mTransform)); wr_node_delete(WR_NODE(mCenterOfMassTransform)); wr_node_delete(WR_NODE(mPolygonRenderable)); wr_node_delete(WR_NODE(mPolygonOutlineRenderable)); wr_node_delete(WR_NODE(mCenterOfMassRenderable)); wr_dynamic_mesh_delete(mPolygonMesh); wr_dynamic_mesh_delete(mPolygonOutlineMesh); wr_static_mesh_delete(mCenterOfMassMesh); wr_material_delete(mPolygonMaterial); wr_material_delete(mPolygonOutlineMaterial); wr_material_delete(mCenterOfMassMaterial); }
9,825
3,880
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cms/model/CreateMyGroupAlertBatchResult.h> #include <json/json.h> using namespace AlibabaCloud::Cms; using namespace AlibabaCloud::Cms::Model; CreateMyGroupAlertBatchResult::CreateMyGroupAlertBatchResult() : ServiceResult() {} CreateMyGroupAlertBatchResult::CreateMyGroupAlertBatchResult(const std::string &payload) : ServiceResult() { parse(payload); } CreateMyGroupAlertBatchResult::~CreateMyGroupAlertBatchResult() {} void CreateMyGroupAlertBatchResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allResources = value["Resources"]["AlertResult"]; for (auto value : allResources) { AlertResult resourcesObject; if(!value["AlertName"].isNull()) resourcesObject.alertName = value["AlertName"].asString(); if(!value["DisplayName"].isNull()) resourcesObject.displayName = value["DisplayName"].asString(); if(!value["MetricNamespace"].isNull()) resourcesObject.metricNamespace = value["MetricNamespace"].asString(); if(!value["MetricName"].isNull()) resourcesObject.metricName = value["MetricName"].asString(); if(!value["Message"].isNull()) resourcesObject.message = value["Message"].asString(); if(!value["Code"].isNull()) resourcesObject.code = std::stoi(value["Code"].asString()); if(!value["Success"].isNull()) resourcesObject.success = value["Success"].asString() == "true"; if(!value["GroupId"].isNull()) resourcesObject.groupId = std::stol(value["GroupId"].asString()); resources_.push_back(resourcesObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["ErrorCode"].isNull()) errorCode_ = std::stoi(value["ErrorCode"].asString()); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); } std::vector<CreateMyGroupAlertBatchResult::AlertResult> CreateMyGroupAlertBatchResult::getResources()const { return resources_; } int CreateMyGroupAlertBatchResult::getErrorCode()const { return errorCode_; } std::string CreateMyGroupAlertBatchResult::getErrorMessage()const { return errorMessage_; } bool CreateMyGroupAlertBatchResult::getSuccess()const { return success_; }
2,892
896
/* Copyright (c) 2018 PaddlePaddle 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 "boost/optional.hpp" #include "paddle/fluid/framework/data_layout_transform.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/memory/malloc.h" #include "paddle/fluid/operators/conv_op.h" #include "paddle/fluid/platform/mkldnn_reuse.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using framework::DataLayout; template <typename T> class ConvTransposeMKLDNNOpKernel : public paddle::framework::OpKernel<T> { public: void Compute(const paddle::framework::ExecutionContext& ctx) const override { PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true, paddle::platform::errors::PreconditionNotMet( "Operator DNNL ConvTranspose must use CPUPlace")); const bool is_test = ctx.Attr<bool>("is_test"); PADDLE_ENFORCE_EQ(is_test, true, platform::errors::InvalidArgument( "ConvTransposeMKLDNN works only for inference. " "Set is_test = True. but got is_test=False .")); auto& dev_ctx = ctx.template device_context<paddle::platform::MKLDNNDeviceContext>(); const auto& mkldnn_engine = dev_ctx.GetEngine(); auto* input = ctx.Input<Tensor>("Input"); auto* filter = ctx.Input<Tensor>("Filter"); auto* bias = ctx.HasInput("Bias") ? ctx.Input<Tensor>("Bias") : nullptr; auto* output = ctx.Output<Tensor>("Output"); PADDLE_ENFORCE_EQ( input->layout(), DataLayout::kMKLDNN, platform::errors::InvalidArgument( "Got wrong layout = %d for Input tensor.", input->layout())); PADDLE_ENFORCE_NE(input->format(), MKLDNNMemoryFormat::undef, platform::errors::InvalidArgument( "Got wrong format for Input tensor.")); PADDLE_ENFORCE_EQ( filter->layout(), DataLayout::kMKLDNN, platform::errors::InvalidArgument( "The filter tensor's laytout should be %d, but got %d.", DataLayout::kMKLDNN, filter->layout())); PADDLE_ENFORCE_NE(filter->format(), MKLDNNMemoryFormat::undef, platform::errors::InvalidArgument( "Got wrong formats for Filter tensor.")); PADDLE_ENFORCE_EQ( input->dims().size(), 4, platform::errors::InvalidArgument( "Input must be with 4 dimensions, i.e. NCHW. but got dimension =%d", input->dims().size())); PADDLE_ENFORCE_EQ( filter->dims().size(), 4, platform::errors::InvalidArgument("Filter must be with 4 dimensions, " "i.e. OIHW, but got dimension =%d", filter->dims().size())); if (bias) { PADDLE_ENFORCE_EQ( bias->layout(), DataLayout::kMKLDNN, platform::errors::InvalidArgument( "The bias tensor's laytout should be %d, but got %d.", DataLayout::kMKLDNN, bias->layout())); PADDLE_ENFORCE_NE(bias->format(), MKLDNNMemoryFormat::undef, platform::errors::InvalidArgument( "Got wrong format for Bias tensor.")); PADDLE_ENFORCE_EQ( bias->dims().size(), 1, platform::errors::InvalidArgument("Bias must only have 1 dimension, " "i.e. X, but got dimension = %d .", bias->dims().size())); } std::vector<int> strides_temp = ctx.Attr<std::vector<int>>("strides"); std::vector<int64_t> strides(begin(strides_temp), end(strides_temp)); std::vector<int> paddings_temp = ctx.Attr<std::vector<int>>("paddings"); std::vector<int64_t> paddings(begin(paddings_temp), end(paddings_temp)); std::vector<int> dilations_temp = ctx.Attr<std::vector<int>>("dilations"); std::vector<int64_t> dilations(begin(dilations_temp), end(dilations_temp)); int groups = ctx.Attr<int>("groups"); std::string padding_algorithm = ctx.Attr<std::string>("padding_algorithm"); PADDLE_ENFORCE_EQ( strides.size(), 2, platform::errors::Unimplemented( "Now we only support 2d oneDNN convolution transpose op")); auto input_dims = input->dims(); auto data_dims = framework::slice_ddim(input_dims, 2, input_dims.size()); auto filter_dims = filter->dims(); auto filter_data_dims = framework::slice_ddim(filter_dims, 2, filter_dims.size()); auto ksize = framework::vectorize(filter_data_dims); UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm, data_dims, strides, ksize); std::transform(dilations.begin(), dilations.end(), dilations.begin(), [](int64_t i) { return i - 1; }); const T* input_data = input->data<T>(); const T* filter_data = filter->data<T>(); auto src_tz = paddle::framework::vectorize<int64_t>(input->dims()); auto iohw_weights_tz = paddle::framework::vectorize<int64_t>(filter->dims()); auto weights_tz = iohw_weights_tz; // IOHW -> OIHW weights_tz[0] = iohw_weights_tz[1]; weights_tz[1] = iohw_weights_tz[0]; // Custom Reorder from IOHW to OIHW auto iohw2oihw_reorder = [&iohw_weights_tz](const T* filter_data) -> std::shared_ptr<T> { int o = iohw_weights_tz[1]; int c = iohw_weights_tz[0]; int h = iohw_weights_tz[2]; int w = iohw_weights_tz[3]; std::shared_ptr<T> reordered_filter_data(new T[o * c * h * w](), std::default_delete<T[]>()); for (int i = 0; i < c; ++i) { for (int j = 0; j < o; ++j) { int in_offset = j * h * w + i * o * h * w; int out_offset = j * c * h * w + i * h * w; std::memcpy(&(reordered_filter_data.get())[out_offset], &filter_data[in_offset], h * w * sizeof(T)); } } return reordered_filter_data; }; int g = std::max(groups, 1); if (g > 1) { int o = weights_tz[0]; int i = weights_tz[1]; int h = weights_tz[2]; int w = weights_tz[3]; weights_tz.resize(5); weights_tz[0] = g; weights_tz[1] = o / g; weights_tz[2] = i; weights_tz[3] = h; weights_tz[4] = w; } auto dst_tz = paddle::framework::vectorize<int64_t>(output->dims()); // Get unique name for storing MKLDNN primitives const std::string key = platform::CreateKey(dev_ctx, src_tz, ctx.OutputName("Output")); std::vector<mkldnn::primitive> pipeline; auto user_src_md = platform::MKLDNNMemDesc( {src_tz}, platform::MKLDNNGetDataType<T>(), input->format()); auto user_weights_md = platform::MKLDNNMemDesc( {weights_tz}, platform::MKLDNNGetDataType<T>(), (g == 1) ? MKLDNNMemoryFormat::oihw : MKLDNNMemoryFormat::goihw); /* create memory descriptor for convolution without specified format * ('any') which lets a primitive (convolution in this case) choose * the memory format preferred for best performance */ auto chosen_memory_format = MKLDNNMemoryFormat::any; std::string fuse_activation = ctx.Attr<std::string>("fuse_activation"); float fuse_alpha = ctx.Attr<float>("fuse_alpha"); float fuse_beta = ctx.Attr<float>("fuse_beta"); auto src_md = platform::MKLDNNMemDesc( src_tz, platform::MKLDNNGetDataType<T>(), chosen_memory_format); auto weights_md = platform::MKLDNNMemDesc( weights_tz, platform::MKLDNNGetDataType<T>(), chosen_memory_format); std::vector<int64_t> bias_tz; auto dst_md = platform::MKLDNNMemDesc( dst_tz, platform::MKLDNNGetDataType<T>(), chosen_memory_format); platform::ConvTransposeMKLDNNHandler handler(dev_ctx, mkldnn_engine, key); // create a deconv(conv transpose) primitive descriptor and save it for // usage in backward std::shared_ptr<mkldnn::deconvolution_forward::primitive_desc> conv_transpose_pd; auto fwd_prop_kind = is_test ? mkldnn::prop_kind::forward_inference : mkldnn::prop_kind::forward_training; if (bias) { bias_tz = paddle::framework::vectorize<int64_t>(bias->dims()); auto bias_md = platform::MKLDNNMemDesc( bias_tz, platform::MKLDNNGetDataType<T>(), MKLDNNMemoryFormat::x); conv_transpose_pd = handler.AcquireConvolutionPrimitiveDescriptor( src_md, weights_md, bias_md, dst_md, strides, dilations, paddings, mkldnn_engine, fuse_activation, fuse_alpha, fuse_beta, false, fwd_prop_kind); } else { conv_transpose_pd = handler.AcquireConvolutionPrimitiveDescriptor( src_md, weights_md, boost::none, dst_md, strides, dilations, paddings, mkldnn_engine, fuse_activation, fuse_alpha, fuse_beta, false, fwd_prop_kind); } // create mkldnn memory from input tensors (data/weights) auto user_src_memory_p = handler.AcquireSrcMemory( user_src_md, platform::to_void_cast<T>(input_data)); auto user_weights_memory_p = handler.AcquireWeightsMemory( user_weights_md, platform::to_void_cast<T>(filter_data), is_test ? iohw2oihw_reorder : platform::user_function()); // create reorder primitive if the input format is not the preferred one auto src_memory_p = handler.AcquireSrcMemoryFromPrimitive(user_src_memory_p, pipeline); auto weights_memory_p = handler.AcquireWeightsMemoryFromPrimitive( user_weights_memory_p, pipeline, is_test); auto output_data = output->mutable_data<T>(ctx.GetPlace(), handler.GetDstMemorySize()); auto dst_memory_p = handler.AcquireDstMemoryFromPrimitive( platform::to_void_cast<T>(output_data)); auto conv_p = handler.AcquireConvolution(); auto& astream = platform::MKLDNNDeviceContext::tls().get_stream(); if (bias) { const T* bias_data = bias->data<T>(); auto user_bias_md = platform::MKLDNNMemDesc( {bias_tz}, platform::MKLDNNGetDataType<T>(), MKLDNNMemoryFormat::x); auto user_bias_memory_p = handler.AcquireBiasMemory( user_bias_md, platform::to_void_cast<T>(bias_data)); auto bias_memory_p = handler.AcquireBiasMemoryFromPrimitive(user_bias_memory_p, pipeline); conv_p->execute(astream, {{MKLDNN_ARG_SRC, *src_memory_p}, {MKLDNN_ARG_WEIGHTS, *weights_memory_p}, {MKLDNN_ARG_BIAS, *bias_memory_p}, {MKLDNN_ARG_DST, *dst_memory_p}}); } else { conv_p->execute(astream, {{MKLDNN_ARG_SRC, *src_memory_p}, {MKLDNN_ARG_WEIGHTS, *weights_memory_p}, {MKLDNN_ARG_DST, *dst_memory_p}}); } astream.wait(); output->set_layout(DataLayout::kMKLDNN); output->set_format(platform::GetMKLDNNFormat(*dst_memory_p)); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(conv2d_transpose, MKLDNN, ::paddle::platform::CPUPlace, ops::ConvTransposeMKLDNNOpKernel<float>);
11,794
3,916
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lambda/model/UpdateEventSourceMappingRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Lambda::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateEventSourceMappingRequest::UpdateEventSourceMappingRequest() : m_uUIDHasBeenSet(false), m_functionNameHasBeenSet(false), m_enabled(false), m_enabledHasBeenSet(false), m_batchSize(0), m_batchSizeHasBeenSet(false), m_maximumBatchingWindowInSeconds(0), m_maximumBatchingWindowInSecondsHasBeenSet(false), m_destinationConfigHasBeenSet(false), m_maximumRecordAgeInSeconds(0), m_maximumRecordAgeInSecondsHasBeenSet(false), m_bisectBatchOnFunctionError(false), m_bisectBatchOnFunctionErrorHasBeenSet(false), m_maximumRetryAttempts(0), m_maximumRetryAttemptsHasBeenSet(false), m_parallelizationFactor(0), m_parallelizationFactorHasBeenSet(false), m_sourceAccessConfigurationsHasBeenSet(false), m_tumblingWindowInSeconds(0), m_tumblingWindowInSecondsHasBeenSet(false), m_functionResponseTypesHasBeenSet(false) { } Aws::String UpdateEventSourceMappingRequest::SerializePayload() const { JsonValue payload; if(m_functionNameHasBeenSet) { payload.WithString("FunctionName", m_functionName); } if(m_enabledHasBeenSet) { payload.WithBool("Enabled", m_enabled); } if(m_batchSizeHasBeenSet) { payload.WithInteger("BatchSize", m_batchSize); } if(m_maximumBatchingWindowInSecondsHasBeenSet) { payload.WithInteger("MaximumBatchingWindowInSeconds", m_maximumBatchingWindowInSeconds); } if(m_destinationConfigHasBeenSet) { payload.WithObject("DestinationConfig", m_destinationConfig.Jsonize()); } if(m_maximumRecordAgeInSecondsHasBeenSet) { payload.WithInteger("MaximumRecordAgeInSeconds", m_maximumRecordAgeInSeconds); } if(m_bisectBatchOnFunctionErrorHasBeenSet) { payload.WithBool("BisectBatchOnFunctionError", m_bisectBatchOnFunctionError); } if(m_maximumRetryAttemptsHasBeenSet) { payload.WithInteger("MaximumRetryAttempts", m_maximumRetryAttempts); } if(m_parallelizationFactorHasBeenSet) { payload.WithInteger("ParallelizationFactor", m_parallelizationFactor); } if(m_sourceAccessConfigurationsHasBeenSet) { Array<JsonValue> sourceAccessConfigurationsJsonList(m_sourceAccessConfigurations.size()); for(unsigned sourceAccessConfigurationsIndex = 0; sourceAccessConfigurationsIndex < sourceAccessConfigurationsJsonList.GetLength(); ++sourceAccessConfigurationsIndex) { sourceAccessConfigurationsJsonList[sourceAccessConfigurationsIndex].AsObject(m_sourceAccessConfigurations[sourceAccessConfigurationsIndex].Jsonize()); } payload.WithArray("SourceAccessConfigurations", std::move(sourceAccessConfigurationsJsonList)); } if(m_tumblingWindowInSecondsHasBeenSet) { payload.WithInteger("TumblingWindowInSeconds", m_tumblingWindowInSeconds); } if(m_functionResponseTypesHasBeenSet) { Array<JsonValue> functionResponseTypesJsonList(m_functionResponseTypes.size()); for(unsigned functionResponseTypesIndex = 0; functionResponseTypesIndex < functionResponseTypesJsonList.GetLength(); ++functionResponseTypesIndex) { functionResponseTypesJsonList[functionResponseTypesIndex].AsString(FunctionResponseTypeMapper::GetNameForFunctionResponseType(m_functionResponseTypes[functionResponseTypesIndex])); } payload.WithArray("FunctionResponseTypes", std::move(functionResponseTypesJsonList)); } return payload.View().WriteReadable(); }
3,721
1,210
#include <limits> #include <random> #include "llvmUtils.h" #include "utils/graphUtils.h" #include "daikon-inst/comments.h" //todo: move to utils #include <boost/algorithm/string.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wstrict-aliasing" // pragam'ed to aviod warnings due to llvm included files #include "llvm/IR/DIBuilder.h" #include "llvm/IR/LegacyPassManager.h" // #include "llvm/IR/ConstantFold.h" // later versions of llvm will need this #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/LoopSimplify.h" //clang related code #include <clang/CodeGen/CodeGenAction.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Basic/TargetInfo.h> #pragma GCC diagnostic pop #define CLANG_VERSION "6.0" void c2bc( const std::string& fileName, const std::string& outName ) { // make a system call std::ostringstream cmd; cmd << "clang-" << CLANG_VERSION << " -emit-llvm -fno-omit-frame-pointer -Xclang -disable-O0-optnone -gdwarf-2 " << fileName << " -o " << outName << " -c"; // std::cout << cmd.str() << "\n"; if( system( cmd.str().c_str() ) != 0 ) exit(1); } // best guess of location class estimate_loc_pass : public llvm::BasicBlockPass { src_loc ref; src_loc ref_end; src_loc low_est; src_loc up_est; llvm::Instruction* I_low = NULL; llvm::Instruction* I_up = NULL; public: static char ID; llvm::Instruction* get_I_low() { return I_low; } llvm::Instruction* get_I_up() { return I_up; } src_loc get_low_estimate() { return low_est; } src_loc get_up_estimate() { return up_est; } public: estimate_loc_pass( src_loc& loc_, src_loc& ref_end_) : llvm::BasicBlockPass(ID), ref(loc_),ref_end(ref_end_), low_est( 0,0, loc_.file), up_est( UINT_MAX, UINT_MAX, loc_.file) { }; ~estimate_loc_pass() {}; virtual bool runOnBasicBlock( llvm::BasicBlock &bb ) { for( llvm::Instruction& I : bb.getInstList() ) { const llvm::DebugLoc d = I.getDebugLoc(); if( d ) { unsigned l = d.getLine(); unsigned c = d.getCol(); std::string f =llvm::cast<llvm::DIScope>(d.getScope())->getFilename(); src_loc curr(l,c,f); if( f != curr.file ) continue; if( COMPARE_OBJ2(curr, low_est, line, col) || COMPARE_OBJ2(up_est, curr, line, col) ) continue; if( ref_end == curr || COMPARE_OBJ2(ref_end, curr, line, col) ) { up_est = curr; I_up = &I; } if( ref == curr || COMPARE_OBJ2(curr, ref, line, col) ) { low_est = curr; I_low = &I; } // { // std::cerr << "\n"; // dump_triple( low_est ); // dump_triple( ref ); // dump_triple( up_est ); // dump_triple( curr ); // std::cerr << "\n"; // } // auto curr = std::make_tuple(l,c,f); // if( f != std::get<2>(curr) ) continue; // if( COMPARE_TUPLE2(curr, low_est, 0, 1) || // COMPARE_TUPLE2(up_est, curr, 0, 1) ) // continue; // if( ref_end == curr || // COMPARE_TUPLE2(ref_end, curr, 0, 1) ) { // up_est = curr; // I_up = &I; // } // if( ref == curr || // COMPARE_TUPLE2(curr, ref, 0, 1) ) { // low_est = curr; // I_low = &I; // } } } return false; } virtual void getAnalysisUsage(llvm::AnalysisUsage &au) const { au.setPreservesAll(); } virtual llvm::StringRef getPassName() const { return "estimate location pass: finds estimate of a source location!!"; } }; char estimate_loc_pass::ID = 0; llvm::Instruction* estimate_comment_location( std::unique_ptr<llvm::Module>& module, src_loc start, src_loc end) { llvm::legacy::PassManager passMan; auto estimate_pass = new estimate_loc_pass( start, end ); passMan.add( estimate_pass ); passMan.run( *module.get() ); // { // estimate_pass->get_I_low()->dump(); // estimate_pass->get_I_up()->dump(); // dump_triple( estimate_pass->get_low_estimate() ); // dump_triple( estimate_pass->get_up_estimate() ); // } return estimate_pass->get_I_up(); // return estimate_pass->get_low_estimate(); } void estimate_comment_location(std::unique_ptr<llvm::Module>& module, std::vector< comment >& comments, std::map< const bb*, std::pair< std::vector<std::string>, std::vector<std::string> > >& bb_comment_map ) { // collect all the comments that are written at the same program point std::map< llvm::Instruction*, std::vector<std::string> > comment_map; std::vector< std::vector< llvm::Instruction* > > Is; for( auto comment : comments ) { auto start = comment.start; auto end = comment.end; auto comment_text = comment.text; llvm::Instruction* I = estimate_comment_location( module, start, end ); if( comment_map.find(I) != comment_map.end() ) { auto& c_vec = comment_map.at(I); c_vec.push_back(comment_text); }else{ comment_map[I].push_back(comment_text); bool done = false; for( auto& B_Is : Is ) { if( B_Is[0]->getParent() == I->getParent() ) { unsigned i = 0; for( auto& Io : B_Is[0]->getParent()->getInstList() ) { if( i == B_Is.size() || &Io == I ) break; if( &Io == B_Is[i] ) i++; } B_Is.insert( B_Is.begin() + i, I); done = true; } } if( !done ) Is.push_back({I}); } } for( auto& B_Is : Is ) { //intially all instructions in B_Is have same block for( llvm::Instruction* I : B_Is ) { llvm::BasicBlock* bb = I->getParent(); auto& pair = bb_comment_map[bb]; llvm::Instruction* first = &(*(bb->getInstList().begin())); if( bb->getTerminator() == I ) { pair.second = comment_map[I]; }else if( first == I ) { pair.first = comment_map[I]; }else{ pair.second = comment_map[I]; bb->splitBasicBlock(I); } } } } // // clang source to llvm soruce location // warning: the code is without several guards (check CGDebugInfo.cpp in clang) src_loc getLocFromClangSource( const clang::SourceLocation& loc, const clang::SourceManager& sm) { unsigned line = sm.getPresumedLoc(loc).getLine(); unsigned col = sm.getPresumedLoc(loc).getColumn(); std::string file = sm.getFilename(loc); return src_loc(line,col,file); } //this function is a copy from CompilerInstance::ExecuteActuib bool ExecuteAction( clang::CompilerInstance& CI, clang::FrontendAction &Act, std::vector< comment >& comments_found) { // FIXME: Take this as an argument, once all the APIs we used have moved to // taking it as an input instead of hard-coding llvm::errs. llvm::raw_ostream &OS = llvm::errs(); // Create the target instance. CI.setTarget(clang::TargetInfo::CreateTargetInfo(CI.getDiagnostics(), CI.getInvocation().TargetOpts)); if (!CI.hasTarget()) return false; CI.getTarget().adjust(CI.getLangOpts()); CI.getTarget().adjustTargetOptions(CI.getCodeGenOpts(), CI.getTargetOpts()); for (const clang::FrontendInputFile &FIF : CI.getFrontendOpts().Inputs) { // Reset the ID tables if we are reusing the SourceManager and parsing // regular files. if (CI.hasSourceManager() && !Act.isModelParsingAction()) CI.getSourceManager().clearIDTables(); if (Act.BeginSourceFile( CI, FIF)) { Act.Execute(); clang::ASTContext& ast_ctx = CI.getASTContext(); clang::SourceManager& sm = CI.getSourceManager(); clang::RawCommentList& comment_list = ast_ctx.getRawCommentList(); for( clang::RawComment* cmnt : comment_list.getComments() ) { // OS << comment->getRawText( sm ) << "\n"; //todo: check prefix of the comment std::string multi_cmt = cmnt->getRawText( sm ); std::vector<std::string> cmts; boost::split(cmts, multi_cmt, [](char c){return c == '\n';}); for( auto cmt : cmts ) { comment c; boost::algorithm::trim(cmt); if(COMMENT_PREFIX == cmt.substr(0, COMMENT_PREFIX_LEN) ) { c.text = cmt.substr(COMMENT_PREFIX_LEN, cmt.size()-COMMENT_PREFIX_LEN ); c.start = getLocFromClangSource(cmnt->getSourceRange().getBegin(), sm); c.end = getLocFromClangSource( cmnt->getSourceRange().getEnd(), sm); comments_found.push_back(c); } } } Act.EndSourceFile(); } } // Notify the diagnostic client that all files were processed. CI.getDiagnostics().getClient()->finish(); if ( CI.getDiagnosticOpts().ShowCarets) { // We can have multiple diagnostics sharing one diagnostic client. // Get the total number of warnings/errors from the client. unsigned NumWarnings = CI.getDiagnostics().getClient()->getNumWarnings(); unsigned NumErrors = CI.getDiagnostics().getClient()->getNumErrors(); if (NumWarnings) OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); if (NumWarnings && NumErrors) OS << " and "; if (NumErrors) OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); } return !CI.getDiagnostics().getClient()->getNumErrors(); } //Direct translation via API clang std::unique_ptr<llvm::Module> c2ir( std::string filename, llvm::LLVMContext& llvm_ctx, std::vector< comment >& comments ) { // return nullptr; // look in clang/include/clang/Driver/CC1Options.td // and clang/lib/Frontend/CompilerInvocation.cpp // to find right param names std::vector<const char *> args; args.push_back( "-emit-llvm" ); args.push_back( "-disable-llvm-passes" ); args.push_back( "-debug-info-kind=standalone" ); args.push_back( "-dwarf-version=2" ); args.push_back( "-dwarf-column-info" ); args.push_back( "-mdisable-fp-elim"); args.push_back( "-femit-all-decls" ); args.push_back( "-O1" ); args.push_back( "-disable-O0-optnone" ); args.push_back( filename.c_str() ); clang::CompilerInstance Clang; Clang.createDiagnostics(); std::shared_ptr<clang::CompilerInvocation> CI(new clang::CompilerInvocation()); clang::CompilerInvocation::CreateFromArgs( *CI.get(), &args[0], &args[0] + args.size(), Clang.getDiagnostics()); Clang.setInvocation(CI); clang::CodeGenAction *Act = new clang::EmitLLVMOnlyAction(&llvm_ctx); if (!ExecuteAction(Clang, *Act, comments)) // if (!Clang.ExecuteAction(*Act)) return nullptr; std::unique_ptr<llvm::Module> module = Act->takeModule(); return std::move(module); return nullptr; } std::unique_ptr<llvm::Module> c2ir( std::string filename, llvm::LLVMContext& llvm_ctx ) { std::vector< comment > comments_found; return move( c2ir( filename, llvm_ctx, comments_found ) ); } void setLLVMConfigViaCommandLineOptions( std::string strs ) { std::string n = "test"; const char* array[2]; array[0] = n.c_str(); array[1] = strs.c_str(); llvm::cl::ParseCommandLineOptions( 2, array ); } void printSegmentInfo(segment& s) { std::cout << "\nPrinting segment info for segment " << &s; std::cout << "\nPrinting entry blocks\n"; printBlockInfo(s.entryCutPoints); std::cout << "\nPrinting exit blocks\n"; printBlockInfo(s.exitCutPoints); std::cout << "\nPrinting body blocks\n"; printBlockInfo(s.bodyBlocks); } void printBlockInfo(std::vector<llvm::BasicBlock*>& blockList) { for(const llvm::BasicBlock* b : blockList) { b->printAsOperand(llvm::errs(), false); std::cout << "\n"; } } std::string getVarName(const llvm::DbgValueInst* dVal ) { // auto var = dVal->getValue(); auto md = dVal->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); return (std::string)( diMd->getName() ); } std::string getVarName(const llvm::DbgDeclareInst* dDecl ) { // auto var = dDecl->getAddress(); auto md = dDecl->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); auto str = (std::string)( diMd->getName() ); return str; } void buildNameMap( options& o, llvm::Function& f, name_map& localNameMap) { std::map<const llvm::Value*, std::set<std::string> > l_name_map_extra; // std::map<std::string, llvm::Value*>& nameValueMap) { // std::cout << "Inside buildNameMap\n"; // localNameMap.clear(); // nameValueMap.clear(); for( llvm::inst_iterator iter(f),end(f,true); iter != end; ++iter ) { llvm::Instruction* I = &*iter; llvm::Value* var = NULL; llvm::MDNode* md = NULL; std::string str; if( llvm::DbgDeclareInst* dDecl = llvm::dyn_cast<llvm::DbgDeclareInst>(I) ) { var = dDecl->getAddress(); md = dDecl->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); // std::cout << "Got the name:" << str << "\n"; } else if( llvm::DbgValueInst* dVal = llvm::dyn_cast<llvm::DbgValueInst>(I)) { var = dVal->getValue(); md = dVal->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); if( llvm::isa<llvm::ConstantInt>(var) ) { var = dVal; } // std::cout << "Got the name:" << str << "\n"; } if( var ) { // if var is non-null add the name to the map if( localNameMap.find(var) != localNameMap.end() ) { if( str != localNameMap.at( var ) ) l_name_map_extra[var].insert( str ); } localNameMap[var] = str; // nameValueMap[str] = var; //to look at the scope field // check if there has been a declaration with same name with different // line number // auto it = declarationLocationMap.find( str ); // if( it == declarationLocationMap.end() ) { // declarationLocationMap[str] = lineNum; // localNameMap[var] = str; // nameValueMap[str] = var; // }else if( it->second == lineNum ) { // localNameMap[var] = str; // nameValueMap[str] = var; // }else{ // localNameMap[var] = str + "_at_"+ std::to_string( lineNum ); // nameValueMap[str] = var; // } } } //Extend names to phiNodes // if phinode names are misssing, for( auto& b: f.getBasicBlockList() ) { for( llvm::BasicBlock::iterator I = b.begin(); llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *phi = llvm::cast<llvm::PHINode>(I); unsigned num = phi->getNumIncomingValues(); std::set<std::string> names; for ( unsigned i = 0 ; i < num ; i++ ) { llvm::Value *v = phi->getIncomingValue(i); if(llvm::Instruction *inI = llvm::dyn_cast<llvm::Instruction>(v)) { if( localNameMap.find(inI) != localNameMap.end() ) { auto back_name = localNameMap.at(inI); names.insert( back_name ); if( l_name_map_extra.find(inI) != l_name_map_extra.end() ) set_insert( l_name_map_extra.at(inI), names ); } } } bool found = ( localNameMap.find(phi) != localNameMap.end() ); if( names.size() == 1) { std::string name = *names.begin(); if( found && localNameMap.at(phi) != name ) { if( o.verbosity > 5 ) { tiler_warning("build name map::","multiple names found for a value!!"); } } localNameMap[phi] = name; }else if( found && l_name_map_extra.find( phi ) == l_name_map_extra.end() ) { // the name is already there std::string name = localNameMap.at(phi); if( names.find( name ) == names.end() && o.verbosity > 5 ) { tiler_warning("build name map::","multiple mismatching names found for a value!!"); } }else if( names.size() > 1 || l_name_map_extra.find( phi ) != l_name_map_extra.end() ) { if( o.verbosity > 5 ) { for( auto name : names ) { std::cout << name << "\n"; } if(found) std::cout << localNameMap.at(phi) << "\n" ; if( l_name_map_extra.find(phi) != l_name_map_extra.end() ) for( auto name : l_name_map_extra.at( phi ) ) { std::cout << name << "\n"; } tiler_warning( "build name map::","multiple names found!!"); } } // auto back_name = localNameMap.at(inI); // if( found && name != localNameMap.at(inI) ) // tiler_error("build name map::","phi node has multiple names!!"); // name = localNameMap.at(inI); // found = true; // if( !found ) { // // If this function fails, investigate to find the (correct) name // //tiler_error("build name map::","name of a phi node not found!!"); // } } } } bool isRemInBop(const llvm::BinaryOperator* bop) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::URem : return true; case llvm::Instruction::SRem: return true; case llvm::Instruction::FRem: return true; default: return false; } return false; } bool isRemInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::URem : return true; case llvm::Instruction::SRem: return true; case llvm::Instruction::FRem: return true; default: return false; } } else { return false; } } bool isAddInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Add : return true; case llvm::Instruction::FAdd: return true; default: return false; } } else { return false; } } bool isSubInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Sub : return true; case llvm::Instruction::FSub: return true; default: return false; } } else { return false; } } bool isMulInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Mul : return true; case llvm::Instruction::FMul: return true; default: return false; } } else { return false; } } bool isDivInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::SDiv: return true; case llvm::Instruction::UDiv: return true; case llvm::Instruction::FDiv: return true; default: return false; } } else { return false; } } bool isValueInSubExpr(const llvm::Value* val, const llvm::Value* expr) { if(val == expr) return true; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = isValueInSubExpr(val, bop->getOperand(0)); if(res) return true; res = isValueInSubExpr(val, bop->getOperand(1)); return res; } else if( llvm::isa<llvm::CallInst>(expr) ) { return false; // tiler_error( "llvmutils::", "Call instruction as sub-expression not supported"); } else if( auto store = llvm::dyn_cast<llvm::StoreInst>(expr) ) { return isValueInSubExpr(val, store->getOperand(0)); } else if( llvm::isa<llvm::GetElementPtrInst>(expr) ) { return false; // tiler_error( "llvmutils::", "GEP as sub-expression not supported"); } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return isValueInSubExpr(val, load->getOperand(0)); // return false; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return isValueInSubExpr(val, cast->getOperand(0)); } else if( llvm::isa<llvm::AllocaInst>(expr) ) { return false; // tiler_error( "llvmutils::", "Alloca as sub-expression not supported"); // return isValueInExpr(val, alloca->getArraySize()); } else { return false; } } bool onlyValueInSubExpr(const llvm::Value* val, const llvm::Value* expr) { if( auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = true; if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(0)) ) res = onlyValueInSubExpr(val, bop->getOperand(0)); if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(1)) ) if(res) res = res && onlyValueInSubExpr(val, bop->getOperand(1)); return res; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return onlyValueInSubExpr(val, cast->getOperand(0)); } else if( auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return onlyValueInSubExpr(val, load->getOperand(0)); /* } else if( llvm::isa<llvm::StoreInst>(expr) ) { return false; } else if( llvm::isa<llvm::GetElementPtrInst>(expr) ) { return false; } else if( llvm::isa<llvm::CallInst>(expr) ) { return false; } else if( llvm::isa<llvm::AllocaInst>(expr) ) { return false; */ } else { if(val == expr) return true; else return false; } } bool onlyValuesInSubExpr(std::list<const llvm::Value*>& val_l, const llvm::Value* expr) { if( auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = true; if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(0)) ) res = onlyValuesInSubExpr(val_l, bop->getOperand(0)); if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(1)) ) if(res) res = res && onlyValuesInSubExpr(val_l, bop->getOperand(1)); return res; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return onlyValuesInSubExpr(val_l, cast->getOperand(0)); } else if( auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return onlyValuesInSubExpr(val_l, load->getOperand(0)); } else { for(auto v : val_l) if(v == expr) return true; return false; } } bool isLoadOrStoreInSubExpr(const llvm::Value* expr) { if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = isLoadOrStoreInSubExpr(bop->getOperand(0)); if(res) return true; return isLoadOrStoreInSubExpr(bop->getOperand(1)); } else if(auto call = llvm::dyn_cast<llvm::CallInst>(expr) ) { llvm::Function* fp = call->getCalledFunction(); if( llvm::dyn_cast<llvm::IntrinsicInst>(call) ) { return false; } else if( fp != NULL && fp->getName().startswith("__VERIFIER") ) { return false; } else { tiler_error( "llvmutils::", "Call instruction as sub-expression not supported"); } } else if( llvm::dyn_cast<llvm::StoreInst>(expr) ) { return true; } else if( llvm::dyn_cast<llvm::GetElementPtrInst>(expr) ) { return true; } else if( llvm::dyn_cast<llvm::LoadInst>(expr) ) { return true; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return isLoadOrStoreInSubExpr(cast->getOperand(0)); } else if( llvm::dyn_cast<llvm::AllocaInst>(expr) ) { tiler_error( "llvmutils::", "Alloca as sub-expression not supported"); } else { return false; } } void getLoadsInSubExpr(llvm::Value* expr, std::list<llvm::Value*>& loads) { if( auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { loads.push_back(load); } else if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { getLoadsInSubExpr(bop->getOperand(0), loads); getLoadsInSubExpr(bop->getOperand(1), loads); } else if( llvm::dyn_cast<llvm::CallInst>(expr) ) { tiler_error( "llvmutils::", "Call instruction as sub-expression not supported"); } else if( auto store = llvm::dyn_cast<llvm::StoreInst>(expr) ) { getLoadsInSubExpr(store->getOperand(0), loads); } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { getLoadsInSubExpr(cast->getOperand(0), loads); } else if( llvm::dyn_cast<llvm::AllocaInst>(expr) ) { tiler_error( "llvmutils::", "Alloca as sub-expression not supported"); } else {} } bool isInHeader(llvm::Instruction *I, llvm::Loop *L) { // std::cout << "In isInHeader\n"; auto h = L->getHeader(); auto b = I->getParent(); if(h==b) { // std::cout << "In Header\n"; return true; } else { // std::cout << "Not in Header\n"; return false; } } bool isOutOfLoop(llvm::Instruction *I, llvm::Loop *L) { // std::cout << "In isOutOfLoop\n"; if(L==NULL) { return true; } auto bb = I->getParent(); for( auto b: L->getBlocks() ) { if(b == bb) { // std::cout << "Is in the loop\n"; return false; } } // std::cout << "Is out of the loop\n"; return true; } bool isMyLatch(llvm::BasicBlock *b, llvm::Loop *L) { // std::cout << "In isInLatch\n"; if(L==NULL) { return false; } auto h = L->getLoopLatch(); return h == b; } bool isInLatch(llvm::Instruction *I, llvm::Loop *L) { if(L==NULL) { return false; } auto b = I->getParent(); // return isMyLatch( b, L ); //todo: auto h = L->getLoopLatch(); if(h==b) { return true; } else { return false; } } unsigned valueIdxFromLatch( llvm::PHINode* phi, llvm::Loop * loop) { assert( phi->getNumIncomingValues() == 2 ); unsigned i =0; if( isMyLatch( phi->getIncomingBlock(0), loop) ) { i = 0; }else if( isMyLatch( phi->getIncomingBlock(1), loop) ) { i = 1; }else{ tiler_error( "llvmutils::", "header latch did not match!!"); } return i; } bool isLoopRotated( llvm::Loop * loop ) { auto t = loop->getLoopLatch()->getTerminator(); if( auto br = llvm::dyn_cast<llvm::BranchInst>(t) ) { return br->isConditional(); } tiler_error( "llvmutils::", "loops always end with conditionals!!"); return false; } // Check whether the loop can be analyzed by us. bool isSupported(llvm::Loop *L) { // Make sure the loop is in simplified form if (!L->isLoopSimplifyForm()) return false; // Only support loops that contain a single exit if (!L->getExitingBlock() || !L->getUniqueExitBlock()) return false; return true; } // Check if the given basic block is in sub loop of the current loop bool isInSubLoop(llvm::BasicBlock *BB, llvm::Loop *CurLoop, llvm::LoopInfo *LI) { if(!CurLoop->contains(BB)) { std::cout << "Check is valid only if the basic block is in the current loop or its sub loop"; } return LI->getLoopFor(BB) != CurLoop; } bool hasPhiNode(llvm::Value* v) { assert(v); if (llvm::isa<llvm::PHINode>(v)) { return true; } else if(llvm::isa<llvm::BinaryOperator>(v)) { llvm::BinaryOperator* bop = llvm::dyn_cast<llvm::BinaryOperator>(v); auto op0 = bop->getOperand( 0 ); auto op1 = bop->getOperand( 1 ); if(hasPhiNode(op0)) { return true; } if(hasPhiNode(op1)) { return true; } return false; } else { return false; } } llvm::Value* getPhiNode(llvm::Value* expr) { assert(expr); if (llvm::isa<llvm::PHINode>(expr)) { return expr; } else if(llvm::isa<const llvm::GlobalVariable>(expr)) { return NULL; // Global Variables are not phi and they don't have phi } else if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr)){ auto phi0 = getPhiNode(bop->getOperand( 0 )); if(phi0 != NULL) { return phi0; } auto phi1 = getPhiNode(bop->getOperand( 1 )); if(phi1 != NULL) { return phi1; } return NULL; } else { return NULL; } } // Return true of the block has atleast one successor bool hasSuccessor(const llvm::BasicBlock* b) { if(llvm::succ_begin(b) == llvm::succ_end(b)) { return false; } else { return true; } } // Return the first Basic Block in the Body of the Current Loop llvm::BasicBlock* getFirstBodyOfLoop(llvm::Loop *CurLoop){ llvm::BasicBlock* head = CurLoop->getHeader(); const llvm::TerminatorInst *TInst = head->getTerminator(); // const llvm::Instruction *TInst = head->getTerminator(); // LLVM 8 assert(TInst->isTerminator()); // unsigned nbSucc = TInst->getNumSuccessors(); bool found = false; unsigned i = 0; llvm::BasicBlock *next = TInst->getSuccessor(i); while(!found) { if(next!=CurLoop->getExitBlock()) found=true; else{ i++; next = TInst->getSuccessor(i); } } std::cout << "First body block in the current loop is :" << next->getName().str() << "\n"; return next; } std::string getFuncNameForDaikon(llvm::Loop *L) { std::string fName = "__TILER_Loop_"; auto loc = L->getStartLoc(); fName = fName + std::to_string(loc->getLine()); return fName; } llvm::Function *rand_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *rand_type = llvm::FunctionType::get( llvm::Type::getInt32Ty(mod->getContext()), false); /* llvm::TypeBuilder<int(void), false>::get(glbContext); // TypeBuilder deprecated from 8.0.1 */ auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Constant *c = mod->getOrInsertFunction( "rand", rand_type, attr_list ); llvm::Function *func = NULL; if(llvm::isa<llvm::CastInst>(c)) { func = llvm::cast<llvm::Function>( c->getOperand(0)); } else { func = llvm::cast<llvm::Function>( c ); } return func; } llvm::Function *printf_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *printf_type = llvm::FunctionType::get( llvm::Type::getInt32Ty(mod->getContext()), llvm::PointerType::get(llvm::Type::getInt8Ty(mod->getContext()), false), true); /* llvm::TypeBuilder<int(char *, ...), false>::get(glbContext); // TypeBuilder deprecated from 8.0.1 */ auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Function *func = llvm::cast<llvm::Function>(mod->getOrInsertFunction( "printf", printf_type, attr_list )); return func; } llvm::Function *assume_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *assume_type = NULL; llvm::FunctionType::get( llvm::Type::getVoidTy(mod->getContext()), llvm::Type::getInt32Ty(mod->getContext()), false); // llvm::TypeBuilder<void(int), false>::get(glbContext); auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Function *func = llvm::cast<llvm::Function>(mod->getOrInsertFunction( "__llbmc_assume", assume_type, attr_list )); return func; } llvm::Function *assert_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *assert_type = NULL; llvm::FunctionType::get( llvm::Type::getVoidTy(mod->getContext()), llvm::Type::getInt32Ty(mod->getContext()), false); // llvm::TypeBuilder<void(int), false>::get(glbContext); auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Function *func = llvm::cast<llvm::Function>(mod->getOrInsertFunction( "__llbmc_assert", assert_type, attr_list)); return func; } llvm::Constant* geti8StrVal(llvm::Module& M, char const* str, llvm::Twine const& name, llvm::LLVMContext& ctx) { // llvm::LLVMContext& ctx = llvm::getGlobalContext(); llvm::Constant* strConstant = llvm::ConstantDataArray::getString(ctx, str); llvm::GlobalVariable* GVStr = new llvm::GlobalVariable(M, strConstant->getType(), true, llvm::GlobalValue::InternalLinkage, strConstant, name); llvm::Constant* zero = llvm::Constant::getNullValue(llvm::IntegerType::getInt32Ty(ctx)); llvm::Constant* indices[] = {zero, zero}; llvm::Constant* strVal = llvm::ConstantExpr::getGetElementPtr(strConstant->getType(), GVStr, indices, true); return strVal; } void assertSingleNesting(llvm::Loop *L) { if(!L->empty()) { L = *L->begin(); auto it = L->begin(); it++; assert(it == L->end()); assert(L->empty()); } } void assertNonNesting(llvm::Loop *L) { assert(L->empty()); } bool isIncrOp(llvm::Value *V) { bool isAdd=true; if( llvm::Instruction *I = llvm::dyn_cast<llvm::Instruction>(V) ) { if( auto bop = llvm::dyn_cast<llvm::BinaryOperator>(I) ) { auto op0 = bop->getOperand(0); auto op1 = bop->getOperand(1); unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Add : isAdd=true; break; case llvm::Instruction::Sub : isAdd=false; break; default: std::cout << "\n\nInvalid operation. Must be + or -\n\n"; exit(1); } if( llvm::ConstantInt *C = llvm::dyn_cast<llvm::ConstantInt>(op0) ) { if(isAdd && C->isNegative()) { return false; } else if(!isAdd && C->isNegative()) { return true; } } else if( llvm::ConstantInt *C = llvm::dyn_cast<llvm::ConstantInt>(op1) ) { if(isAdd && C->isNegative()) { return false; } else if(!isAdd && C->isNegative()) { return true; } } } } return true; } llvm::GetElementPtrInst* getGEP(llvm::LoadInst* load) { auto addr = load->getOperand(0); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr)) return elemPtr; else return NULL; // No GEP for global variables } llvm::GetElementPtrInst* getGEP(llvm::StoreInst* store) { auto addr = store->getOperand(1); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) return elemPtr; else return NULL; // No GEP for global variables } llvm::Value* getIdx(llvm::LoadInst* load) { if(auto elemPtr = getGEP(load)) { auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); return idx; } else { return NULL; // No indices for global variables } } llvm::Value* getIdx(llvm::StoreInst* store) { if(auto elemPtr = getGEP(store)) { auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); return idx; } else { return NULL; // No indices for global variables } } llvm::AllocaInst* getAlloca(llvm::LoadInst* load) { if(auto elemPtr = getGEP(load)) { auto arry = elemPtr->getPointerOperand(); llvm::AllocaInst *arry_alloca = llvm::dyn_cast<llvm::AllocaInst>(arry); return arry_alloca; } else { return NULL; // No alloca inst for global variables } } llvm::AllocaInst* getAlloca(llvm::StoreInst* store) { if(auto elemPtr = getGEP(store)) { auto arry = elemPtr->getPointerOperand(); llvm::AllocaInst *arry_alloca = llvm::dyn_cast<llvm::AllocaInst>(arry); return arry_alloca; } else { return NULL; // No alloca inst for global variables } } llvm::Loop* getNextLoop(std::list<llvm::Loop*> lList, llvm::Loop* L) { bool flag = false; for(llvm::Loop* lo : lList) { if(flag) { return lo; } if(lo == L) { flag = true; } } return NULL; } llvm::Value* getArrValueFromZ3Expr(llvm::Value *V, z3::expr e, llvm::IRBuilder<> &irb, llvm::LLVMContext& c, std::map<std::string, llvm::Value*>& exprValMap, std::set<llvm::Value*>& arrSet) { llvm::Value *res = getValueFromZ3Expr(e, irb, c, exprValMap, arrSet); if(V != NULL ) { res = irb.CreateGEP(V, res); res = irb.CreateLoad(res); res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); assert(res); } return res; } llvm::Value* getValueFromZ3Expr(z3::expr e, llvm::IRBuilder<> &irb, llvm::LLVMContext& c, std::map<std::string, llvm::Value*>& exprValMap, std::set<llvm::Value*>& arrSet) { llvm::Value *res = NULL; if(e.is_numeral()) { int64_t num; if (Z3_get_numeral_int64(e.ctx(), e, &num)) { res = llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(c), num); assert(res); } } else if (e.is_var()) { std::string varName = e.decl().name().str(); // std::cout << "\n Getting Val for Expr: " << varName << "\n"; res = exprValMap.at(varName); assert(res); if(llvm::isa<llvm::GlobalVariable>(res)) { res = irb.CreateLoad(res); } else { // res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); } assert(res); } else if (e.is_app()) { // std::cout << "\n Getting val for subexpr \n"; res = getValueFromZ3SubExpr(e, irb, c, exprValMap, arrSet); assert(res); } else if (e.is_quantifier()) { tiler_error("llvmUtils", "encountered a quantifier"); } return res; } llvm::Value* getValueFromZ3SubExpr(z3::expr e, llvm::IRBuilder<> &irb, llvm::LLVMContext& c, std::map<std::string, llvm::Value*>& exprValMap, std::set<llvm::Value*>& arrSet) { std::list<llvm::Value*> argValList; unsigned args = e.num_args(); for (unsigned i = 0; i<args; i++) { z3::expr arg = e.arg(i); argValList.push_back(getValueFromZ3Expr(arg, irb, c, exprValMap, arrSet)); } Z3_decl_kind dk = e.decl().decl_kind(); std::list<llvm::Value*>::const_iterator argListIt; argListIt = argValList.begin(); if (dk == Z3_OP_MUL) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateMul(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_ADD) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateAdd(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_SUB) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateSub(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_DIV || dk == Z3_OP_IDIV) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateSDiv(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_REM) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateSRem(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_UMINUS) { llvm::Value* res = irb.CreateNeg(*argListIt); assert(res); return res; } else if (dk == Z3_OP_SELECT) { // std::cout << "\n Found a select statement with " << args << " args \n"; llvm::Value* Arr = *argListIt; assert(Arr); argListIt++; llvm::Value* Ind = *argListIt; assert(Ind); llvm::Value* res = irb.CreateGEP(Arr, Ind); assert(res); res = irb.CreateLoad(res); assert(res); // res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); assert(res); return res; } else if (dk == Z3_OP_NOT) { llvm::Value* res = irb.CreateNot(*argListIt); assert(res); return res; } else if (dk == Z3_OP_AND) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateAnd(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_OR) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateOr(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_EQ) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpEQ(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_GE) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSGE(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_GT) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSGT(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_LE) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSLE(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_LT) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSLT(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else { std::string varName = e.decl().name().str(); llvm::Value* res = exprValMap.at(varName); assert(res); if(arrSet.count(res) == 0) { if(llvm::isa<llvm::GlobalVariable>(res)) { res = irb.CreateLoad(res); } else { // res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); } assert(res); } return res; } } bool checkRangeOverlap(z3::expr range1, z3::expr range2) { z3::context& z3_ctx = range1.ctx(); z3::expr_vector ipsrc(z3_ctx); z3::expr_vector ipdst(z3_ctx); std::string lbName = "__lb"; std::string ubName = "__ub"; z3::expr lb = z3_ctx.int_const(lbName.c_str()); z3::expr ub = z3_ctx.int_const(ubName.c_str()); std::string lbpName = lbName+"_p"; std::string ubpName = ubName+"_p"; z3::expr lbp = z3_ctx.int_const(lbpName.c_str()); z3::expr ubp = z3_ctx.int_const(ubpName.c_str()); ipsrc.push_back(ub); ipsrc.push_back(lb); ipdst.push_back(ubp); ipdst.push_back(lbp); z3::expr sub_range2 = range2.substitute(ipsrc, ipdst); z3::solver s(z3_ctx); s.add(range1); s.add(sub_range2); if (s.check() == z3::sat) { return true; } else { return false; } } void collect_fun_bb(llvm::Function* f, std::vector<llvm::BasicBlock*>& fun_bb_vec) { for( auto bbit = f->begin(), end = f->end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); fun_bb_vec.push_back(bb); } } void get_topologically_sorted_bb(llvm::Function *f, std::vector<llvm::BasicBlock*>& fun_bb_vec) { llvm::ReversePostOrderTraversal<llvm::Function*> RPOT(f); for (llvm::ReversePostOrderTraversal<llvm::Function*>::rpo_iterator RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) { llvm::BasicBlock* b = *RI; fun_bb_vec.push_back(b); // b->print( llvm::outs() ); llvm::outs() << "\n\n"; } } void collect_arr(llvm::Function &f, std::set<llvm::AllocaInst*>& arrSet) { arrSet.clear(); for( auto bbit = f.begin(), end = f.end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); for( llvm::Instruction& Iobj : bb->getInstList() ) { llvm::Instruction* I = &(Iobj); if( auto alloc = llvm::dyn_cast<llvm::AllocaInst>(I) ) { if( alloc->isArrayAllocation() && !alloc->getType()->getElementType()->isIntegerTy() && !alloc->getType()->getElementType()->isFloatTy()) { tiler_error( "llvmUtils", "only pointers to intergers and floats is allowed!" ); } arrSet.insert( alloc ); } } } } bool is_assume_call(const llvm::CallInst* call) { assert( call ); llvm::Function* fp = call->getCalledFunction(); if( fp != NULL && (fp->getName() == "_Z6assumeb" || fp->getName() == "assume" || fp->getName() == "assume_abort_if_not" || fp->getName().startswith("__VERIFIER_assume") ) ) { return true; } else if (fp == NULL) { const llvm::Value * val = call->getCalledValue(); if( auto CE = llvm::dyn_cast<llvm::ConstantExpr>(val) ) { if(CE->isCast()) { if(CE->getOperand(0)->getName() == "assume" || CE->getOperand(0)->getName() == "assume_abort_if_not" || CE->getOperand(0)->getName() == "_Z6assumeb" || CE->getOperand(0)->getName().startswith("__VERIFIER_assume")) { return true; } } } } return false; } bool is_assert_call(const llvm::CallInst* call ) { assert( call ); llvm::Function* fp = call->getCalledFunction(); if( fp != NULL && (fp->getName() == "_Z6assertb" || fp->getName() == "assert" || fp->getName().startswith("__VERIFIER_assert") ) ) { return true; } else if (fp == NULL) { const llvm::Value * val = call->getCalledValue(); if( auto CE = llvm::dyn_cast<llvm::ConstantExpr>(val) ) { if(CE->isCast()) { if(CE->getOperand(0)->getName() == "assert" || CE->getOperand(0)->getName() == "_Z6assertb" || CE->getOperand(0)->getName().startswith("__VERIFIER_assert") ) { return true; } } } } return false; } bool is_assert_loop( llvm::Loop* L ) { bool assert_seen=false; for( auto bb: L->getBlocks() ) { for( auto it = bb->begin(), e = bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto call = llvm::dyn_cast<llvm::CallInst>(I) ) { if(llvm::isa<llvm::DbgValueInst>(I) ||llvm::isa<llvm::DbgDeclareInst>(I)){ // Ignore debug instructions }else{ assert_seen = assert_seen || is_assert_call(call); } } } } return assert_seen; } class bb_succ_iter : public llvm::succ_const_iterator { public: bb_succ_iter( llvm::succ_const_iterator begin_, llvm::succ_const_iterator end_, std::set<const llvm::BasicBlock*>& back_edges ) : llvm::succ_const_iterator( begin_ ), end(end_), b_edges( back_edges ) { llvm::succ_const_iterator& it = (llvm::succ_const_iterator&)*this; while( it != end && exists( b_edges, (const llvm::BasicBlock*)*it) ) ++it; }; bb_succ_iter( llvm::succ_const_iterator begin_, llvm::succ_const_iterator end_ ) : llvm::succ_const_iterator( begin_ ), end(end_) {}; bb_succ_iter( llvm::succ_const_iterator end_ ) : llvm::succ_const_iterator( end_ ), end( end_ ) {}; llvm::succ_const_iterator end; std::set<const llvm::BasicBlock*> b_edges; bb_succ_iter& operator++() { llvm::succ_const_iterator& it = (llvm::succ_const_iterator&)*this; do{ ++it; }while( it != end && exists( b_edges, (const llvm::BasicBlock*)*it) ); return *this; } }; void computeTopologicalOrder( llvm::Function &F, std::map<const llvm::BasicBlock*,std::set<const llvm::BasicBlock*>>& bedges, std::vector<const llvm::BasicBlock*>& bs, std::map< const llvm::BasicBlock*, unsigned >& o_map) { auto f = [&bedges](const llvm::BasicBlock* b) { if( exists( bedges, b ) ) { return bb_succ_iter( llvm::succ_begin(b), llvm::succ_end(b),bedges.at(b)); }else{ return bb_succ_iter( llvm::succ_begin(b), llvm::succ_end(b)); } }; auto e = [](const llvm::BasicBlock* b) { return bb_succ_iter( llvm::succ_end(b) ); }; const llvm::BasicBlock* h = &F.getEntryBlock(); bs.clear(); o_map.clear(); topological_sort<const llvm::BasicBlock*, bb_succ_iter>( h, f, e, bs, o_map ); } // Pass p must declare it requires LoopInfoWrapperPass void collect_loop_backedges(llvm::Pass *p, std::map< const llvm::BasicBlock*, std::set<const llvm::BasicBlock*>>& loop_ignore_edge, std::map< const llvm::BasicBlock*, std::set<const llvm::BasicBlock*>>& rev_loop_ignore_edge) { //todo: llvm::FindFunctionBackedges could have done the job auto &LIWP = p->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); std::vector<llvm::Loop*> loops, stack; for(auto I = LI->rbegin(), E = LI->rend(); I != E; ++I) stack.push_back(*I); while( !stack.empty() ) { llvm::Loop *L = stack.back(); stack.pop_back(); loops.push_back( L ); for(auto I = L->begin(), E = L->end(); I != E; ++I) stack.push_back(*I); } loop_ignore_edge.clear(); rev_loop_ignore_edge.clear(); for( llvm::Loop *L : loops ) { auto h = L->getHeader(); llvm::SmallVector<llvm::BasicBlock*,10> LoopLatches; L->getLoopLatches( LoopLatches ); for( llvm::BasicBlock* bb : LoopLatches ) { loop_ignore_edge[h].insert( bb ); rev_loop_ignore_edge[bb].insert(h); } } } void collect_block_ancestors(llvm::BasicBlock* b, std::map<llvm::BasicBlock*, std::set<llvm::BasicBlock*>>& block_preds_map) { auto& preds = block_preds_map[b]; std::vector<llvm::BasicBlock*> stack; std::vector<llvm::BasicBlock*> processed; processed.push_back(b); for (llvm::BasicBlock *pb : llvm::predecessors(b)) { if(block_preds_map.find(pb) != block_preds_map.end()) { preds.insert( pb ); processed.push_back(pb); for(llvm::BasicBlock *ab : block_preds_map.at(pb)) { preds.insert( ab ); processed.push_back(ab); } } else { stack.push_back(pb); processed.push_back(pb); } } while( !stack.empty() ) { llvm::BasicBlock *pb = stack.back(); stack.pop_back(); preds.insert( pb ); for (llvm::BasicBlock *ppb : llvm::predecessors(pb)) { if(find(processed.begin(), processed.end(), ppb) == processed.end()) { stack.push_back(ppb); processed.push_back(ppb); } } } } llvm::Value* collect_loads_recs(llvm::Value* v, llvm::Value* N, std::list<llvm::Value*>& load_lst) { llvm::Value* rec_t = NULL; if(llvm::isa<llvm::LoadInst>(v)) { load_lst.push_back(v); } else if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(v)) { if(isRemInBop(bop)) return NULL; assert( bop ); llvm::Value* rec_t0 = NULL; llvm::Value* rec_t1 = NULL; auto op0 = bop->getOperand( 0 ); auto op1 = bop->getOperand( 1 ); if(llvm::isa<llvm::BinaryOperator>(op0)) { rec_t0 = collect_loads_recs(op0, N, load_lst); } else if(auto op0_l = llvm::dyn_cast<llvm::LoadInst>(op0)) { if(op0_l->getOperand(0) != N) load_lst.push_back(op0_l); else rec_t0 = op0_l; } else rec_t0 = op0; if(llvm::isa<llvm::BinaryOperator>(op1)) { rec_t1 = collect_loads_recs(op1, N, load_lst); } else if(auto op1_l = llvm::dyn_cast<llvm::LoadInst>(op1)) { if(op1_l->getOperand(0) != N) load_lst.push_back(op1_l); else rec_t1 = op1_l; } else rec_t1 = op1; if(rec_t0 != NULL) rec_t = rec_t0; if(rec_t1 != NULL) rec_t = rec_t1; if(rec_t0 != NULL && rec_t1 != NULL) rec_t = bop; } else { rec_t = v; } return rec_t; } // Pass p must declare it requires LoopInfoWrapperPass void find_cutpoints(llvm::Pass* P, llvm::Function &f, std::vector< llvm::BasicBlock* >& cutPoints) { cutPoints.clear(); cutPoints.push_back(&f.getEntryBlock()); std::vector<llvm::Loop*> stack; auto &LIWP = P->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); for(auto I = LI->rbegin(), E = LI->rend(); I != E; ++I) stack.push_back(*I); while( !stack.empty() ) { llvm::Loop *L = stack.back(); stack.pop_back(); cutPoints.push_back( L->getHeader() ); for(auto I = L->begin(), E = L->end(); I != E; ++I) stack.push_back(*I); } } void create_segments(llvm::Function &f, std::vector< llvm::BasicBlock* >& cutPoints, std::vector< segment >& segVec) { segVec.clear(); std::map< llvm::BasicBlock*, bool > bbVisited; std::vector< llvm::BasicBlock* > stack; for (auto fi = f.begin(), fe = f.end(); fi != fe; ++fi) bbVisited[&(*fi)] = false; for(llvm::BasicBlock* bb : cutPoints) { for (llvm::succ_iterator sit = succ_begin(bb), set = succ_end(bb); sit != set; ++sit) { llvm::BasicBlock* b = *sit; segment s; s.entryCutPoints.push_back(bb); bbVisited[bb] = true; std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(bb, nameValueMap); s.assuMapCPs[bb] = nameValueMap; if(exists(cutPoints, b)) { if(!exists(s.exitCutPoints, b)) { s.exitCutPoints.push_back(b); } std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(b, nameValueMap); s.assertMapCPs[b] = nameValueMap; } else if(!bbVisited.at(b)) { stack.push_back(b); while(!stack.empty()) { llvm::BasicBlock* sbb = stack.back(); if(bbVisited.at(sbb)) { stack.pop_back(); } else { s.bodyBlocks.push_back(sbb); bbVisited[sbb] = true; stack.pop_back(); for (llvm::succ_iterator sit = succ_begin(sbb), set = succ_end(sbb); sit != set; ++sit) { llvm::BasicBlock* b = *sit; if(exists(cutPoints, b)) { if(!exists(s.exitCutPoints, b)) { s.exitCutPoints.push_back(b); } std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(b, nameValueMap); s.assertMapCPs[b] = nameValueMap; } else if(!bbVisited.at(b)) { stack.push_back(b); } } for (llvm::pred_iterator pit = pred_begin(sbb), pet = pred_end(sbb); pit != pet; ++pit) { llvm::BasicBlock* b = *pit; if(exists(cutPoints, b)) { if(!exists(s.entryCutPoints, b)) { s.entryCutPoints.push_back(b); } std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(b, nameValueMap); s.assuMapCPs[b] = nameValueMap; } else if(!bbVisited.at(b)) { stack.push_back(b); } } } } if(!s.bodyBlocks.empty()) { segVec.push_back(s); } } } } } void buildBlockMap(llvm::BasicBlock* bb, std::map<std::string, llvm::Value*>& nameValueMap) { for (llvm::Instruction &II : *bb){ llvm::Instruction* I = &II; llvm::Value* var = NULL; llvm::MDNode* md = NULL; std::string str; if( llvm::DbgDeclareInst* dDecl = llvm::dyn_cast<llvm::DbgDeclareInst>(I) ) { var = dDecl->getAddress(); md = dDecl->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); } else if( llvm::DbgValueInst* dVal = llvm::dyn_cast<llvm::DbgValueInst>(I)) { var = dVal->getValue(); md = dVal->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); } if( var ) { nameValueMap[str] = var; } } } int readInt( const llvm::ConstantInt* c ) { const llvm::APInt& n = c->getUniqueInteger(); unsigned len = n.getNumWords(); if( len > 1 ) tiler_error("llvmUtils", "long integers not supported!!" ); const uint64_t *v = n.getRawData(); return *v; } // Remove a loop bool deleteLoop(llvm::Loop *L, llvm::DominatorTree &DT, llvm::ScalarEvolution &SE, llvm::LoopInfo &LI) { llvm::SmallPtrSet<llvm::BasicBlock *, 8> blocks; blocks.insert(L->block_begin(), L->block_end()); llvm::BasicBlock *preheader = L->getLoopPreheader(); if (!preheader) return false; llvm::SmallVector<llvm::BasicBlock *, 4> exitingBlocks; L->getExitingBlocks(exitingBlocks); llvm::SmallVector<llvm::BasicBlock *, 4> exitBlocks; L->getUniqueExitBlocks(exitBlocks); // Single exit block to branch to if (exitBlocks.size() != 1) return false; // Tell ScalarEvolution that the loop is deleted SE.forgetLoop(L); // Connect the preheader directly to the exit block llvm::TerminatorInst *TI = preheader->getTerminator(); // llvm::Instruction *TI = preheader->getTerminator(); // LLVM 8 assert(TI && TI->isTerminator()); llvm::BasicBlock *exitBlock = exitBlocks[0]; TI->replaceUsesOfWith(L->getHeader(), exitBlock); // Rewrite phis in the exit block to get their inputs from // the preheader instead of the exiting block llvm::BasicBlock *exitingBlock = exitingBlocks[0]; llvm::BasicBlock::iterator BI = exitBlock->begin(); while (llvm::PHINode *P = llvm::dyn_cast<llvm::PHINode>(BI)) { int j = P->getBasicBlockIndex(exitingBlock); assert(j >= 0 && "Can't find exiting block in exit block's phi node!"); P->setIncomingBlock(j, preheader); for (unsigned i = 1; i < exitingBlocks.size(); ++i) P->removeIncomingValue(exitingBlocks[i]); ++BI; } std::cout << "Updated the Phi nodes of the exit block\n"; // Update the dominator tree // Remove blocks that will be deleted from the reference counting scheme llvm::SmallVector<llvm::DomTreeNode*, 8> ChildNodes; for (llvm::Loop::block_iterator LBI = L->block_begin(), LE = L->block_end(); LBI != LE; ++LBI) { // Move all of the block's children to be children of the preheader in DT // Remove DT entry for the block ChildNodes.insert(ChildNodes.begin(), DT[*LBI]->begin(), DT[*LBI]->end()); for (llvm::DomTreeNode *ChildNode : ChildNodes) { DT.changeImmediateDominator(ChildNode, DT[preheader]); } ChildNodes.clear(); DT.eraseNode(*LBI); // Remove the block from the reference counting (*LBI)->dropAllReferences(); } // std::cout << "Erase the blocks from the loop"; for (llvm::BasicBlock *BB : blocks) BB->eraseFromParent(); // Remove the blocks from loopinfo for (llvm::BasicBlock *BB : blocks) LI.removeBlock(BB); // Update LoopInfo // #ifndef LLVM_SVN // LI.markAsRemoved(L); // #endif return true; } //todo: streamline getLoc and getLocation src_loc getLoc( const llvm::Instruction* I ) { if( auto dbg = llvm::dyn_cast<llvm::DbgInfoIntrinsic>(I) ) { // if( auto dbg = llvm::dyn_cast<llvm::DbgVariableIntrinsic>(dbgi) ) { auto loc = dbg->getVariableLocation(); if( auto I_val = llvm::dyn_cast<llvm::Instruction>(loc) ) { if( I_val ) I = I_val; }else if( llvm::dyn_cast<llvm::Constant>(loc) ) { // what to do?? } else { tiler_error("llvmUtils", "Unknown type"); } // } else { // tiler_error("llvmUtils", "Not handled type of Info Intrinsic Inst"); // } } const llvm::DebugLoc d = I->getDebugLoc(); if( d ) { unsigned l = d.getLine(); unsigned c = d.getCol(); std::string f =llvm::cast<llvm::DIScope>(d.getScope())->getFilename(); return src_loc(l,c,f); } return src_loc(); } std::string getLocation(const llvm::Instruction* I ) { const llvm::DebugLoc d = I->getDebugLoc(); if( d ) { unsigned line = d.getLine(); unsigned col = d.getCol(); auto *Scope = llvm::cast<llvm::DIScope>(d.getScope()); std::string fname = Scope->getFilename(); std::string l_name = fname + ":" + std::to_string(line) + ":" + std::to_string(col); return l_name; }else{ return ""; } } std::string getLocation(const llvm::BasicBlock* b ) { auto I = b->getFirstNonPHIOrDbg(); return getLocation(I); } std::string getLocRange(const llvm::BasicBlock* b ) { unsigned minLine = std::numeric_limits<unsigned>::max(); unsigned minCol = std::numeric_limits<unsigned>::max(); unsigned maxLine = 0; unsigned maxCol = 0; std::string fname = ""; for( const llvm::Instruction& Iobj : b->getInstList() ) { const llvm::Instruction* I = &(Iobj); const llvm::DebugLoc d = I->getDebugLoc(); if( d ) { unsigned line = d.getLine(); unsigned col = d.getCol(); auto *Scope = llvm::cast<llvm::DIScope>(d.getScope()); if( fname.empty() ) fname = Scope->getFilename(); if( line < minLine ) { minLine = line; minCol = col; }else if( line == minLine ) { if( col < minCol ) minCol = col; } if( line > maxLine ) { maxLine = line; maxCol = col; }else if( line == maxLine ) { if( col > maxCol ) maxCol = col; } } } std::string l_name = fname + ":" + std::to_string(minLine) + ":"+ std::to_string(minCol) + "-" + std::to_string(maxLine) + ":"+ std::to_string(maxCol); return l_name; } z3::sort llvm_to_z3_sort( z3::context& c, llvm::Type* t ) { if( t->isIntegerTy() ) { if( t->isIntegerTy( 16 ) ) return c.int_sort(); if( t->isIntegerTy( 32 ) ) return c.int_sort(); if( t->isIntegerTy( 64 ) ) return c.int_sort(); if( t->isIntegerTy( 8 ) ) return c.bool_sort(); if( t->isIntegerTy( 1 ) ) return c.bool_sort(); } if( t->isArrayTy() ) { llvm::Type* te = t->getArrayElementType(); z3::sort z_te = llvm_to_z3_sort(c, te); return c.array_sort( c.int_sort(), z_te ); } if( t->isFloatTy() ) { return c.real_sort(); } tiler_error("llvmUtils", "only int and bool sorts are supported"); // return c.bv_sort(32); // needs to be added // return c.bv_sort(16); // return c.bv_sort(64); // return c.bool_sort(); // return c.real_sort(); return c.int_sort(); // dummy return } z3::expr read_const( const llvm::Value* op, z3::context& ctx ) { assert( op ); if( const llvm::ConstantInt* c = llvm::dyn_cast<llvm::ConstantInt>(op) ) { unsigned bw = c->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { int i = readInt( c ); return ctx.int_val(i); }else if(bw == 1 || bw == 8) { int i = readInt( c ); assert( i == 0 || i == 1 ); if( i == 1 ) return ctx.bool_val(true); else return ctx.bool_val(false); }else tiler_error("llvmUtils", "unrecognized constant!" ); }else if( llvm::isa<llvm::ConstantPointerNull>(op) ) { tiler_error("llvmUtils", "Constant pointer are not implemented!!" ); // }else if( LLCAST( llvm::ConstantPointerNull, c, op) ) { return ctx.int_val(0); }else if( llvm::isa<llvm::UndefValue>(op) ) { llvm::Type* ty = op->getType(); if( auto i_ty = llvm::dyn_cast<llvm::IntegerType>(ty) ) { int bw = i_ty->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { return get_fresh_int(ctx); }else if( bw == 1 ) { return get_fresh_bool(ctx); } } tiler_error("llvmUtils", "unsupported type: "<< ty << "!!"); }else if(const llvm::ConstantFP* c = llvm::dyn_cast<llvm::ConstantFP>(op) ) { const llvm::APFloat& n = c->getValueAPF(); double v = n.convertToDouble(); return ctx.real_val(std::to_string(v).c_str()); //tiler_error("llvmUtils", "Floating point constant not implemented!!" ); }else if( llvm::isa<llvm::Constant>(op) ) { tiler_error("llvmUtils", "non int constants are not implemented!!" ); std::cerr << "un recognized constant!"; // // int i = readInt(c); // // return eHandler->mkIntVal( i ); }else if( llvm::isa<llvm::ConstantExpr>(op) ) { tiler_error("llvmUtils", "case for constant not implemented!!" ); }else if( llvm::isa<llvm::ConstantArray>(op) ) { // const llvm::ArrayType* n = c->getType(); // unsigned len = n->getNumElements(); //return ctx.arraysort(); tiler_error("llvmUtils", "case for constant not implemented!!" ); }else if( llvm::isa<llvm::ConstantStruct>(op) ) { // const llvm::StructType* n = c->getType(); tiler_error("llvmUtils", "case for constant not implemented!!" ); }else if( llvm::isa<llvm::ConstantVector>(op) ) { // const llvm::VectorType* n = c->getType(); tiler_error("llvmUtils", "vector constant not implemented!!" ); } z3::expr e(ctx); return e; // contains no expression; } std::vector<llvm::BasicBlock*> to_std_vec(llvm::SmallVector<llvm::BasicBlock*, 20>& bb_sv) { std::vector<llvm::BasicBlock*> bb_stdv; for(bb* b : bb_sv) { bb_stdv.push_back(b); } return bb_stdv; } llvm::SmallVector<llvm::BasicBlock*, 40> to_small_vec(std::vector<llvm::BasicBlock*>& bb_vec) { llvm::SmallVector<llvm::BasicBlock*, 40> bb_sv; for(bb* b : bb_vec) { bb_sv.push_back(b); } return bb_sv; } bool cmp_loop_by_line_num (llvm::Loop* l1, llvm::Loop* l2) { assert(l1); assert(l2); const llvm::DebugLoc d1 = l1->getStartLoc(); const llvm::DebugLoc d2 = l2->getStartLoc(); if(d1.getLine() < d2.getLine()) { return true; } else { return false; } } void remove_loop_back_edge (llvm::Loop* L) { bb* exit_block = NULL; bb* header = L->getHeader(); bb* latch = L->getLoopLatch(); llvm::Instruction* term = latch->getTerminator(); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(term)) { const int NumS = bi->getNumSuccessors(); for(int i=0; i<NumS; i++) { bb* s = bi->getSuccessor(i); if(s != header) { exit_block = s; } } // Remove the conditional branch and add a unconditional branch llvm::IRBuilder<> b(term); b.CreateBr(exit_block); llvm::Value *loopCond = bi->getCondition(); bi->eraseFromParent(); if( auto icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) { icmp->eraseFromParent(); } } /* // Doing this generates bmc formula where the // needed path gets sliced off for(int i=0; i<NumS; i++) { bb* s = bi->getSuccessor(i); if(s == header) { bi->setSuccessor(i, exit_block); } } */ } void populate_arr_rd_wr(llvm::BasicBlock* bb, std::map<llvm::Value*, std::list<llvm::Value*>>& arrRead, std::map<llvm::Value*, std::list<llvm::Value*>>& arrWrite) { arrRead.clear(); arrWrite.clear(); for( auto it = bb->begin(), e = bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto store = llvm::dyn_cast<llvm::StoreInst>(I) ) { auto addr = store->getOperand(1); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { auto arry = elemPtr->getPointerOperand(); arrWrite[arry].push_back(store); } else {} // Do nothing } else if( auto load = llvm::dyn_cast<llvm::LoadInst>(I) ) { auto addr = load->getOperand(0); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if(auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { auto arry = elemPtr->getPointerOperand(); arrRead[arry].push_back(load); } else{} // Do nothing } else {} // Do nothing for inst other than store and load } } // Following function is taken from the llvm class lib/Transform/Scalar/LoopInterchange // We require that the PHINode must be only of the integer type. llvm::PHINode* getInductionVariable(llvm::Loop *L, llvm::ScalarEvolution *SE) { llvm::PHINode* InnerIndexVar = L->getCanonicalInductionVariable(); if (InnerIndexVar) return InnerIndexVar; if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) return nullptr; for (llvm::BasicBlock::iterator I = L->getHeader()->begin(); llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *PhiVar = llvm::cast<llvm::PHINode>(I); llvm::Type *PhiTy = PhiVar->getType(); if (!PhiTy->isIntegerTy()) return nullptr; const llvm::SCEVAddRecExpr *AddRec = llvm::dyn_cast<llvm::SCEVAddRecExpr>(SE->getSCEV(PhiVar)); if (!AddRec || !AddRec->isAffine()) continue; const llvm::SCEV *Step = AddRec->getStepRecurrence(*SE); if (!llvm::isa<llvm::SCEVConstant>(Step)) continue; // Found the induction variable. // FIXME: Handle loops with more than one induction variable. Note that, // currently, legality makes sure we have only one induction variable. return PhiVar; } return nullptr; } llvm::Value* find_ind_param_N(std::unique_ptr<llvm::Module>& module, llvm::Function* f, llvm::BasicBlock* entry_bb) { llvm::Value* N = NULL; bool checkAssignment = false; if(f->arg_size() == 1 ) { // Use the only param to the function as the program parameter N = &(*f->arg_begin()); } else if(!module->global_empty()) { // Use the only global variable as the program parameter int glbCntr = 0; for( auto iter_glb= module->global_begin(),end_glb = module->global_end(); iter_glb != end_glb; ++iter_glb ) { glbCntr ++; N = &*iter_glb; //3.8 } // if(glbCntr != 1) // tiler_error("llvmUtils", "Unable to find the program variable N for induction"); checkAssignment = true; } else { for( auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto alloc = llvm::dyn_cast<llvm::AllocaInst>(I) ) { if(alloc->isStaticAlloca()) continue; if( auto zext = llvm::dyn_cast<llvm::ZExtInst>(alloc->getArraySize()) ) { if(llvm::isa<llvm::BinaryOperator>(zext->getOperand(0)) ) break; N = zext->getOperand(0); checkAssignment=true; break; } } } } if(N == NULL) { tiler_error("llvmUtils", "Unable to find a program variable to induct on"); } // If N is not a function parameter check that there is only one non-det assignment // to N in the first block of the program. // Otherwise, report error due to inability to find the full-program induction vairable. if(checkAssignment) { int storeToNCntr = 0; for( auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto store = llvm::dyn_cast<llvm::StoreInst>(I) ) { if(N == store->getOperand(1)) { if( auto call = llvm::dyn_cast<llvm::CallInst>(store->getOperand(0)) ) { llvm::Function* fp = call->getCalledFunction(); if( fp != NULL && fp->getName().startswith("__VERIFIER_nondet_") ) { storeToNCntr++; } } } } } if(storeToNCntr > 1) tiler_error("llvmUtils", "Unable to find the program variable N for induction"); int intermediateCnt = storeToNCntr; for( auto bbit = f->begin(), end = f->end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); if(bb == entry_bb) continue; for( auto it = bb->begin(), e = bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto store = llvm::dyn_cast<llvm::StoreInst>(I) ) { if(N == store->getOperand(1)) storeToNCntr++; } } } if(intermediateCnt != storeToNCntr) tiler_error("llvmUtils", "Unable to find the program variable N for induction"); } return N; } bool check_conditional_in_loopbody(llvm::Loop *L) { for( auto b: L->getBlocks() ) { if(b == L->getLoopLatch()) continue; for( auto it = b->begin(), e = b->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(I)) { if(bi->isUnconditional()) continue; if( llvm::isa<llvm::ICmpInst>(bi->getCondition()) ) { return true; } else {} } else {} } } return false; } // Pass p must declare it requires LoopInfoWrapperPass void check_conditional_in_loopbody(llvm::Pass* p, llvm::Value* N, int& unsupported) { auto &LIWP = p->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); for (auto I = LI->rbegin(), E = LI->rend(); I != E; ++I) { llvm::Loop *L = *I; for( auto b: L->getBlocks() ) { if(b == L->getLoopLatch()) continue; for( auto it = b->begin(), e = b->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(I)) { if(bi->isUnconditional()) continue; if( auto icmp = llvm::dyn_cast<llvm::ICmpInst>(bi->getCondition()) ) { if(isValueInSubExpr(N, icmp->getOperand( 0 ))) unsupported = 2; if(isValueInSubExpr(N, icmp->getOperand( 1 ))) unsupported = 2; } else { tiler_error("llvmUtils", "Non integer comparision is currently not supported"); } } else {} } } } } void check_indu_param_in_index(llvm::Function *f, llvm::Value* N, int& unsupported) { for( auto bbit = f->begin(), end = f->end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); for( llvm::Instruction& Iobj : bb->getInstList() ) { llvm::Instruction* I = &(Iobj); if( auto load = llvm::dyn_cast<llvm::LoadInst>(I) ) { auto addr = load->getOperand(0); if(auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); if(isValueInSubExpr(N, idx)) unsupported = 3; } } } } } bool checkDependence(llvm::Value* expr, llvm::Value* val) { if(val == expr) return true; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = checkDependence(bop->getOperand(0), val); if(res) return true; return checkDependence(bop->getOperand(1), val); } else if(llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(expr)) { bool res = checkDependence(icmp->getOperand(0), val); if(res) return true; return checkDependence(icmp->getOperand(1), val); } else if( llvm::isa<llvm::CallInst>(expr) ) { // In general, need to check the parameters of the call I think return false; } else if( auto gep = llvm::dyn_cast<llvm::GetElementPtrInst>(expr) ) { return checkDependence(gep->getOperand(1), val); } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return checkDependence(load->getOperand(0), val); } else if(auto store = llvm::dyn_cast<llvm::StoreInst>(expr) ) { bool res = checkDependence(store->getOperand(0), val); if(res) return true; return checkDependence(store->getOperand(1), val); } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { checkDependence(cast->getOperand(0), val); } else if( llvm::isa<llvm::AllocaInst>(expr) ) { return false; } else { return false; } } llvm::Instruction* cloneExpr(llvm::Instruction* expr, llvm::Instruction* insert_pos, llvm::Instruction* skip, llvm::Instruction* phi) { if(expr == skip) return NULL; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr)) { auto* bopcl = bop->clone(); bopcl->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* op1 = llvm::dyn_cast<llvm::Instruction>(bopcl->getOperand(0))) { auto* clOp1 = cloneExpr(op1, bopcl, skip, phi); if(clOp1 != NULL) VMap[op1] = clOp1; } if(llvm::Instruction* op2 = llvm::dyn_cast<llvm::Instruction>(bopcl->getOperand(1))) { auto* clOp2 = cloneExpr(op2, bopcl, skip, phi); if(clOp2 != NULL) VMap[op2] = clOp2; } llvm::RemapInstruction(bopcl, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return bopcl; } else if(auto gep = llvm::dyn_cast<llvm::GetElementPtrInst>(expr)) { auto* g = gep ->clone(); g->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* idx1 = llvm::dyn_cast<llvm::Instruction>(gep->getOperand(1))) { llvm::Instruction* clIdx1 = cloneExpr(idx1, g, skip, phi); if(clIdx1 != NULL) VMap[idx1] = clIdx1; } if(gep->getNumIndices() == 2) { if(llvm::Instruction* idx2 = llvm::dyn_cast<llvm::Instruction>(gep->getOperand(2))) { llvm::Instruction* clIdx2 = cloneExpr(idx2, g, skip, phi); if(clIdx2 != NULL) VMap[idx2] = clIdx2; } } llvm::RemapInstruction(g, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return g; } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { auto* l = load->clone(); l->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* op = llvm::dyn_cast<llvm::Instruction>(l->getOperand(0))) { llvm::Instruction* v = cloneExpr(op, l, skip, phi); if(v != NULL) VMap[op] = v; } llvm::RemapInstruction(l, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return l; } else if(auto cast = llvm::dyn_cast<llvm::CastInst>(expr)) { auto* c = cast->clone(); c->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* op = llvm::cast<llvm::Instruction>(c->getOperand(0))) { auto* v = cloneExpr(op, c, skip, phi); if(v != NULL) VMap[op] = v; } llvm::RemapInstruction(c, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return c; } else if(llvm::isa<llvm::PHINode>(expr)) { return phi; // tiler_error("Cloning", "Cloning a PHI node is a very very tricky thing!"); } else if(llvm::isa<llvm::CallInst>(expr)) { // Parameters to be cloned ? tiler_error("Cloning", "Call Instruciton currently not supported as a sub-expression"); } else if(llvm::isa<llvm::StoreInst>(expr)) { tiler_error("Cloning", "Store cannot be a part of the sub-expression"); } else if(llvm::isa<llvm::AllocaInst>(expr)) { return NULL; // Dont clone or remap } else if(llvm::isa<const llvm::GlobalVariable>(expr)) { return NULL; // Dont clone or remap } else { tiler_error("Cloning", "Case undefined for this expression"); } return NULL; } void eraseExpr(llvm::Instruction* expr, llvm::Instruction* skip) { if(expr == NULL) return; if(expr == skip) return; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr)) { auto op0 = bop->getOperand(0); auto op1 = bop->getOperand(1); bop->eraseFromParent(); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); if(auto op1Inst = llvm::dyn_cast<llvm::Instruction>(op1)) eraseExpr(op1Inst, skip); } else if(auto gep = llvm::dyn_cast<llvm::GetElementPtrInst>(expr)) { auto idx = gep->getOperand(1); if(gep->getNumIndices() == 2) idx = gep->getOperand(2); gep->eraseFromParent(); if(auto idxInst = llvm::dyn_cast<llvm::Instruction>(idx)) eraseExpr(idxInst, skip); } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { auto op0 = load->getOperand(0); load->eraseFromParent(); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); } else if(auto cast = llvm::dyn_cast<llvm::CastInst>(expr)) { auto op0 = cast->getOperand(0); cast->eraseFromParent(); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); } else if(llvm::isa<llvm::PHINode>(expr)) { // Don't erase //tiler_error("Erasing", "Erasing a PHI node is a very bad idea!"); } else if(llvm::isa<llvm::CallInst>(expr)) { tiler_error("Erasing", "Erasing call Instrucitons currently not supported"); } else if(auto store = llvm::dyn_cast<llvm::StoreInst>(expr)) { auto op0 = store->getOperand(0); auto op1 = store->getOperand(1); store->eraseFromParent(); if(auto op1Inst = llvm::dyn_cast<llvm::Instruction>(op1)) eraseExpr(op1Inst, skip); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); } else if(llvm::isa<llvm::AllocaInst>(expr)) { // Don't erase } else if(llvm::isa<const llvm::GlobalVariable>(expr)) { // Don't erase } else { tiler_error("Erasing", "Erasing undefined for the given expression"); } } /// Following function is inspired from lib/Transforms/Utils/LoopUnrollPeel.cpp /// /// \brief Clones the body of the loop L, putting it between \p InsertTop and \p /// InsertBot. FinalBot is the block to totally exit from all iterations. /// \param IterNumber The serial number of the iteration currently being /// peeled off. /// \param[out] NewBlocks A list of the the blocks in the newly created clone. /// \param[out] VMap The value map between the loop and the new clone. /// \param LoopBlocks A helper for DFS-traversal of the loop. /// \param LVMap A value-map that maps instructions from the original loop to /// instructions in the last peeled-off iteration. void cloneLoopBlocksAtEnd(llvm::Loop *L, unsigned IterNumber, llvm::BasicBlock *InsertTop, llvm::BasicBlock *InsertBot, llvm::BasicBlock *FinalBot, llvm::SmallVectorImpl<llvm::BasicBlock *> &NewBlocks, llvm::LoopBlocksDFS &LoopBlocks, llvm::ValueToValueMapTy &VMap, llvm::ValueToValueMapTy &LVMap, llvm::DominatorTree *DT, llvm::LoopInfo *LI) { llvm::BasicBlock *Header = L->getHeader(); llvm::BasicBlock *Latch = L->getLoopLatch(); llvm::Function *F = Header->getParent(); llvm::LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); llvm::LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); llvm::Loop *ParentLoop = L->getParentLoop(); /* llvm::BasicBlock *PreHeader = L->getLoopPreheader(); llvm::errs() << "\nPreHeader Block\n\n"; PreHeader->print( llvm::errs() ); llvm::errs() << "\nTop Anchor\n\n"; InsertTop->print( llvm::errs() ); */ // For each block in the original loop, create a new copy, // and update the value map with the newly created values. for (llvm::LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { llvm::BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); NewBlocks.push_back(NewBB); if (ParentLoop) ParentLoop->addBasicBlockToLoop(NewBB, *LI); VMap[*BB] = NewBB; // If dominator tree is available, insert nodes to represent cloned blocks. if (DT) { if (Header == *BB) DT->addNewBlock(NewBB, InsertTop); else { llvm::DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); // VMap must contain entry for IDom, as the iteration order is RPO. DT->addNewBlock(NewBB, llvm::cast<llvm::BasicBlock>(VMap[IDom->getBlock()])); } } /* llvm::errs() << "\n\n"; llvm::cast<llvm::BasicBlock>(*BB)->print( llvm::errs() ); llvm::errs() << "\n\n"; NewBB->print( llvm::errs() ); llvm::errs() << "\n\n"; */ } /* llvm::errs() << "\nBottom Anchor\n"; InsertBot->print( llvm::errs() ); llvm::errs() << "\nFinal Exit\n"; FinalBot->print( llvm::errs() ); */ // Hook-up the control flow for the newly inserted blocks. // The new header is hooked up directly to the "newexit", which is either // the original loop exit (for the first iteration) or the previous // iteration's exit block (for every other iteration) InsertTop->getTerminator()->setSuccessor(0, llvm::cast<llvm::BasicBlock>(VMap[Header])); // Similarly, for the latch: // The original exiting edge is still hooked up to the loop exit. // The backedge now goes to the "newexittop", which is either the copied exit // of the loop (for the last peeled iteration) or the copied exit of the next // iteration (for every other iteration) llvm::BasicBlock *NewLatch = llvm::cast<llvm::BasicBlock>(VMap[Latch]); llvm::BranchInst *NewLatchBR = llvm::cast<llvm::BranchInst>(NewLatch->getTerminator()); // llvm::errs() << "\nBranch Inst in Latch before setting successor\n"; // NewLatchBR->print( llvm::errs() ); unsigned HeaderIdx = (NewLatchBR->getSuccessor(0) == Header ? 0 : 1); NewLatchBR->setSuccessor(HeaderIdx, InsertBot); NewLatchBR->setSuccessor(1 - HeaderIdx, FinalBot); if (DT) DT->changeImmediateDominator(InsertBot, NewLatch); // llvm::errs() << "\nBranch Inst in Latch after setting successor\n"; // NewLatchBR->print( llvm::errs() ); // The new copy of the loop body starts with a bunch of PHI nodes // that pick an incoming value from the previous loop iteration. // Since this copy is no longer part of the loop, we resolve this statically: // For the first iteration, we use the value from the latch of the loop. // For any other iteration, we replace the phi with the value generated by // the immediately preceding clone of the loop body (which represents // the previous iteration). llvm::BasicBlock::iterator I = Header->begin(); for ( ; llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *NewPHI = llvm::cast<llvm::PHINode>(VMap[&*I]); llvm::Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); llvm::Instruction *LatchInst = llvm::dyn_cast<llvm::Instruction>(LatchVal); if (IterNumber == 0) { VMap[&*I] = LatchVal; // To be mapped to NS later } else { VMap[&*I] = LVMap[LatchInst]; // To be mapped to NS later } llvm::cast<llvm::BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); } // Fix up the outgoing values - we need to add a value for the iteration // we've just created. Note that this must happen *after* the incoming // values are adjusted, since the value going out of the latch may also be // a value coming into the header. for (llvm::BasicBlock::iterator I = FinalBot->begin(); llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *PHI = llvm::cast<llvm::PHINode>(I); llvm::Value *LatchVal = PHI->getIncomingValueForBlock(Latch); llvm::Instruction *LatchInst = llvm::dyn_cast<llvm::Instruction>(LatchVal); if (LatchInst && L->contains(LatchInst)) LatchVal = VMap[LatchVal]; PHI->addIncoming(LatchVal, llvm::cast<llvm::BasicBlock>(VMap[Latch])); } // LastValueMap is updated with the values for the current loop // which are used the next time this function is called. for (const auto &KV : VMap) LVMap[KV.first] = KV.second; } /// Following function is inspired from lib/Transforms/Utils/LoopUnrollPeel.cpp /// /// \brief Peel off the last \p PeelCount iterations of loop \p L. /// /// Note that this does not peel them off as a single straight-line block. /// Rather, each iteration is peeled off separately, and needs to check the /// exit condition. bool myPeelLoop(llvm::Loop *L, unsigned PeelCount, llvm::LoopInfo *LI, llvm::ScalarEvolution *SE, llvm::DominatorTree *DT, llvm::AssumptionCache *AC, bool PreserveLCSSA, llvm::Value *N, llvm::Value *NS, llvm::Value *exitVal, int stepCnt, llvm::ValueToValueMapTy &LVMap, std::vector<llvm::BasicBlock*>& peeledBlocks) { // Only peeling single iteration is currently supported specifically for Advanced FPI if(PeelCount != 1) return false; // Make sure the loop is in simplified form if (!L->isLoopSimplifyForm()) return false; // Only peel loops that contain a single exit if (!L->getExitingBlock() || !L->getUniqueExitBlock()) return false; // Don't try to peel loops where the latch is not the exiting block. // This can be an indication of two different things: // 1) The loop is not rotated. // 2) The loop contains irreducible control flow that involves the latch. if (L->getLoopLatch() != L->getExitingBlock()) return false; llvm::LoopBlocksDFS LoopBlocks(L); LoopBlocks.perform(LI); llvm::BasicBlock *Header = L->getHeader(); llvm::BasicBlock *Latch = L->getLoopLatch(); llvm::BasicBlock *Exit = L->getUniqueExitBlock(); llvm::BranchInst *ExitBR = llvm::cast<llvm::BranchInst>(Exit->getTerminator()); llvm::BasicBlock *ExitSucc = ExitBR->getSuccessor(0); llvm::Function *F = Header->getParent(); /* llvm::BasicBlock *PreHeader = L->getLoopPreheader(); llvm::errs() << "\n\nPreHeader Block\n\n"; PreHeader->print( llvm::errs() ); llvm::errs() << "\n\nHeader Block\n\n"; Header->print( llvm::errs() ); llvm::errs() << "\n\nLatch Block\n\n"; Latch->print( llvm::errs() ); llvm::errs() << "\n\nExit Block\n\n"; Exit->print( llvm::errs() ); llvm::errs() << "\n\nExit Succcessor Block\n\n"; ExitSucc->print( llvm::errs() ); */ // Set up all the necessary basic blocks. It is convenient to split the // Exit into 3 parts - two blocks to anchor the peeled copy of the loop // body, and the final exit to skip subsequent iterations. // Peeling the last iteration transforms. // // PreHeader: // ... // Header: // LoopBody // If (cond) goto Header // Exit: // // into // // PreHeader: // ... // Header: // LoopBody // If (cond') goto Header // Exit: // InsertTop: // LoopBody // If (!cond) goto FinalBot // InsertBot: // FinalBot: // // Each following iteration will split the current bottom anchor "bottom" // in two, and put the new copy of the loop body between these two blocks. // That is, after peeling another iteration from the example above, we'll split // InsertBot, and get: // // PreHeader: // ... // Header: // LoopBody // If (cond') goto Header // Exit: // InsertTop: // LoopBody // If (!cond) goto FinalBot // InsertBot: // LoopBody // If (!cond) goto FinalBot // InsertBot.next: // FinalBot: llvm::BasicBlock *InsertTop = llvm::SplitEdge(Exit, ExitSucc, DT, LI); llvm::BasicBlock *InsertBot = llvm::SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI); llvm::BasicBlock *FinalBot = llvm::SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); InsertTop->setName(Exit->getName() + ".peel.begin"); InsertBot->setName(Exit->getName() + ".peel.next"); FinalBot->setName(Exit->getName() + ".peel.final"); // Collect all the newly created blocks for future use llvm::SmallVector<llvm::BasicBlock *, 20> AllNewBlocks; AllNewBlocks.push_back(InsertTop); AllNewBlocks.push_back(InsertBot); AllNewBlocks.push_back(FinalBot); // For each peeled-off iteration, make a copy of the loop. for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { llvm::SmallVector<llvm::BasicBlock *, 8> NewBlocks; llvm::ValueToValueMapTy VMap; // Clone the blocks in the loop and attach them after the loop cloneLoopBlocksAtEnd(L, Iter, InsertTop, InsertBot, FinalBot, NewBlocks, LoopBlocks, VMap, LVMap, DT, LI); if(NewBlocks.empty()) tiler_error("Cloning", "List of cloned blocks is empty"); // Remap to use values from the current iteration instead of the loop // iteration. VMap populated in above function call of cloneLoopBlocksAtEnd. llvm::remapInstructionsInBlocks(NewBlocks, VMap); // Collect all the newly created blocks for future use for(llvm::BasicBlock* b : NewBlocks) AllNewBlocks.push_back(b); InsertTop = InsertBot; if(PeelCount > 1) { // Subsequent splits only if more iterations are to be peeled InsertBot = llvm::SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); InsertBot->setName(InsertTop->getName() + ".next"); AllNewBlocks.push_back(InsertBot); } else { /* llvm::BasicBlock *IBPred = InsertBot->getUniquePredecessor(); if(IBPred != NULL) { llvm::Instruction* term = IBPred->getTerminator(); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(term)) { if(bi->isConditional()) { // Remove the conditional branch and add a unconditional branch llvm::IRBuilder<> b(term); b.CreateBr(FinalBot); llvm::Value *loopCond = bi->getCondition(); bi->eraseFromParent(); if( auto icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) icmp->eraseFromParent(); // Detach the InsertBot Block InsertBot->getTerminator()->setSuccessor(0, NULL); } else {} } else {} } else {} auto position = std::find(AllNewBlocks.begin(), AllNewBlocks.end(), InsertBot); if (position != AllNewBlocks.end()) // == myVector.end() means the element was not found AllNewBlocks.erase(position); */ } // Attach the new cloned blocks in the basicblock list of the function F->getBasicBlockList().splice(InsertTop->getIterator(), F->getBasicBlockList(), NewBlocks[0]->getIterator(), F->end()); // Replace the loop counter in the peeled blocks with the approprite value llvm::PHINode *PHI = getInductionVariable(L, SE); llvm::Value *LatchVal = PHI->getIncomingValueForBlock(Latch); llvm::Instruction *LatchInst = llvm::dyn_cast<llvm::Instruction>(LatchVal); if (Iter > 0) { LatchVal = LVMap[LatchInst]; // To be mapped to NS later } llvm::ValueToValueMapTy VVMap; llvm::BranchInst *LatchBR = llvm::cast<llvm::BranchInst>(Latch->getTerminator()); if(!LatchBR) tiler_error("llvmUtils", "Latch block does not have unique term inst"); llvm::Value *loopCond = LatchBR->getCondition(); if( llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) { llvm::ValueToValueMapTy ExitVMap; if( PeelCount == 1 && llvm::isa<llvm::LoadInst>(exitVal) ) { llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(exitVal); if(N == load->getOperand(0)) VVMap[LatchVal] = NS; } else if (N == exitVal && PeelCount == 1) { VVMap[LatchVal] = NS; } else { llvm::ValueToValueMapTy::iterator I; I = LVMap.find(icmp); if (I == LVMap.end()) tiler_error("Cloning","Value not in map"); llvm::ICmpInst* clIcmp = llvm::dyn_cast<llvm::ICmpInst>(I->second); llvm::Instruction* clExitVal = llvm::dyn_cast<llvm::Instruction>(exitVal); if (L->contains(clExitVal->getParent())) { I = LVMap.find(exitVal); if (I == LVMap.end()) tiler_error("Cloning","Value not in map"); if((clExitVal = llvm::dyn_cast<llvm::Instruction>(I->second))) { } else { assert(clExitVal && "Clone of exit value is not a instruction"); } } llvm::Instruction* clExitValp = NULL; llvm::Type *constValTy = clExitVal->getType(); if(constValTy->isPointerTy()) constValTy = constValTy->getPointerElementType(); llvm::Value* constVal = llvm::ConstantInt::get(constValTy, PeelCount-Iter); if(stepCnt > 0) clExitValp = llvm::BinaryOperator::Create(llvm::Instruction::Sub, clExitVal, constVal, "NewBound.peel"); else clExitValp = llvm::BinaryOperator::Create(llvm::Instruction::Add, clExitVal, constVal, "NewBound.peel"); clExitValp->insertBefore(clIcmp); VVMap[LatchVal] = clExitValp; } } else {} llvm::remapInstructionsInBlocks(AllNewBlocks, VVMap); } // Change the loop terminating condition in accordance with the peel count llvm::BranchInst *LatchBR = llvm::cast<llvm::BranchInst>(Latch->getTerminator()); if(!LatchBR) tiler_error("llvmUtils", "Latch block does not have unique term inst"); llvm::Value *loopCond = LatchBR->getCondition(); if( llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) { llvm::ValueToValueMapTy ExitVMap; if( llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(exitVal) ) { if(N == load->getOperand(0)) ExitVMap[load] = NS; } else if (N == exitVal) { ExitVMap[N] = NS; } else { llvm::Type *constValTy = exitVal->getType(); if(constValTy->isPointerTy()) constValTy = constValTy->getPointerElementType(); llvm::Value* constVal = llvm::ConstantInt::get(constValTy, PeelCount); llvm::Instruction* exitValp = NULL; if(stepCnt > 0) exitValp = llvm::BinaryOperator::Create(llvm::Instruction::Sub, exitVal, constVal, "NewBound"); else exitValp = llvm::BinaryOperator::Create(llvm::Instruction::Add, exitVal, constVal, "NewBound"); exitValp->insertBefore(icmp); ExitVMap[exitVal] = exitValp; } llvm::RemapInstruction(icmp, ExitVMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); } else {} /* // Replace the loop counter in the peeled blocks with the approprite value // Multiple nodes will have to be mapped if PeelCount > 1 and not all such // nodes use the latch value but the value coming from the previous peel llvm::PHINode *PHI = getInductionVariable(L, SE); llvm::Value *LatchVal = PHI->getIncomingValueForBlock(Latch); llvm::ValueToValueMapTy VVMap; VVMap[LatchVal] = NS; // LatchVal will not work if PeelCount > 1 llvm::remapInstructionsInBlocks(AllNewBlocks, VVMap); */ // If the loop is nested, we changed the parent loop, update SE. if (llvm::Loop *ParentLoop = L->getParentLoop()) { SE->forgetLoop(ParentLoop); // FIXME: Incrementally update loop-simplify llvm::simplifyLoop(ParentLoop, DT, LI, SE, AC, PreserveLCSSA); } else { // FIXME: Incrementally update loop-simplify llvm::simplifyLoop(L, DT, LI, SE, AC, PreserveLCSSA); } // Collect all the newly created blocks for future use for(llvm::BasicBlock* b : AllNewBlocks) peeledBlocks.push_back(b); if(peeledBlocks.empty()) tiler_error("Cloning", "List of cloned blocks is empty"); return true; } // Following function is adapted from the llvm code since // llvm v 6.0 does not have this function in the LoopInfo.cpp llvm::BranchInst *getLoopGuardBR(llvm::Loop *L, bool isPeeled) { if (!L->isLoopSimplifyForm()) return NULL; llvm::BasicBlock *Preheader = L->getLoopPreheader(); assert(Preheader && L->getLoopLatch() && "Expecting a loop with valid preheader and latch"); // Loop should be in rotate form. // if (!L->isRotatedForm()) return NULL; // Above line commented since the call is not available in llvm v 6.0 // Disallow loops with more than one unique exit block, as we do not verify // that GuardOtherSucc post dominates all exit blocks. llvm::BasicBlock *ExitFromLatch = L->getUniqueExitBlock(); if (!ExitFromLatch) return NULL; llvm::BasicBlock *ExitFromLatchSucc = ExitFromLatch->getUniqueSuccessor(); if (!ExitFromLatchSucc) return NULL; llvm::BasicBlock *GuardBB = Preheader->getUniquePredecessor(); if (!GuardBB) return NULL; assert(GuardBB->getTerminator() && "Expecting valid guard terminator"); llvm::BranchInst *GuardBI = llvm::dyn_cast<llvm::BranchInst>(GuardBB->getTerminator()); if (!GuardBI || GuardBI->isUnconditional()) return NULL; llvm::BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader) ? GuardBI->getSuccessor(1) : GuardBI->getSuccessor(0); // The following condition will not hold when loops are peeled if(isPeeled) return GuardBI; else return (GuardOtherSucc == ExitFromLatchSucc) ? GuardBI : NULL; } llvm::Value* getSingularNRef(llvm::Value* N, llvm::BasicBlock* entry_bb) { if(N == NULL || entry_bb == NULL) return NULL; llvm::Value* SingularNRef = NULL; if(llvm::isa<llvm::GlobalVariable>(N)) { for(auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if(llvm::LoadInst *load = llvm::dyn_cast<llvm::LoadInst>(I) ) { if(N == load->getOperand(0)) { SingularNRef = load; break; } else {} } else {} } } else { SingularNRef = N; } if(SingularNRef == NULL) tiler_error("llvmUtils","Program Parameter is NULL"); return SingularNRef; } llvm::Instruction* generateNSVal(llvm::Value* N, llvm::Value* SingularNRef, llvm::BasicBlock* entry_bb) { if(N==NULL) return NULL; if(llvm::isa<llvm::GlobalVariable>(N)) { llvm::Type *oneTy = N->getType(); oneTy = oneTy->getPointerElementType(); llvm::Value *one = llvm::ConstantInt::get(oneTy, 1); if(SingularNRef == NULL) return NULL; llvm::LoadInst *Nload = llvm::dyn_cast<llvm::LoadInst>(SingularNRef); llvm::Instruction *NS = llvm::BinaryOperator::Create(llvm::Instruction::Sub, Nload, one, "NS"); NS->insertAfter(Nload); return NS; } else { if(entry_bb == NULL) return NULL; llvm::Type *oneTy = N->getType(); llvm::Value *one = llvm::ConstantInt::get(oneTy, 1); llvm::Instruction *NS = llvm::BinaryOperator::Create(llvm::Instruction::Sub, N, one, "NS"); NS->insertBefore(entry_bb->getFirstNonPHI()); return NS; } return NULL; } //---------------------------------------------------------------- // Cloning APIs llvm::BasicBlock* create_cloned_remapped_bb( const llvm::BasicBlock* basicBlock, const llvm::Twine& Name = "_aggr", llvm::Function* F = 0) { llvm::ValueToValueMapTy VMap; bb * clonedBB = llvm::CloneBasicBlock(basicBlock, VMap, Name, F); llvm::SmallVector<llvm::BasicBlock*,2> bbVec; bbVec.push_back(clonedBB); llvm::remapInstructionsInBlocks(bbVec, VMap); // remaps instructions return clonedBB; } // Pass p must declare it requires LoopInfoWrapperPass and // DominatorTreeWrapperPass std::vector<llvm::BasicBlock*> collect_cloned_loop_blocks(llvm::Pass *p, llvm::Loop *L, loopdata *ld) { if (!L->getExitingBlock() || !L->getUniqueExitBlock() || L->getLoopLatch() != L->getExitingBlock()) tiler_error("llvmUtils", "Loop does not have a unique exiting latch"); bb* preheader = L->getLoopPreheader(); bb* header = L->getHeader(); bb* latch = L->getLoopLatch(); bb* block_after_exit = NULL; llvm::Instruction* term = latch->getTerminator(); if(!term) tiler_error("llvmUtils", "Loop does not have unique term inst"); if (llvm::BranchInst *bi = llvm::dyn_cast<llvm::BranchInst>(term)) { const int NS = bi->getNumSuccessors(); for(int i=0; i<NS; i++) { bb* s = bi->getSuccessor(i); if(s != header) block_after_exit = s; } } else tiler_error("llvmUtils", "Cast of term inst to branch inst failed"); if(!block_after_exit) tiler_error("llvmUtils", "Block after the exiting loop not found"); llvm::ValueToValueMapTy VMap; auto &LIWP = p->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); auto &DTWP = p->getAnalysis<llvm::DominatorTreeWrapperPass>(); llvm::DominatorTree* DT = &DTWP.getDomTree(); llvm::SmallVector<llvm::BasicBlock *, 20> cloned_blocks; llvm::Loop* cl = cloneLoopWithPreheader(block_after_exit, preheader, L, VMap, "_clone", LI, DT, cloned_blocks); if(!cl) tiler_error("llvmUtils", "Unable to clone the preheader of the loop"); return to_std_vec(cloned_blocks); } llvm::AllocaInst* create_new_alloca(llvm::AllocaInst* arry_alloca) { llvm::IRBuilder<> alloca_builder(arry_alloca); llvm::AllocaInst* new_arry_alloca = alloca_builder.CreateAlloca(arry_alloca->getAllocatedType(), arry_alloca ->getArraySize()); return new_arry_alloca; } void remap_store(llvm::StoreInst* store, llvm::AllocaInst* arry_alloca, llvm::AllocaInst* new_arry_alloca) { auto addr = store->getOperand(1); llvm::BitCastInst* addr_bc = NULL; if( (addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr)) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { elemPtr->setOperand(0, new_arry_alloca); // llvm::ValueToValueMapTy VMap; // VMap[arry_alloca] = new_arry_alloca; /* auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); llvm::IRBuilder<> builder(elemPtr); llvm::GetElementPtrInst* new_elem_ptr = llvm::dyn_cast<llvm::GetElementPtrInst>(builder.CreateGEP(new_arry_alloca, idx)); elemPtr->removeFromParent(); */ } } void remap_load(llvm::LoadInst* load, llvm::AllocaInst* arry_alloca, llvm::AllocaInst* new_arry_alloca) { auto addr = load->getOperand(0); llvm::BitCastInst* addr_bc = NULL; if( (addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr)) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { elemPtr->setOperand(0, new_arry_alloca); /* llvm::ValueToValueMapTy VMap; VMap[arry_alloca] = new_arry_alloca; RemapInstruction(elemPtr, VMap); auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); llvm::IRBuilder<> builder(elemPtr); builder.CreateGEP(new_arry_alloca, idx); elemPtr->removeFromParent(); */ } } void add_equality_stmt(llvm::BasicBlock* bb, llvm::AllocaInst* prev_arry_alloca, llvm::AllocaInst* new_arry_alloca, llvm::LLVMContext& globalContext) { llvm::Instruction* term = bb->getTerminator(); if(!term) tiler_error("llvmUtils", "Preheader block does not have unique term inst"); llvm::IRBuilder<> b(term); llvm::Type *i32_ptr_type = llvm::IntegerType::getInt32PtrTy(globalContext); llvm::Value* constZero = llvm::ConstantInt::get(globalContext, llvm::APInt(64, 0, true)); llvm::GetElementPtrInst* prev_elem_ptr = llvm::dyn_cast<llvm::GetElementPtrInst>(b.CreateInBoundsGEP(prev_arry_alloca, constZero)); auto prev_elem_ptr_bc = b.CreateBitCast(prev_elem_ptr, i32_ptr_type); llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(b.CreateLoad(prev_elem_ptr_bc)); llvm::GetElementPtrInst* new_elem_ptr = llvm::dyn_cast<llvm::GetElementPtrInst>(b.CreateInBoundsGEP(new_arry_alloca, constZero)); auto new_elem_ptr_bc = b.CreateBitCast(new_elem_ptr, i32_ptr_type); b.CreateStore(load, new_elem_ptr_bc); } //---------------------------------------------------------------------- // value_expr_map void value_expr_map::insert_term_map( const llvm::Value* op, z3::expr e ) { auto it = versions.find(op); if( it == versions.end() ) { insert_term_map( op, 0, e ); }else{ insert_term_map( op, (it->second).back() + 1, e ); } } void value_expr_map::insert_term_map( const llvm::Value* op, unsigned c_count, z3::expr e ) { auto it = versions.find(op); if( it == versions.end() ) { // assert( c_count == 0 ); }else{ assert( (it->second).back() < c_count); } versions[op].push_back( c_count ); auto pair = std::make_pair( std::make_pair( op, c_count ), e ); vmap.insert( pair ); } //insert_new_def with 2 param is alias of get_term z3::expr value_expr_map::insert_new_def( const llvm::Value* op, unsigned c_count ) { return get_term( op, c_count ); } z3::expr value_expr_map::insert_new_def( const llvm::Value* op ) { unsigned count = versions.find(op) == versions.end() ? 0 : versions[op].back() + 1; return insert_new_def( op, count ); } z3::expr value_expr_map::get_term( const llvm::Value* op, std::string op_name ) { z3::expr c = read_constant( op ); if( c ) return c; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return get_term( op, 0, op_name ); }else{ return get_term(op, (it->second).back(), op_name ); } } z3::expr value_expr_map::get_term( const llvm::Value* op ) { z3::expr c = read_constant( op ); if( c ) return c; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return get_term( op, 0 ); }else{ return get_term(op, (it->second).back() ); } } z3::expr value_expr_map::get_term( const llvm::Value* op, unsigned c_count, std::string op_name ) { z3::expr e = read_term( op, c_count ); if( e ) return e; // create new name z3::expr name = create_fresh_name( op, op_name ); insert_term_map( op, c_count, name ); return name; } z3::expr value_expr_map::get_term( const llvm::Value* op, unsigned c_count ) { z3::expr e = read_term( op, c_count ); if( e ) return e; // create new name z3::expr name = create_fresh_name( op ); insert_term_map( op, c_count, name ); return name; } z3::expr value_expr_map::get_earlier_term( const llvm::Value* op, unsigned c_count ) { z3::expr c = read_constant( op ); if( c ) return c; auto it = versions.find(op); if( it != versions.end() ) { auto vs = it->second; unsigned i = vs.size(); while( i > 0 ) { i--; if( vs[i] <= c_count ) { c_count = vs[i]; break; } } return read_term( op, c_count); } tiler_error( "llvmUtils", "versions of an LLVM value not found !!"); } z3::expr value_expr_map::create_fresh_name( const llvm::Value* op, std::string op_name ) { llvm::Type* ty = op->getType(); if( auto i_ty = llvm::dyn_cast<llvm::IntegerType>(ty) ) { int bw = i_ty->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { z3::expr i = get_fresh_int(ctx, op_name, true); return i; }else if(bw == 1 || bw == 8) { z3::expr bit = get_fresh_bool(ctx, op_name, true); return bit; } } ty->print( llvm::errs() ); llvm::errs() << "\n"; tiler_error("llvmUtils", "unsupported type!!"); z3::expr e(ctx); return e; } z3::expr value_expr_map::create_fresh_name( const llvm::Value* op ) { llvm::Type* ty = op->getType(); if( auto i_ty = llvm::dyn_cast<llvm::IntegerType>(ty) ) { int bw = i_ty->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { z3::expr i = get_fresh_int(ctx, op->getName().str()); return i; }else if(bw == 1 || bw == 8) { z3::expr bit = get_fresh_bool(ctx, op->getName().str()); return bit; } } ty->print( llvm::errs() ); llvm::errs() << "\n"; tiler_error("llvmUtils", "unsupported type!!"); z3::expr e(ctx); return e; } z3::expr value_expr_map::read_term( const llvm::Value* op, unsigned c_count ) { auto it = vmap.find( {op,c_count} ); if( it != vmap.end() ) { return it->second; }else{ z3::expr e(ctx); return e; // contains no expression; } } z3::expr value_expr_map::read_constant( const llvm::Value* op ) { return read_const(op, ctx); } unsigned value_expr_map::get_max_version( const llvm::Value* op ) { z3::expr c = read_constant( op ); if( c ) return 0; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return 0; }else{ return (it->second).back(); } } const std::vector<unsigned>& value_expr_map::get_versions( const llvm::Value* op ) { z3::expr c = read_constant( op ); if( c ) return dummy_empty_versions; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return dummy_empty_versions; }else{ return (it->second); } } // todo: violates invaiant of the system of multiple copies void value_expr_map::copy_values(value_expr_map& m) { for(auto it = vmap.begin(); it != vmap.end(); ++it) { m.insert_term_map(it->first.first, it->first.second, it->second); } } void value_expr_map::print( std::ostream& o ) { for(auto it = vmap.begin(); it != vmap.end(); ++it) { const llvm::Value* I = it->first.first; unsigned version = it->first.second; z3::expr val = it->second; LLVM_DUMP(I); o << I << " " << version << "~~>" << val << "\n"; } } inline void value_expr_map::dump() { print( std::cout ); } std::list<z3::expr> value_expr_map::get_expr_list() { std::list<z3::expr> l; for(auto it = vmap.begin(); it != vmap.end(); ++it) { l.push_back(it->second); } return l; } //---------------------------------------------------------------------- char fun_clonner_mod_pass::ID = 0; fun_clonner_mod_pass:: fun_clonner_mod_pass(options& o_, std::string ns, std::map<llvm::Function*, std::string>& fn_h_map, std::map<std::string, llvm::ValueToValueMapTy>& fwd_v2v_map, std::map<llvm::Function*, std::map<const llvm::Value*, const llvm::Value*>>& rev_v2v_map, std::map<const bb*, std::pair<std::vector<std::string>, std::vector<std::string> > >& bb_cmt_map_, bool mk_tgt ) : llvm::ModulePass(ID) , o(o_) , fn_hash_map(fn_h_map) , fwd_fn_v2v_map(fwd_v2v_map) , rev_fn_v2v_map(rev_v2v_map) , bb_cmt_map(bb_cmt_map_) { name_suffix = ns; make_target = mk_tgt; } bool fun_clonner_mod_pass::runOnModule(llvm::Module &M) { llvm::Function *F = M.getFunction(o.funcName); if(!F) { tiler_error("Cloning", "Function under analysis not present in the module"); } std::string hash_str = random_string(); llvm::ValueToValueMapTy& VMap = fwd_fn_v2v_map[hash_str]; llvm::Function* C_F = llvm::CloneFunction(F, VMap); assert(C_F); /* // Copy all pairs from the the temporary vmap to the permanent one for (auto &KV : VMap) fwd_fn_v2v_map[C_F][KV.first] = KV.second; */ fn_hash_map[C_F] = hash_str; C_F->setName(F->getName().str() + name_suffix); if(make_target) { // Clone is the new function under analysis o.funcName = F->getName().str() + name_suffix; } else {} // Clone is not immediately under analysis create_alloca_map(F, VMap, rev_fn_v2v_map[C_F]); if(make_target) { adjust_bb_cmt_map(VMap); } else {} // Pointers to blocks with comments are not shifted return true; } void fun_clonner_mod_pass:: create_alloca_map(llvm::Function* F, llvm::ValueToValueMapTy& fn_vmap, std::map<const llvm::Value*, const llvm::Value*>& alloca_map) { std::set<llvm::AllocaInst*> arr_set; collect_arr(*F, arr_set); for(auto arr_alloc : arr_set) { llvm::Value* mapped_alloc = fn_vmap[arr_alloc]; alloca_map[mapped_alloc] = arr_alloc; // arr_alloc->print( llvm::outs() ); // mapped_alloc->print( llvm::outs() ); } } void fun_clonner_mod_pass:: adjust_bb_cmt_map(llvm::ValueToValueMapTy& fn_vmap) { std::map<const bb*, std::pair<std::vector<std::string>, std::vector<std::string> > > cmt_map; for(auto it = bb_cmt_map.begin(); it!= bb_cmt_map.end(); it++) { llvm::WeakTrackingVH &c_b = fn_vmap[it->first]; bb* clonedBB; if ((clonedBB = llvm::dyn_cast<llvm::BasicBlock>(c_b))) { cmt_map[clonedBB] = it->second; bb_cmt_map.erase(it->first); } else { tiler_error("llvmUtils", "Casting of the block failed"); } } assert(bb_cmt_map.empty()); bb_cmt_map.insert(cmt_map.begin(), cmt_map.end()); } std::string fun_clonner_mod_pass::random_string() { std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); std::random_device rd; std::mt19937 generator(rd()); std::shuffle(str.begin(), str.end(), generator); return str.substr(0, 32); } llvm::StringRef fun_clonner_mod_pass::getPassName() const { return "Create a clone of the function with given name. Attach the suffix \ to the name of clone. Make this name as the target function name."; } //---------------------------------------------------------------------- char preprocess::ID = 0; preprocess::preprocess(std::unique_ptr<llvm::Module>& m, options& o_) : llvm::FunctionPass(ID) , module(m) , o(o_) {} preprocess::~preprocess() {} bool preprocess::runOnFunction( llvm::Function &f ) { if(f.getName() != o.funcName) return false; target_f = &f; // Get entry block entry_bb = &target_f->getEntryBlock(); // Identify the program parameter, error if a suitable value is not found N = find_ind_param_N(module, target_f, entry_bb); assert(N); // Global N create multiple load instruction, we remove those // and map thier uses to the load instruction in the entry block if(llvm::isa<llvm::GlobalVariable>(N)) { remove_glb_N_loads(); remove_unwanted_assume(); } check_nesting_depth(); return true; } void preprocess::remove_glb_N_loads() { for( auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(I) ) { if(N == load->getOperand(0)) { N_load = load; } else {} } else {} } assert(N_load); if(N_load == NULL) tiler_error("preprocess", "First load of program parameter not found"); llvm::ValueToValueMapTy VMap; llvm::SmallVector<llvm::BasicBlock*, 20> blocks; llvm::SmallVector<llvm::LoadInst*, 20> removeLoads; for( auto& b : target_f->getBasicBlockList() ) { if( &b == entry_bb) continue; for( auto it = b.begin(), e = b.end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(I) ) { if(N == load->getOperand(0)) { VMap[load] = N_load; blocks.push_back(&b); removeLoads.push_back(load); } else {} } else {} } } llvm::remapInstructionsInBlocks(blocks, VMap); for(auto load : removeLoads) load->eraseFromParent(); } void preprocess::remove_unwanted_assume() { llvm::Value* SingularNRef = NULL; if(llvm::isa<llvm::GlobalVariable>(N)) SingularNRef = N_load; else SingularNRef = N; for( auto& b : target_f->getBasicBlockList() ) { for( auto it = b.begin(), e = b.end(); it != e; ++it) { llvm::Instruction *I = &(*it); if(llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(I)) { if( llvm::isa<llvm::IntrinsicInst>(call) ) continue; if( call->getNumArgOperands() <= 0 ) continue; if( is_assume_call(call) ) { auto op = llvm::dyn_cast<llvm::Instruction>(call->getArgOperand(0)); llvm::Instruction* cast1 = NULL; llvm::Instruction* cast2 = NULL; if( (cast1 = llvm::dyn_cast<llvm::CastInst>(op)) ) op = cast1; if(llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(op->getOperand(0))) { bool erase = false; if(llvm::isa<llvm::Constant>(icmp->getOperand(1))) { auto icmpop = llvm::dyn_cast<llvm::Instruction>(icmp->getOperand(0)); if( (cast2 = llvm::dyn_cast<llvm::CastInst>(icmpop)) ) icmpop = llvm::dyn_cast<llvm::Instruction>(cast2->getOperand(0)); if(icmpop == SingularNRef) erase = true; } if(llvm::isa<llvm::Constant>(icmp->getOperand(0))) { auto icmpop = llvm::dyn_cast<llvm::Instruction>(icmp->getOperand(1)); if( (cast2 = llvm::dyn_cast<llvm::CastInst>(icmpop)) ) icmpop = llvm::dyn_cast<llvm::Instruction>(cast2->getOperand(0)); if(icmpop == SingularNRef) erase = true; } if(erase) { call->eraseFromParent(); cast1->eraseFromParent(); icmp->eraseFromParent(); cast2->eraseFromParent(); return; } } else {} } else {} } else {} } } } void preprocess::check_nesting_depth() { llvm::LoopInfo &LI = getAnalysis<llvm::LoopInfoWrapperPass>().getLoopInfo(); for (auto L = LI.rbegin(), E = LI.rend(); L != E; ++L) { // llvm::Loop *Lp = *L; for (llvm::Loop *SL : (*L)->getSubLoops()) { for (llvm::Loop *SSL : SL->getSubLoops()) { if(SSL) tiler_error("Preprocess", "Nesting depth greater than 2 is not supported"); } } } } llvm::StringRef preprocess::getPassName() const { return "Identify the program parameter, check input program \ sanity, remove unnecessary stmts, and so on"; } void preprocess::getAnalysisUsage(llvm::AnalysisUsage &au) const { au.addRequired<llvm::LoopInfoWrapperPass>(); } //-------------------------------------------------------------------------- char count_loops::ID = 0; count_loops::count_loops(std::unique_ptr<llvm::Module>& m, options& o_) : llvm::FunctionPass(ID) , module(m) , o(o_) {} count_loops::~count_loops() {} bool count_loops::runOnFunction( llvm::Function &f ) { if(f.getName() != o.funcName) return false; llvm::LoopInfo &LI = getAnalysis<llvm::LoopInfoWrapperPass>().getLoopInfo(); for (auto L = LI.rbegin(), E = LI.rend(); L != E; ++L) loop_count++; return false; } llvm::StringRef count_loops::getPassName() const { return "Counts the number of top level loops in the program"; } void count_loops::getAnalysisUsage(llvm::AnalysisUsage &au) const { au.addRequired<llvm::LoopInfoWrapperPass>(); } //-------------------------------------------------------------------------- void merge_mono( const llvm_mono& m1, const llvm_mono& m2, llvm_mono& m ) { auto it1 = m1.begin(); auto it2 = m2.begin(); while( it1 != m1.end() && it2 != m2.end() ) { const auto& v1 = it1->first; const auto& v2 = it2->first; if( v1 == v2 ) { int c = it1->second + it2->second; if( c ) m[v1] = c; it1++; it2++; }else if( v1 < v2 ) { m[v1] = it1->second; it2++; }else{ m[v2] = it2->second; it1++; } } while( it1 != m1.end() ) { m.insert( *it1 ); it1++; } while( it2 != m2.end() ) { m.insert( *it2 ); it2++; } } const llvm::DataLayout& getDataLayout( llvm::Instruction* I ) { return I->getParent()->getModule()->getDataLayout(); } llvm::Constant* make_one_constant( llvm::LLVMContext& ctx ) { auto* intType = llvm::IntegerType::get (ctx, 32); return llvm::ConstantInt::getSigned( intType , 1); } llvm::Constant* add_constants( llvm::Constant* c1, llvm::Constant* c2 , const llvm::DataLayout& DL ) { return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Add, c1,c2,DL); } llvm::Constant* sub_constants( llvm::Constant* c1, llvm::Constant* c2 , const llvm::DataLayout& DL ) { return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Sub, c1,c2,DL); } llvm::Constant* mul_constants( llvm::Constant* c1, llvm::Constant* c2 , const llvm::DataLayout& DL ) { return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Mul, c1,c2,DL); } llvm::Constant* min_constant( llvm::Constant* c1, const llvm::DataLayout& DL) { auto* intType = llvm::IntegerType::get (c1->getContext(), 32); llvm::Constant* m1 = llvm::ConstantInt::getSigned( intType , -1); return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Mul, m1,c1,DL); } bool is_zero( llvm::Constant* c1 ) { assert(c1); return c1->isZeroValue(); } bool is_eq( const llvm_mono& lhs, const llvm_mono& rhs ) { auto it1 = lhs.begin(); auto it2 = rhs.begin(); while( it1 != lhs.end() && it2 != rhs.end() ) { llvm::Value* i1 = it1->first; llvm::Value* i2 = it2->first; int c1 = it1->second; int c2 = it2->second; if( i1 == i2 && c1 == c2 ) { it1++; it2++; }else return false; } if( it1 != lhs.end() ) return false; if( it2 != rhs.end() ) return false; return true; } void sum_poly( llvm_poly& poly1, llvm_poly& poly2, llvm_poly& poly, const llvm::DataLayout& DL) { auto it1 = poly1.begin(); auto it2 = poly2.begin(); while( it1 != poly1.end() && it2 != poly2.end() ) { const llvm_mono& m1 = it1->first; const llvm_mono& m2 = it2->first; if( is_eq( m1, m2 ) ) { llvm::Constant* c = add_constants( it1->second, it2->second, DL); if( !is_zero(c) ) poly[m1] = c; it1++; it2++; }else if( compare_mono()(m1,m2) ) { poly[m1] = it1->second; it2++; }else{ poly[m2] = it2->second; it1++; } } while( it1 != poly1.end() ) { poly.insert( *it1 ); it1++; } while( it2 != poly2.end() ) { poly.insert( *it2 ); it2++; } } void sub_poly( llvm_poly& poly1, llvm_poly& poly2, llvm_poly& poly, const llvm::DataLayout& DL ) { auto it1 = poly1.begin(); auto it2 = poly2.begin(); while( it1 != poly1.end() && it2 != poly2.end() ) { const llvm_mono& m1 = it1->first; const llvm_mono& m2 = it2->first; if( is_eq( m1, m2 ) ) { llvm::Constant* c = sub_constants( it1->second, it2->second, DL); if( !is_zero(c) ) poly[m1] = c; it1++; it2++; }else if( compare_mono()(m1,m2) ) { poly[m1] = it1->second; it2++; }else{ poly[m2] = min_constant( it2->second, DL); it1++; } } while( it1 != poly1.end() ) { poly.insert( *it1 ); it1++; } while( it2 != poly2.end() ) { const llvm_mono& m2 = it2->first; poly[m2] = min_constant( it2->second, DL ); it2++; } } void mul_poly( llvm_poly& poly1, llvm_poly& poly2, llvm_poly& poly , const llvm::DataLayout& DL ) { for( auto it1 = poly1.begin(); it1 != poly1.end(); it1++ ) { const llvm_mono& m1 = it1->first; for( auto it2 = poly2.begin(); it2 != poly2.end(); it2++ ) { const llvm_mono& m2 = it2->first; llvm_mono m; merge_mono(m1,m2,m); llvm::Constant* c = mul_constants( it1->second, it2->second, DL); if( exists( poly, m) ) { llvm::Constant* c1 = add_constants( c, poly[m], DL ); if( is_zero(c1) ) { poly.erase(m); }else{ poly[m] = c1; } }else{ poly[m] = c; } } } } llvm_poly& get_simplified_polynomial( llvm::Value* I, std::map<llvm::Value*,llvm_poly>& poly_map, const llvm::DataLayout& DL ) { if( exists( poly_map, I ) ) return poly_map[I]; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(I) ) { assert( bop ); auto op0 = bop->getOperand( 0 ); auto op1 = bop->getOperand( 1 ); llvm_poly& poly1 = get_simplified_polynomial( op0, poly_map, DL ); llvm_poly& poly2 = get_simplified_polynomial( op1, poly_map, DL ); llvm_poly& poly = poly_map[I];// construct the empty poly map unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Add : sum_poly( poly1, poly2, poly, DL ); break; case llvm::Instruction::Sub : sub_poly( poly1, poly2, poly, DL ); break; case llvm::Instruction::Mul : mul_poly( poly1, poly2, poly, DL ); break; // case llvm::Instruction::And : // case llvm::Instruction::Or : // case llvm::Instruction::Xor : // case llvm::Instruction::SDiv: // case llvm::Instruction::UDiv: // case llvm::Instruction::SRem: // case llvm::Instruction::URem: // case llvm::Instruction::FAdd: // case llvm::Instruction::FSub: // case llvm::Instruction::FMul: // case llvm::Instruction::FDiv: // case llvm::Instruction::FRem: default: { const char* opName = bop->getOpcodeName(); tiler_error("simplfy polynomial", "unsupported instruction \"" << opName << "\" occurred!!"); } } }else if(auto cint = llvm::dyn_cast<llvm::ConstantInt>(I) ) { llvm_poly& p = poly_map[I]; llvm_mono m; p[m] = cint; } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(I) ) { auto addr = load->getOperand(0); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( llvm::isa<llvm::GetElementPtrInst>(addr) ) tiler_error("simplfy polynomial", "array instructions unsupporetd supported in polys!!"); llvm_poly& p = poly_map[addr]; llvm_mono m; p[m] = make_one_constant( I->getContext() ); } else { LLVM_DUMP_MARKED( I ); tiler_error("simplfy polynomial", "unsupported instruction!!"); } return poly_map[I]; } // llvm_poly void get_simplified_polynomial( llvm::Value* I, const std::vector<llvm::Value*>& vars, const llvm::DataLayout& DL, llvm_poly& p ) { // const llvm::DataLayout& DL = getDataLayout(I); std::map<llvm::Value*,llvm_poly> poly_map; for( llvm::Value* v : vars ) { llvm_mono m; m[v] = 1; llvm_poly& poly = poly_map[v]; poly[m] = make_one_constant( I->getContext() ); } p = get_simplified_polynomial( I, poly_map, DL ); dump( p ); // return p; } void dump( const llvm_mono& m ) { for( auto pair : m ) { auto& v = pair.first; auto& power = pair.second; v->print( llvm::errs() );; std::cerr << power << "\n"; } } void dump( const llvm_poly& p ) { for( auto& pair : p ) { auto& m = pair.first; auto& coeff = pair.second; dump( m ); std::cerr << "\n"; coeff->print( llvm::errs() ); std::cerr << "\n"; } }
130,429
47,733
#include <stan/math/mix/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/fun/util.hpp> using stan::math::fvar; TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_fv; matrix_fv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_fv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0,0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).val_.val()); EXPECT_FLOAT_EQ(-2.0,result(1,1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(0,0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(0,1).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1,1).d_.val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0,0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(1,0).val_.val()); EXPECT_FLOAT_EQ(2.0,result(1,1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(0,0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(0,1).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1,0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1,1).d_.val()); AVEC q = createAVEC(v(0,0).val(),v(0,1).val(),v(1,0).val(),v(1,1).val()); VEC h; result(0,0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_matrix_2ndDeriv) { using stan::math::subtract; using stan::math::matrix_fv; matrix_fv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_fv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val(),v(0,1).val(),v(1,0).val(),v(1,1).val()); VEC h; result(0,0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_fv; vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_fv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_vector_2ndDeriv) { using stan::math::subtract; using stan::math::vector_fv; vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_fv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_fv; row_vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_fv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_rowvector_2ndDeriv) { using stan::math::subtract; using stan::math::row_vector_fv; row_vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_fv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_vector_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_fv; vector_d expected_output(5); vector_fv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_fv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(vd_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(vv_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(1, output(0).d_.val()); EXPECT_FLOAT_EQ(1, output(1).d_.val()); EXPECT_FLOAT_EQ(1, output(2).d_.val()); EXPECT_FLOAT_EQ(1, output(3).d_.val()); EXPECT_FLOAT_EQ(1, output(4).d_.val()); output = subtract(vd_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(-1.0, output(0).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(1).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(2).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(3).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(4).d_.val()); output = subtract(vv_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(0, output(0).d_.val()); EXPECT_FLOAT_EQ(0, output(1).d_.val()); EXPECT_FLOAT_EQ(0, output(2).d_.val()); EXPECT_FLOAT_EQ(0, output(3).d_.val()); EXPECT_FLOAT_EQ(0, output(4).d_.val()); AVEC q = createAVEC(vv_1(0).val(),vv_1(1).val(),vv_1(2).val(),vv_1(3).val()); VEC h; output(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_vector_vector_2ndDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_fv; vector_d expected_output(5); vector_fv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_fv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val(),vv_1(1).val(),vv_1(2).val(),vv_1(3).val()); VEC h; output(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_vector_vector_exception) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_fv; vector_d d1(5), d2(1); vector_fv v1(5), v2(1); vector_fv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,fv_rowvector_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_fv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_fv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_fv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(rvd_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(rvv_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(1, output(0).d_.val()); EXPECT_FLOAT_EQ(1, output(1).d_.val()); EXPECT_FLOAT_EQ(1, output(2).d_.val()); EXPECT_FLOAT_EQ(1, output(3).d_.val()); EXPECT_FLOAT_EQ(1, output(4).d_.val()); output = subtract(rvd_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(-1, output(0).d_.val()); EXPECT_FLOAT_EQ(-1, output(1).d_.val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val()); EXPECT_FLOAT_EQ(-1, output(3).d_.val()); EXPECT_FLOAT_EQ(-1, output(4).d_.val()); output = subtract(rvv_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(0, output(0).d_.val()); EXPECT_FLOAT_EQ(0, output(1).d_.val()); EXPECT_FLOAT_EQ(0, output(2).d_.val()); EXPECT_FLOAT_EQ(0, output(3).d_.val()); EXPECT_FLOAT_EQ(0, output(4).d_.val()); AVEC q = createAVEC(rvv_1(0).val(),rvv_1(1).val(),rvv_1(2).val(),rvv_1(3).val()); VEC h; output(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_rowvector_rowvector_2ndDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_fv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_fv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_fv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val(),rvv_1(1).val(),rvv_1(2).val(),rvv_1(3).val()); VEC h; output(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_rowvector_rowvector_exception) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_fv; row_vector_d d1(5), d2(2); row_vector_fv v1(5), v2(2); row_vector_fv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,fv_matrix_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_fv; matrix_d expected_output(2,2); matrix_fv output; matrix_d md_1(2,2), md_2(2,2); matrix_fv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_fv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; expected_output << -20, 11, 9, -2; matrix_d output_d = subtract(md_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output_d(0,0)); EXPECT_FLOAT_EQ(expected_output(0,1), output_d(0,1)); EXPECT_FLOAT_EQ(expected_output(1,0), output_d(1,0)); EXPECT_FLOAT_EQ(expected_output(1,1), output_d(1,1)); output = subtract(mv_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val()); EXPECT_FLOAT_EQ(1, output(0,0).d_.val()); EXPECT_FLOAT_EQ(1, output(0,1).d_.val()); EXPECT_FLOAT_EQ(1, output(1,0).d_.val()); EXPECT_FLOAT_EQ(1, output(1,1).d_.val()); output = subtract(md_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val()); EXPECT_FLOAT_EQ(-1, output(0,0).d_.val()); EXPECT_FLOAT_EQ(-1, output(0,1).d_.val()); EXPECT_FLOAT_EQ(-1, output(1,0).d_.val()); EXPECT_FLOAT_EQ(-1, output(1,1).d_.val()); output = subtract(mv_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val()); EXPECT_FLOAT_EQ(0, output(0,0).d_.val()); EXPECT_FLOAT_EQ(0, output(0,1).d_.val()); EXPECT_FLOAT_EQ(0, output(1,0).d_.val()); EXPECT_FLOAT_EQ(0, output(1,1).d_.val()); AVEC q = createAVEC(mv_1(0,0).val(),mv_1(0,1).val(),mv_1(1,0).val(),mv_1(1,1).val()); VEC h; output(0,0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_matrix_matrix_2ndDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_fv; matrix_d expected_output(2,2); matrix_fv output; matrix_d md_1(2,2), md_2(2,2); matrix_fv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_fv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val(),mv_1(0,1).val(),mv_1(1,0).val(),mv_1(1,1).val()); VEC h; output(0,0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_matrix_matrix_exception) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_fv; matrix_d d1(2,2), d2(1,2); matrix_fv v1(2,2), v2(1,2); EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_ffv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0,0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).val_.val().val()); EXPECT_FLOAT_EQ(-2.0,result(1,1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0,0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0,1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1,1).d_.val().val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0,0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1,0).val_.val().val()); EXPECT_FLOAT_EQ(2.0,result(1,1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0,0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0,1).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1,0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1,1).d_.val().val()); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_2ndDeriv_1) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_2ndDeriv_2) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_3rdDeriv) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; v(0).val_.d_ = 1.0; v(1).val_.d_ = 1.0; v(2).val_.d_ = 1.0; v(3).val_.d_ = 1.0; matrix_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_ffv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_2ndDeriv_1) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_2ndDeriv_2) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_3rdDeriv) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; v(0).val_.d_ = 1.0; v(1).val_.d_ = 1.0; v(2).val_.d_ = 1.0; v(3).val_.d_ = 1.0; vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_ffv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_2ndDeriv_1) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_2ndDeriv_2) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_3rdDeriv) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; v(0).val_.d_ = 1.0; v(1).val_.d_ = 1.0; v(2).val_.d_ = 1.0; v(3).val_.d_ = 1.0; row_vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(vd_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(vv_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(1, output(0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1).d_.val().val()); EXPECT_FLOAT_EQ(1, output(2).d_.val().val()); EXPECT_FLOAT_EQ(1, output(3).d_.val().val()); EXPECT_FLOAT_EQ(1, output(4).d_.val().val()); output = subtract(vd_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(2).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(3).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(4).d_.val().val()); output = subtract(vv_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(0, output(0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1).d_.val().val()); EXPECT_FLOAT_EQ(0, output(2).d_.val().val()); EXPECT_FLOAT_EQ(0, output(3).d_.val().val()); EXPECT_FLOAT_EQ(0, output(4).d_.val().val()); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_2ndDeriv_1) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_2ndDeriv_2) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_3rdDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vv_1(0).val_.d_ = 1.0; vv_1(1).val_.d_ = 1.0; vv_1(2).val_.d_ = 1.0; vv_1(3).val_.d_ = 1.0; vv_1(4).val_.d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; vv_2(0).val_.d_ = 1.0; vv_2(1).val_.d_ = 1.0; vv_2(2).val_.d_ = 1.0; vv_2(3).val_.d_ = 1.0; vv_2(4).val_.d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_exception) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d d1(5), d2(1); vector_ffv v1(5), v2(1); vector_ffv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(rvd_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(rvv_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(1, output(0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1).d_.val().val()); EXPECT_FLOAT_EQ(1, output(2).d_.val().val()); EXPECT_FLOAT_EQ(1, output(3).d_.val().val()); EXPECT_FLOAT_EQ(1, output(4).d_.val().val()); output = subtract(rvd_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(-1, output(0).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(1).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(3).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(4).d_.val().val()); output = subtract(rvv_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(0, output(0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1).d_.val().val()); EXPECT_FLOAT_EQ(0, output(2).d_.val().val()); EXPECT_FLOAT_EQ(0, output(3).d_.val().val()); EXPECT_FLOAT_EQ(0, output(4).d_.val().val()); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_2ndDeriv_1) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_2ndDeriv_2) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_3rdDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvv_1(0).val_.d_ = 1.0; rvv_1(1).val_.d_ = 1.0; rvv_1(2).val_.d_ = 1.0; rvv_1(3).val_.d_ = 1.0; rvv_1(4).val_.d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; rvv_2(0).val_.d_ = 1.0; rvv_2(1).val_.d_ = 1.0; rvv_2(2).val_.d_ = 1.0; rvv_2(3).val_.d_ = 1.0; rvv_2(4).val_.d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_exception) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d d1(5), d2(2); row_vector_ffv v1(5), v2(2); row_vector_ffv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; expected_output << -20, 11, 9, -2; matrix_d output_d = subtract(md_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output_d(0,0)); EXPECT_FLOAT_EQ(expected_output(0,1), output_d(0,1)); EXPECT_FLOAT_EQ(expected_output(1,0), output_d(1,0)); EXPECT_FLOAT_EQ(expected_output(1,1), output_d(1,1)); output = subtract(mv_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val().val()); EXPECT_FLOAT_EQ(1, output(0,0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(0,1).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1,0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1,1).d_.val().val()); output = subtract(md_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val().val()); EXPECT_FLOAT_EQ(-1, output(0,0).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(0,1).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(1,0).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(1,1).d_.val().val()); output = subtract(mv_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val().val()); EXPECT_FLOAT_EQ(0, output(0,0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(0,1).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1,0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1,1).d_.val().val()); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_2ndDeriv_1) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_2ndDeriv_2) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_3rdDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; mv_1(0,0).val_.d_ = 1.0; mv_1(0,1).val_.d_ = 1.0; mv_1(1,0).val_.d_ = 1.0; mv_1(1,1).val_.d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; mv_2(0,0).val_.d_ = 1.0; mv_2(0,1).val_.d_ = 1.0; mv_2(1,0).val_.d_ = 1.0; mv_2(1,1).val_.d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_exception) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d d1(2,2), d2(1,2); matrix_ffv v1(2,2), v2(1,2); EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); }
46,697
25,581
// solution to 71A #include <iostream> #include <string> using namespace std; int main() { string arr[100]; int n; cin >> n; for (int i = 0; i < n; i++){ cin >> arr[i]; } for (int i = 0; i < n; i++){ if ( arr[i].size() > 10){ cout << arr[i][0] << arr[i].size() - 2 << arr[i].back() << endl; } else{ cout << arr[i] << endl; } } }
376
167
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 3.0 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /// @file Palette.cpp Defines a color palette. Class defintions. #include "Palette.hpp" namespace vdraw { Palette::Palette(const Color &base, double imin, double imax) { setRange(imin,imax); setColor(imin,base); setColor(imax,base); } Palette::Palette(const Palette &p) { min = p.min; width = p.width; palette = p.palette; } Palette& Palette::operator=(Palette p) { // p is a copy, swap the variables std::swap(min,p.min); std::swap(width,p.width); std::swap(palette,p.palette); // p is destructed with the old data from this return *this; } void Palette::setColor(double val, const Color &c) { clamp(val); val = (val-min)/width; if(palette.size()==0) palette.push_back(std::pair<double,Color>(val,c)); else { std::list<std::pair<double,Color> >::iterator i=palette.begin(); while((i!=palette.end())&&(i->first<val)) i++; if(i==palette.end()) palette.push_back(std::pair<double,Color>(val,c)); else if(i==palette.begin()) palette.push_front(std::pair<double,Color>(val,c)); else if(i->first==val) i->second=c; else palette.insert(i,std::pair<double,Color>(val,c)); } } Color Palette::getColor(double val) const { clamp(val); val = (val-min)/width; std::list<std::pair<double,Color> >::const_iterator j,i=palette.begin(); while((i!=palette.end())&&(i->first<val)) i++; if(i->first==val || i==palette.begin()) return i->second; else if(i==palette.end())return (--i)->second; j = i--; // i is before j return (i->second).interpolate((val-(i->first))/((j->first)-(i->first)),j->second); } }
3,331
1,077
/** * MIT License * * Copyright (c) 2018-2019 Kravchenko Artyom * * 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 "AppService.h" AppService* AppService::_instance = 0; void AppService::init() { _serial = &Serial; _serial->begin(115200); _settingsService = new SettingsService(); _serialService = new SerialService(); _wifiService = new WifiService(); _wifiService->init(); _ntpUDP = new WiFiUDP(); _ntpClient = new NTPClient(*_ntpUDP); _ntpClient->setTimeOffset(3 * 3600); _ntpClient->begin(); _clockService = new ClockService(); _clockService->init(); _webServer = new WebServer(); _webServer->init(); _lightService = new LightService(); _heatingService = new HeatingService(); _aerationService = new AerationService(); _filterService = new FilterService(); _maintainTemperatureService = new MaintainTemperatureService(); _outerTemperatureService = new OuterTemperatureService(); _apiService = new ApiService(); } void AppService::update() { this->getSerialService()->update(); this->getWifiService()->update(); this->getClockService()->update(); this->getLightService()->update(); this->getHeatingService()->update(); this->getAerationService()->update(); this->getFilterService()->update(); this->getMaintainTemperatureService()->update(); this->getOuterTemperatureService()->update(); this->getApiService()->update(); }
2,507
802
#include <string> #include <iostream> #include <aocmaxnoe2020/aocmaxnoe2020.h> #include <aocmaxnoe2020/day10.h> using namespace aocmaxnoe2020; int main() { std::string input = get_input(10); auto numbers = day10::parse_input(input); uint64_t part1 = day10::part1(numbers); std::cout << "Solution 1: " << part1 << std::endl; std::cout << "Solution 2: " << day10::part2(numbers) << std::endl; return 0; }
432
187
// Wiaeditproprange.cpp : implementation file // #include "stdafx.h" #include "wiatest.h" #include "Wiaeditproprange.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CWiaeditproprange dialog CWiaeditproprange::CWiaeditproprange(CWnd* pParent /*=NULL*/) : CDialog(CWiaeditproprange::IDD, pParent) { //{{AFX_DATA_INIT(CWiaeditproprange) m_szPropertyName = _T(""); m_szPropertyValue = _T(""); m_szPropertyIncValue = _T(""); m_szPropertyMaxValue = _T(""); m_szPropertyMinValue = _T(""); m_szPropertyNomValue = _T(""); //}}AFX_DATA_INIT } void CWiaeditproprange::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CWiaeditproprange) DDX_Text(pDX, IDC_RANGE_PROPERTY_NAME, m_szPropertyName); DDX_Text(pDX, IDC_RANGE_PROPERTYVALUE_EDITBOX, m_szPropertyValue); DDX_Text(pDX, RANGE_PROPERTY_INCVALUE, m_szPropertyIncValue); DDX_Text(pDX, RANGE_PROPERTY_MAXVALUE, m_szPropertyMaxValue); DDX_Text(pDX, RANGE_PROPERTY_MINVALUE, m_szPropertyMinValue); DDX_Text(pDX, RANGE_PROPERTY_NOMVALUE, m_szPropertyNomValue); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CWiaeditproprange, CDialog) //{{AFX_MSG_MAP(CWiaeditproprange) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CWiaeditproprange message handlers void CWiaeditproprange::SetPropertyName(TCHAR *szPropertyName) { m_szPropertyName = szPropertyName; } void CWiaeditproprange::SetPropertyValue(TCHAR *szPropertyValue) { m_szPropertyValue = szPropertyValue; } void CWiaeditproprange::SetPropertyValidValues(PVALID_RANGE_VALUES pValidRangeValues) { m_szPropertyMinValue.Format(TEXT("%d"),pValidRangeValues->lMin); m_szPropertyMaxValue.Format(TEXT("%d"),pValidRangeValues->lMax); m_szPropertyNomValue.Format(TEXT("%d"),pValidRangeValues->lNom); m_szPropertyIncValue.Format(TEXT("%d"),pValidRangeValues->lInc); }
2,161
851
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Martin Fusseder, https://github.com/MFusseder // // System includes // External includes // Project includes #include "stress_response_definitions.h" #include "utilities/compare_elements_and_conditions_utility.h" #include "structural_mechanics_application_variables.h" namespace Kratos { namespace StressResponseDefinitions { TracedStressType ConvertStringToTracedStressType(const std::string& Str) { const std::map<std::string, TracedStressType> traced_stress_type_map { { "FX", TracedStressType::FX }, { "FY", TracedStressType::FY }, { "FZ", TracedStressType::FZ }, { "MX", TracedStressType::MX }, { "MY", TracedStressType::MY }, { "MZ", TracedStressType::MZ }, { "FXX", TracedStressType::FXX }, { "FXY", TracedStressType::FXY }, { "FXZ", TracedStressType::FXZ }, { "FYX", TracedStressType::FYX }, { "FYY", TracedStressType::FYY }, { "FYZ", TracedStressType::FYZ }, { "FZX", TracedStressType::FZX }, { "FZY", TracedStressType::FZY }, { "FZZ", TracedStressType::FZZ }, { "MXX", TracedStressType::MXX }, { "MXY", TracedStressType::MXY }, { "MXZ", TracedStressType::MXZ }, { "MYX", TracedStressType::MYX }, { "MYY", TracedStressType::MYY }, { "MYZ", TracedStressType::MYZ }, { "MZX", TracedStressType::MZX }, { "MZY", TracedStressType::MZY }, { "MZZ", TracedStressType::MZZ }, { "PK2", TracedStressType::PK2 }, }; auto stress_type_it = traced_stress_type_map.find(Str); if (stress_type_it == traced_stress_type_map.end()) { std::stringstream available_types; for(auto& it : traced_stress_type_map) available_types << it.first << ",\n"; KRATOS_ERROR << "Chosen stress type '" <<Str<<"' is not available!" << " Available types are: \n" << available_types.str() << std::endl; } return stress_type_it->second; } StressTreatment ConvertStringToStressTreatment(const std::string& Str) { const std::map<std::string, StressTreatment> stress_treatment_map { { "mean", StressTreatment::Mean }, { "node", StressTreatment::Node }, { "GP", StressTreatment::GaussPoint } }; auto stress_treatment_it = stress_treatment_map.find(Str); if (stress_treatment_it == stress_treatment_map.end()) { std::stringstream available_types; for(auto& it : stress_treatment_map) available_types << it.first << ",\n"; KRATOS_ERROR << "Chosen stress treatment '" <<Str<<"' is not available!" << " Available types are: \n" << available_types.str() << std::endl; } return stress_treatment_it->second; } } // namespace StressResponseDefinitions. void StressCalculation::CalculateStressOnNode(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; std::string name_current_element; CompareElementsAndConditionsUtility::GetRegisteredName(rElement, name_current_element); if(name_current_element == "CrLinearBeamElement3D2N") StressCalculation::CalculateStressOnNodeBeam(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "ShellThinElement3D3N") KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; else if(name_current_element == "TrussElement3D2N") KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; else if(name_current_element == "TrussLinearElement3D2N") KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; else KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGP(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; std::string name_current_element; CompareElementsAndConditionsUtility::GetRegisteredName(rElement, name_current_element); if(name_current_element == "CrLinearBeamElement3D2N") StressCalculation::CalculateStressOnGPBeam(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "ShellThinElement3D3N") StressCalculation::CalculateStressOnGPShell(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "TrussElement3D2N") StressCalculation::CalculateStressOnGPTruss(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "TrussLinearElement3D2N") StressCalculation::CalculateStressOnGPLinearTruss(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else KRATOS_ERROR << "Stress calculation on GP not yet implemented for " << name_current_element << std::endl; KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGPLinearTruss(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; const SizeType GP_num = rElement.GetGeometry().IntegrationPoints().size(); if (rOutput.size() != GP_num) rOutput.resize(GP_num, false); switch (rTracedStressType) { case TracedStressType::FX: { std::vector< array_1d<double, 3 > > force_vector; rElement.CalculateOnIntegrationPoints(FORCE, force_vector, rCurrentProcessInfo); for(IndexType i = 0; i < GP_num ; ++i) rOutput(i) = force_vector[i][0]; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGPTruss(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; const SizeType GP_num = (rElement.GetGeometry().IntegrationPoints()).size(); if (rOutput.size() != GP_num) rOutput.resize(GP_num, false); switch (rTracedStressType) { case TracedStressType::FX: { std::vector< array_1d<double, 3 > > force_vector; rElement.CalculateOnIntegrationPoints(FORCE, force_vector, rCurrentProcessInfo); for(IndexType i = 0; i < GP_num ; ++i) rOutput(i) = force_vector[i][0]; break; } case TracedStressType::PK2: { std::vector<Vector> stress_vector; rElement.CalculateOnIntegrationPoints(PK2_STRESS_VECTOR, stress_vector, rCurrentProcessInfo); for(IndexType i = 0; i < GP_num ; ++i) rOutput(i) = stress_vector[i][0]; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGPShell(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; const SizeType num_gps = rElement.GetGeometry().IntegrationPointsNumber(rElement.GetIntegrationMethod()); int direction_1 = 0; int direction_2 = 0; std::vector<Matrix> stress_vector; bool stress_is_moment = true; switch (rTracedStressType) { case TracedStressType::MXX: { direction_1 = 0; direction_2 = 0; break; } case TracedStressType::MXY: { direction_1 = 0; direction_2 = 1; break; } case TracedStressType::MXZ: { direction_1 = 0; direction_2 = 2; break; } case TracedStressType::MYX: { direction_1 = 1; direction_2 = 0; break; } case TracedStressType::MYY : { direction_1 = 1; direction_2 = 1; break; } case TracedStressType::MYZ: { direction_1 = 1; direction_2 = 2; break; } case TracedStressType::MZX: { direction_1 = 2; direction_2 = 0; break; } case TracedStressType::MZY: { direction_1 = 2; direction_2 = 1; break; } case TracedStressType::MZZ : { direction_1 = 2; direction_2 = 2; break; } case TracedStressType::FXX : { direction_1 = 0; direction_2 = 0; stress_is_moment = false; break; } case TracedStressType::FXY: { direction_1 = 0; direction_2 = 1; stress_is_moment = false; break; } case TracedStressType::FXZ: { direction_1 = 0; direction_2 = 2; stress_is_moment = false; break; } case TracedStressType::FYX: { direction_1 = 1; direction_2 = 0; stress_is_moment = false; break; } case TracedStressType::FYY: { direction_1 = 1; direction_2 = 1; stress_is_moment = false; break; } case TracedStressType::FYZ: { direction_1 = 1; direction_2 = 2; stress_is_moment = false; break; } case TracedStressType::FZX: { direction_1 = 2; direction_2 = 0; stress_is_moment = false; break; } case TracedStressType::FZY: { direction_1 = 2; direction_2 = 1; stress_is_moment = false; break; } case TracedStressType::FZZ: { direction_1 = 2; direction_2 = 2; stress_is_moment = false; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } if(stress_is_moment) rElement.CalculateOnIntegrationPoints(SHELL_MOMENT_GLOBAL, stress_vector, rCurrentProcessInfo); else rElement.CalculateOnIntegrationPoints(SHELL_FORCE_GLOBAL, stress_vector, rCurrentProcessInfo); rOutput.resize(num_gps, false); for(IndexType i = 0; i < num_gps; i++) { rOutput(i) = stress_vector[i](direction_1, direction_2); } KRATOS_CATCH(""); } void StressCalculation::StressCalculation::CalculateStressBeam(Element& rElement, const TracedStressType rTracedStressType, std::vector< array_1d<double, 3 > >& rStressVector, const ProcessInfo& rCurrentProcessInfo, int& rDirection) { rDirection = 0; bool stress_is_moment = true; switch (rTracedStressType) { case TracedStressType::MX: { rDirection = 0; break; } case TracedStressType::MY: { rDirection = 1; break; } case TracedStressType::MZ: { rDirection = 2; break; } case TracedStressType::FX: { rDirection = 0; stress_is_moment = false; break; } case TracedStressType::FY: { rDirection = 1; stress_is_moment = false; break; } case TracedStressType::FZ: { rDirection = 2; stress_is_moment = false; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } if(stress_is_moment) rElement.CalculateOnIntegrationPoints(MOMENT, rStressVector, rCurrentProcessInfo); else rElement.CalculateOnIntegrationPoints(FORCE, rStressVector, rCurrentProcessInfo); } void StressCalculation::CalculateStressOnGPBeam(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; int direction_1; std::vector< array_1d<double, 3 > > stress_vector; StressCalculation::CalculateStressBeam(rElement, rTracedStressType, stress_vector, rCurrentProcessInfo, direction_1); const SizeType GP_num = rElement.GetGeometry().IntegrationPointsNumber(Kratos::GeometryData::GI_GAUSS_3); rOutput.resize(GP_num, false); for(IndexType i = 0; i < GP_num ; i++) { rOutput(i) = stress_vector[i][direction_1]; } KRATOS_CATCH("") } void StressCalculation::CalculateStressOnNodeBeam(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; int direction_1; std::vector< array_1d<double, 3 > > stress_vector; StressCalculation::CalculateStressBeam(rElement, rTracedStressType, stress_vector, rCurrentProcessInfo, direction_1); rOutput.resize(2, false); rOutput(0) = 2 * stress_vector[0][direction_1] - stress_vector[1][direction_1]; rOutput(1) = 2 * stress_vector[2][direction_1] - stress_vector[1][direction_1]; KRATOS_CATCH("") } } // namespace Kratos.
14,919
4,749
// Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. #ifndef _UROS_AGENT_AGENT_HPP #define _UROS_AGENT_AGENT_HPP #include <uxr/agent/AgentInstance.hpp> #include <uxr/agent/middleware/Middleware.hpp> #include <uxr/agent/middleware/utils/Callbacks.hpp> #include <agent/graph_manager/graph_manager.hpp> // TODO(jamoralp): class Documentation namespace uros { namespace agent { class Agent { public: Agent(); ~Agent() = default; bool create( int argc, char** argv); void run(); private: eprosima::uxr::AgentInstance& xrce_dds_agent_instance_; std::map<eprosima::fastdds::dds::DomainId_t, std::shared_ptr<graph_manager::GraphManager>> graph_manager_map_; std::shared_ptr<graph_manager::GraphManager> find_or_create_graph_manager(eprosima::fastdds::dds::DomainId_t domain_id); }; } // namespace agent } // namespace uros #endif // _UROS_AGENT_AGENT_HPP
1,489
505
#include <string> #include <vector> #include <libpy/autofunction.h> #include <libpy/automodule.h> #include <libpy/ndarray_view.h> #include <libpy/numpy_utils.h> namespace libpy_tutorial { std::int64_t simple_sum(py::array_view<const std::int64_t> values) { std::int64_t out = 0; for (auto value : values) { out += value; } return out; } std::int64_t simple_sum_iterator(py::array_view<const std::int64_t> values) { return std::accumulate(values.begin(), values.end(), 0); } void negate_inplace(py::array_view<std::int64_t> values) { std::transform(values.cbegin(), values.cend(), values.begin(), [](std::int64_t v) { return -v; }); } bool check_prime(std::int64_t n) { if (n <= 3) { return n > 1; } else if (n % 2 == 0 || n % 3 == 0) { return false; } for (auto i = 5; std::pow(i, 2) < n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } py::owned_ref<> is_prime(py::array_view<const std::int64_t> values) { std::vector<py::py_bool> out(values.size()); std::transform(values.begin(), values.end(), out.begin(), check_prime); return py::move_to_numpy_array(std::move(out)); } LIBPY_AUTOMODULE(libpy_tutorial, arrays, ({py::autofunction<simple_sum>("simple_sum"), py::autofunction<simple_sum_iterator>("simple_sum_iterator"), py::autofunction<negate_inplace>("negate_inplace"), py::autofunction<is_prime>("is_prime")})) (py::borrowed_ref<>) { return false; } } // namespace libpy_tutorial
1,696
634
#include <cstdio> #include <chrono> #include "nl_means.h" #include "nl_means_auto_schedule.h" #include "halide_benchmark.h" #include "HalideBuffer.h" #include "halide_image_io.h" using namespace Halide::Runtime; using namespace Halide::Tools; int main(int argc, char **argv) { if (argc < 7) { printf("Usage: ./process input.png patch_size search_area sigma timing_iterations output.png\n" "e.g.: ./process input.png 7 7 0.12 10 output.png\n"); return 0; } Buffer<float> input = load_and_convert_image(argv[1]); int patch_size = atoi(argv[2]); int search_area = atoi(argv[3]); float sigma = atof(argv[4]); Buffer<float> output(input.width(), input.height(), 3); int timing_iterations = atoi(argv[5]); nl_means(input, patch_size, search_area, sigma, output); // Timing code printf("Input size: %d by %d, patch size: %d, search area: %d, sigma: %f\n", input.width(), input.height(), patch_size, search_area, sigma); // Manually-tuned version double min_t_manual = benchmark(timing_iterations, 1, [&]() { nl_means(input, patch_size, search_area, sigma, output); output.device_sync(); }); printf("Manually-tuned time: %gms\n", min_t_manual * 1e3); // Auto-scheduled version double min_t_auto = benchmark(timing_iterations, 1, [&]() { nl_means_auto_schedule(input, patch_size, search_area, sigma, output); }); printf("Auto-scheduled time: %gms\n", min_t_auto * 1e3); convert_and_save_image(output, argv[6]); return 0; }
1,570
590
/*! * Copyright 2017-2020 XGBoost contributors */ #include <dmlc/filesystem.h> #include <gtest/gtest.h> #include <xgboost/predictor.h> #include "../helpers.h" #include "test_predictor.h" #include "../../../src/gbm/gbtree_model.h" #include "../../../src/gbm/gbtree.h" #include "../../../src/data/adapter.h" namespace xgboost { TEST(CpuPredictor, Basic) { auto lparam = CreateEmptyGenericParam(GPUIDX); std::unique_ptr<Predictor> cpu_predictor = std::unique_ptr<Predictor>(Predictor::Create("cpu_predictor", &lparam)); size_t constexpr kRows = 5; size_t constexpr kCols = 5; LearnerModelParam param; param.num_feature = kCols; param.base_score = 0.0; param.num_output_group = 1; gbm::GBTreeModel model = CreateTestModel(&param); auto dmat = RandomDataGenerator(kRows, kCols, 0).GenerateDMatrix(); // Test predict batch PredictionCacheEntry out_predictions; cpu_predictor->InitOutPredictions(dmat->Info(), &out_predictions.predictions, model); cpu_predictor->PredictBatch(dmat.get(), &out_predictions, model, 0); std::vector<float>& out_predictions_h = out_predictions.predictions.HostVector(); for (size_t i = 0; i < out_predictions.predictions.Size(); i++) { ASSERT_EQ(out_predictions_h[i], 1.5); } // Test predict instance auto const &batch = *dmat->GetBatches<xgboost::SparsePage>().begin(); auto page = batch.GetView(); for (size_t i = 0; i < batch.Size(); i++) { std::vector<float> instance_out_predictions; cpu_predictor->PredictInstance(page[i], &instance_out_predictions, model); ASSERT_EQ(instance_out_predictions[0], 1.5); } // Test predict leaf HostDeviceVector<float> leaf_out_predictions; cpu_predictor->PredictLeaf(dmat.get(), &leaf_out_predictions, model); auto const& h_leaf_out_predictions = leaf_out_predictions.ConstHostVector(); for (auto v : h_leaf_out_predictions) { ASSERT_EQ(v, 0); } // Test predict contribution HostDeviceVector<float> out_contribution_hdv; auto& out_contribution = out_contribution_hdv.HostVector(); cpu_predictor->PredictContribution(dmat.get(), &out_contribution_hdv, model); ASSERT_EQ(out_contribution.size(), kRows * (kCols + 1)); for (size_t i = 0; i < out_contribution.size(); ++i) { auto const& contri = out_contribution[i]; // shift 1 for bias, as test tree is a decision dump, only global bias is // filled with LeafValue(). if ((i + 1) % (kCols + 1) == 0) { ASSERT_EQ(out_contribution.back(), 1.5f); } else { ASSERT_EQ(contri, 0); } } // Test predict contribution (approximate method) cpu_predictor->PredictContribution(dmat.get(), &out_contribution_hdv, model, 0, nullptr, true); for (size_t i = 0; i < out_contribution.size(); ++i) { auto const& contri = out_contribution[i]; // shift 1 for bias, as test tree is a decision dump, only global bias is // filled with LeafValue(). if ((i + 1) % (kCols + 1) == 0) { ASSERT_EQ(out_contribution.back(), 1.5f); } else { ASSERT_EQ(contri, 0); } } } TEST(CpuPredictor, IterationRange) { TestIterationRange("cpu_predictor"); } TEST(CpuPredictor, ExternalMemory) { size_t constexpr kPageSize = 64, kEntriesPerCol = 3; size_t constexpr kEntries = kPageSize * kEntriesPerCol * 2; std::unique_ptr<DMatrix> dmat = CreateSparsePageDMatrix(kEntries); auto lparam = CreateEmptyGenericParam(GPUIDX); std::unique_ptr<Predictor> cpu_predictor = std::unique_ptr<Predictor>(Predictor::Create("cpu_predictor", &lparam)); LearnerModelParam param; param.base_score = 0; param.num_feature = dmat->Info().num_col_; param.num_output_group = 1; gbm::GBTreeModel model = CreateTestModel(&param); // Test predict batch PredictionCacheEntry out_predictions; cpu_predictor->InitOutPredictions(dmat->Info(), &out_predictions.predictions, model); cpu_predictor->PredictBatch(dmat.get(), &out_predictions, model, 0); std::vector<float> &out_predictions_h = out_predictions.predictions.HostVector(); ASSERT_EQ(out_predictions.predictions.Size(), dmat->Info().num_row_); for (const auto& v : out_predictions_h) { ASSERT_EQ(v, 1.5); } // Test predict leaf HostDeviceVector<float> leaf_out_predictions; cpu_predictor->PredictLeaf(dmat.get(), &leaf_out_predictions, model); auto const& h_leaf_out_predictions = leaf_out_predictions.ConstHostVector(); ASSERT_EQ(h_leaf_out_predictions.size(), dmat->Info().num_row_); for (const auto& v : h_leaf_out_predictions) { ASSERT_EQ(v, 0); } // Test predict contribution HostDeviceVector<float> out_contribution_hdv; auto& out_contribution = out_contribution_hdv.HostVector(); cpu_predictor->PredictContribution(dmat.get(), &out_contribution_hdv, model); ASSERT_EQ(out_contribution.size(), dmat->Info().num_row_ * (dmat->Info().num_col_ + 1)); for (size_t i = 0; i < out_contribution.size(); ++i) { auto const& contri = out_contribution[i]; // shift 1 for bias, as test tree is a decision dump, only global bias is filled with LeafValue(). if ((i + 1) % (dmat->Info().num_col_ + 1) == 0) { ASSERT_EQ(out_contribution.back(), 1.5f); } else { ASSERT_EQ(contri, 0); } } // Test predict contribution (approximate method) HostDeviceVector<float> out_contribution_approximate_hdv; auto& out_contribution_approximate = out_contribution_approximate_hdv.HostVector(); cpu_predictor->PredictContribution( dmat.get(), &out_contribution_approximate_hdv, model, 0, nullptr, true); ASSERT_EQ(out_contribution_approximate.size(), dmat->Info().num_row_ * (dmat->Info().num_col_ + 1)); for (size_t i = 0; i < out_contribution.size(); ++i) { auto const& contri = out_contribution[i]; // shift 1 for bias, as test tree is a decision dump, only global bias is filled with LeafValue(). if ((i + 1) % (dmat->Info().num_col_ + 1) == 0) { ASSERT_EQ(out_contribution.back(), 1.5f); } else { ASSERT_EQ(contri, 0); } } } TEST(CpuPredictor, InplacePredict) { bst_row_t constexpr kRows{128}; bst_feature_t constexpr kCols{64}; auto gen = RandomDataGenerator{kRows, kCols, 0.5}.Device(-1); { HostDeviceVector<float> data; gen.GenerateDense(&data); ASSERT_EQ(data.Size(), kRows * kCols); std::shared_ptr<data::DenseAdapter> x{ new data::DenseAdapter(data.HostPointer(), kRows, kCols)}; TestInplacePrediction(x, "cpu_predictor", kRows, kCols, -1); } { HostDeviceVector<float> data; HostDeviceVector<bst_row_t> rptrs; HostDeviceVector<bst_feature_t> columns; gen.GenerateCSR(&data, &rptrs, &columns); std::shared_ptr<data::CSRAdapter> x{new data::CSRAdapter( rptrs.HostPointer(), columns.HostPointer(), data.HostPointer(), kRows, data.Size(), kCols)}; TestInplacePrediction(x, "cpu_predictor", kRows, kCols, -1); } } void TestUpdatePredictionCache(bool use_subsampling) { size_t constexpr kRows = 64, kCols = 16, kClasses = 4; LearnerModelParam mparam; mparam.num_feature = kCols; mparam.num_output_group = kClasses; mparam.base_score = 0; GenericParameter gparam; gparam.Init(Args{}); std::unique_ptr<gbm::GBTree> gbm; gbm.reset(static_cast<gbm::GBTree*>(GradientBooster::Create("gbtree", &gparam, &mparam))); std::map<std::string, std::string> cfg; cfg["tree_method"] = "hist"; cfg["predictor"] = "cpu_predictor"; if (use_subsampling) { cfg["subsample"] = "0.5"; } Args args = {cfg.cbegin(), cfg.cend()}; gbm->Configure(args); auto dmat = RandomDataGenerator(kRows, kCols, 0).GenerateDMatrix(true, true, kClasses); HostDeviceVector<GradientPair> gpair; auto& h_gpair = gpair.HostVector(); h_gpair.resize(kRows*kClasses); for (size_t i = 0; i < kRows*kClasses; ++i) { h_gpair[i] = {static_cast<float>(i), 1}; } PredictionCacheEntry predtion_cache; predtion_cache.predictions.Resize(kRows*kClasses, 0); // after one training iteration predtion_cache is filled with cached in QuantileHistMaker::Builder prediction values gbm->DoBoost(dmat.get(), &gpair, &predtion_cache); PredictionCacheEntry out_predictions; // perform fair prediction on the same input data, should be equal to cached result gbm->PredictBatch(dmat.get(), &out_predictions, false, 0, 0); std::vector<float> &out_predictions_h = out_predictions.predictions.HostVector(); std::vector<float> &predtion_cache_from_train = predtion_cache.predictions.HostVector(); for (size_t i = 0; i < out_predictions_h.size(); ++i) { ASSERT_NEAR(out_predictions_h[i], predtion_cache_from_train[i], kRtEps); } } TEST(CPUPredictor, CategoricalPrediction) { TestCategoricalPrediction("cpu_predictor"); } TEST(CPUPredictor, CategoricalPredictLeaf) { TestCategoricalPredictLeaf(StringView{"cpu_predictor"}); } TEST(CpuPredictor, UpdatePredictionCache) { TestUpdatePredictionCache(false); TestUpdatePredictionCache(true); } TEST(CpuPredictor, LesserFeatures) { TestPredictionWithLesserFeatures("cpu_predictor"); } } // namespace xgboost
9,045
3,394
version https://git-lfs.github.com/spec/v1 oid sha256:8aa5ed706dca5c634da572b1fb1bbb853d4587e7f5852d746790690c0ed3cd7e size 396
128
88
#include "platform_macro.h" #if defined(TARGET_ARCH_X64) || defined(TARGET_ARCH_IA32) #include "core/modules/assembler/assembler-x86-shared.h" using namespace zz::x86shared; void Assembler::jmp(Immediate imm) { buffer_->Emit8(0xE9); buffer_->Emit32((int)imm.value()); } uint64_t TurboAssembler::CurrentIP() { return pc_offset() + (addr_t)realized_address_; } #endif
376
165
#include "stdafx.h" #include "ReInstructionGenerator.h" #include "ReExpression.h" #include "ReInstruction.h" #include "ReBinaryOperationExpression.h" #include "ReIfExpression.h" #include "ReDeclarationExpression.h" #include "ReAssociationExpression.h" #include "ReValueExpression.h" #include "ReIdentifierExpression.h" #include "ReWhileExpression.h" namespace Redneck { InstructionGenerator::InstructionGenerator() { } InstructionGenerator::~InstructionGenerator() { } vector<Instruction*> InstructionGenerator::Generate(list<Expression*> expressions) { vector<Instruction*> instructions; DoGenerateInner(instructions, expressions, 0); return instructions; } void InstructionGenerator::DoGenerateInner(vector<Instruction*>& instructions, list<Expression*> expressions, unsigned depth) { for (Expression* expression : expressions) { DoGenerate(instructions, expression, depth); } } void InstructionGenerator::DoGenerate(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { switch (expression->GetExpressionType()) { case ExpressionType::EXPRESSION_DECLARATION: GenerateDeclaration(instructions, expression, depth); break; case ExpressionType::EXPRESSION_ASSOCIATION: GenerateAssociation(instructions, expression, depth); break; case ExpressionType::EXPRESSION_VALUE: GenerateValue(instructions, expression, depth); break; case ExpressionType::EXPRESSION_IDENTIFIER: GenerateIdentifier(instructions, expression, depth); break; case ExpressionType::EXPRESSION_BIN_OPERATION: GenerateBinaryOperation(instructions, expression, depth); break; case ExpressionType::EXPRESSION_IF: GenerateIf(instructions, expression, depth); break; case ExpressionType::EXPRESSION_WHILE: GenerateWhile(instructions, expression, depth); break; } } void InstructionGenerator::GenerateDeclaration(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { DeclarationExpression* declarationExpression = (DeclarationExpression*)expression; AddInstruction(instructions, ByteCode::VAR, declarationExpression->GetIdentifier()->GetValue()); DoGenerate(instructions, declarationExpression->GetDeclaration(), depth); AddInstruction(instructions, ByteCode::ASN, declarationExpression->GetIdentifier()->GetValue()); } void InstructionGenerator::GenerateAssociation(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { AssociationExpression* associationExpression = (AssociationExpression*)expression; DoGenerate(instructions, associationExpression->GetDeclaration(), depth); AddInstruction(instructions, ByteCode::ASN, associationExpression->GetIdentifier()->GetValue()); } void InstructionGenerator::GenerateValue(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { ValueExpression* valueExpression = (ValueExpression*)expression; AddInstruction(instructions, ByteCode::PUSH, valueExpression->GetValue()); } void InstructionGenerator::GenerateIdentifier(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { IdentifierExpression* identifierExpression = (IdentifierExpression*)expression; AddInstruction(instructions, ByteCode::LOAD, identifierExpression->GetValue()); } void InstructionGenerator::GenerateBinaryOperation(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { BinaryOperationExpression* binaryOperationExpression = (BinaryOperationExpression*)expression; DoGenerate(instructions, binaryOperationExpression->GetArg0(), depth); DoGenerate(instructions, binaryOperationExpression->GetArg1(), depth); if (binaryOperationExpression->GetOperator() == "+") { AddInstruction(instructions, ByteCode::ADD, EMPTY); } else if (binaryOperationExpression->GetOperator() == "-") { AddInstruction(instructions, ByteCode::SUB, EMPTY); } else if (binaryOperationExpression->GetOperator() == "*") { AddInstruction(instructions, ByteCode::MULT, EMPTY); } else if (binaryOperationExpression->GetOperator() == "/") { AddInstruction(instructions, ByteCode::DIV, EMPTY); } else if (binaryOperationExpression->GetOperator() == "==") { AddInstruction(instructions, ByteCode::EQUALS, EMPTY); } else if (binaryOperationExpression->GetOperator() == "!=") { AddInstruction(instructions, ByteCode::NEQUALS, EMPTY); } else if (binaryOperationExpression->GetOperator() == ">") { AddInstruction(instructions, ByteCode::GRT, EMPTY); } else if (binaryOperationExpression->GetOperator() == "<") { AddInstruction(instructions, ByteCode::LS, EMPTY); } else if (binaryOperationExpression->GetOperator() == ">=") { AddInstruction(instructions, ByteCode::GRTE, EMPTY); } else if (binaryOperationExpression->GetOperator() == "<=") { AddInstruction(instructions, ByteCode::LSE, EMPTY); } } void InstructionGenerator::GenerateIf(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { //IfExpression* ifExpression = (IfExpression*)expression; //string jumpAddress = GetJumpAddress("cond", depth++); //DoGenerate(instructions, ifExpression->GetCondition(), depth); //AddInstruction(instructions, ByteCode::JZERO, jumpAddress); //DoGenerateInner(instructions, ifExpression->GetStatements(), depth); //AddInstruction(instructions, ByteCode::END, jumpAddress); } void InstructionGenerator::GenerateWhile(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { //WhileExpression* whileExpression = (WhileExpression*)expression; //string jumpAddress = GetJumpAddress("loop", depth++); //AddInstruction(instructions, ByteCode::SKIP, jumpAddress); //DoGenerate(instructions, whileExpression->GetCondition(), depth); //AddInstruction(instructions, ByteCode::JZERO, EMPTY); //DoGenerateInner(instructions, whileExpression->GetStatements(), depth); //AddInstruction(instructions, ByteCode::LOOP, jumpAddress); } void InstructionGenerator::AddInstruction(vector<Instruction*>& instructions, ByteCode byteCode, const string& value) { instructions.push_back(new Instruction(byteCode, value)); } string InstructionGenerator::GetJumpAddress(const string& name, int depth) { stringstream sstream; sstream << name << depth; return sstream.str(); } }
6,510
2,008
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2023-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include <maxscale/ccdefs.hh> #include <maxscale/maxscale.h> #include <time.h> #include <maxscale/mainworker.hh> #include <maxscale/routingworker.hh> #include "internal/maxscale.hh" #include "internal/service.hh" #include "internal/admin.hh" #include "internal/monitormanager.hh" static time_t started; namespace { struct ThisUnit { std::atomic<const mxb::Worker*> admin_worker {nullptr}; }; ThisUnit this_unit; } void maxscale_reset_starttime(void) { started = time(0); } time_t maxscale_started(void) { return started; } int maxscale_uptime() { return time(0) - started; } static sig_atomic_t n_shutdowns = 0; bool maxscale_is_shutting_down() { return n_shutdowns != 0; } int maxscale_shutdown() { int n = n_shutdowns++; if (n == 0) { auto func = []() { if (mxs::MainWorker::created()) { mxs::MainWorker::get().shutdown(); } /*< Stop all monitors */ MonitorManager::stop_all_monitors(); mxs_admin_shutdown(); mxs::RoutingWorker::shutdown_all(); }; auto w = mxs::RoutingWorker::get(mxs::RoutingWorker::MAIN); w->execute(func, nullptr, mxs::RoutingWorker::EXECUTE_QUEUED); } return n + 1; } static bool teardown_in_progress = false; bool maxscale_teardown_in_progress() { return teardown_in_progress; } void maxscale_start_teardown() { teardown_in_progress = true; } bool running_in_admin_thread() { auto current_worker = mxb::Worker::get_current(); return current_worker == this_unit.admin_worker.load(std::memory_order_acquire); } void set_admin_worker(const mxb::Worker* admin_worker) { this_unit.admin_worker.store(admin_worker, std::memory_order_release); }
2,222
780
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/benchmark.h" #include "iree/base/internal/file_io.h" #include "iree/base/internal/flags.h" #include "iree/base/status.h" #include "iree/base/tracing.h" #include "iree/hal/drivers/init.h" #include "iree/modules/hal/hal_module.h" #include "iree/tools/utils/vm_util.h" #include "iree/vm/api.h" #include "iree/vm/bytecode_module.h" IREE_FLAG(string, module_file, "-", "File containing the module to load that contains the entry " "function. Defaults to stdin."); // TODO(hanchung): Extract the batch size using // iree_vm_function_reflection_attr. IREE_FLAG( int32_t, batch_size, 1, "The number of batch size, which is expected to match " "iree-hal-benchmark-dispatch-repeat-count when translating the module"); IREE_FLAG(string, entry_function, "", "Name of a function contained in the module specified by module_file " "to run. If this is not set, all the exported functions will be " "benchmarked and they are expected to not have input arguments."); IREE_FLAG(string, driver, "vmla", "Backend driver to use."); static iree_status_t parse_function_input(iree_string_view_t flag_name, void* storage, iree_string_view_t value) { auto* list = (std::vector<std::string>*)storage; list->push_back(std::string(value.data, value.size)); return iree_ok_status(); } static void print_function_input(iree_string_view_t flag_name, void* storage, FILE* file) { auto* list = (std::vector<std::string>*)storage; if (list->empty()) { fprintf(file, "# --%.*s=\n", (int)flag_name.size, flag_name.data); } else { for (size_t i = 0; i < list->size(); ++i) { fprintf(file, "--%.*s=\"%s\"\n", (int)flag_name.size, flag_name.data, list->at(i).c_str()); } } } static std::vector<std::string> FLAG_function_inputs; IREE_FLAG_CALLBACK( parse_function_input, print_function_input, &FLAG_function_inputs, function_input, "An input value or buffer of the format:\n" " [shape]xtype=[value]\n" " 2x2xi32=1 2 3 4\n" "Optionally, brackets may be used to separate the element values:\n" " 2x2xi32=[[1 2][3 4]]\n" "Each occurrence of the flag indicates an input in the order they were\n" "specified on the command line."); namespace iree { namespace { static void BenchmarkFunction( const std::string& benchmark_name, int batch_size, iree_vm_context_t* context, iree_vm_function_t function, iree_vm_list_t* inputs, const std::vector<RawSignatureParser::Description>& output_descs, benchmark::State& state) { IREE_TRACE_SCOPE_DYNAMIC(benchmark_name.c_str()); IREE_TRACE_FRAME_MARK(); // Benchmarking loop. while (state.KeepRunningBatch(batch_size)) { IREE_TRACE_SCOPE0("BenchmarkIteration"); IREE_TRACE_FRAME_MARK_NAMED("Iteration"); vm::ref<iree_vm_list_t> outputs; IREE_CHECK_OK(iree_vm_list_create(/*element_type=*/nullptr, output_descs.size(), iree_allocator_system(), &outputs)); IREE_CHECK_OK(iree_vm_invoke(context, function, /*policy=*/nullptr, inputs, outputs.get(), iree_allocator_system())); } } void RegisterModuleBenchmarks( const std::string& function_name, iree_vm_context_t* context, iree_vm_function_t function, iree_vm_list_t* inputs, const std::vector<RawSignatureParser::Description>& output_descs) { auto benchmark_name = "BM_" + function_name; int batch_size = FLAG_batch_size; benchmark::RegisterBenchmark( benchmark_name.c_str(), [benchmark_name, batch_size, context, function, inputs, output_descs](benchmark::State& state) -> void { BenchmarkFunction(benchmark_name, batch_size, context, function, inputs, output_descs, state); }) // By default only the main thread is included in CPU time. Include all // the threads instead. ->MeasureProcessCPUTime() // To make single and multi-threaded benchmarks more comparable, use the // wall time to determine how many iterations to run. See // https://github.com/google/benchmark#cpu-timers, ->UseRealTime() // Report timing in milliseconds, which is the general order of magnitude // of model runs. The benchmark framework will print with precision // between 0 and 3 places after the decimal while aiming for three // significant digits. If we end up wanting precision beyond microseconds, // we can make this setting configurable with a custom command line flag. ->Unit(benchmark::kMillisecond); } Status GetModuleContentsFromFlags(std::string* out_contents) { IREE_TRACE_SCOPE0("GetModuleContentsFromFlags"); auto module_file = std::string(FLAG_module_file); if (module_file == "-") { *out_contents = std::string{std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>()}; } else { IREE_RETURN_IF_ERROR( file_io::GetFileContents(module_file.c_str(), out_contents)); } return OkStatus(); } // TODO(hanchung): Consider to refactor this out and reuse in iree-run-module. // This class helps organize required resources for IREE. The order of // construction and destruction for resources matters. And the lifetime of // resources also matters. The lifetime of IREEBenchmark should be as long as // ::benchmark::RunSpecifiedBenchmarks() where the resources are used during // benchmarking. class IREEBenchmark { public: IREEBenchmark() = default; ~IREEBenchmark() { IREE_TRACE_SCOPE0("IREEBenchmark::dtor"); // Order matters. inputs_.reset(); iree_vm_context_release(context_); iree_vm_module_release(hal_module_); iree_vm_module_release(input_module_); iree_hal_device_release(device_); iree_vm_instance_release(instance_); }; Status Register() { IREE_TRACE_SCOPE0("IREEBenchmark::Register"); if (!instance_ || !device_ || !hal_module_ || !context_ || !input_module_) { IREE_RETURN_IF_ERROR(Init()); } auto function_name = std::string(FLAG_entry_function); if (!function_name.empty()) { IREE_RETURN_IF_ERROR(RegisterSpecificFunction(function_name)); } else { IREE_RETURN_IF_ERROR(RegisterAllExportedFunctions()); } return iree::OkStatus(); } private: Status Init() { IREE_TRACE_SCOPE0("IREEBenchmark::Init"); IREE_TRACE_FRAME_MARK_BEGIN_NAMED("init"); IREE_RETURN_IF_ERROR(GetModuleContentsFromFlags(&module_data_)); IREE_RETURN_IF_ERROR(iree_hal_module_register_types()); IREE_RETURN_IF_ERROR( iree_vm_instance_create(iree_allocator_system(), &instance_)); // Create IREE's device and module. IREE_RETURN_IF_ERROR( iree::CreateDevice(std::string(FLAG_driver), &device_)); IREE_RETURN_IF_ERROR(CreateHalModule(device_, &hal_module_)); IREE_RETURN_IF_ERROR(LoadBytecodeModule(module_data_, &input_module_)); // Order matters. The input module will likely be dependent on the hal // module. std::array<iree_vm_module_t*, 2> modules = {hal_module_, input_module_}; IREE_RETURN_IF_ERROR(iree_vm_context_create_with_modules( instance_, modules.data(), modules.size(), iree_allocator_system(), &context_)); IREE_TRACE_FRAME_MARK_END_NAMED("init"); return iree::OkStatus(); } Status RegisterSpecificFunction(const std::string& function_name) { IREE_TRACE_SCOPE0("IREEBenchmark::RegisterSpecificFunction"); iree_vm_function_t function; IREE_RETURN_IF_ERROR(input_module_->lookup_function( input_module_->self, IREE_VM_FUNCTION_LINKAGE_EXPORT, iree_string_view_t{function_name.data(), function_name.size()}, &function)); IREE_RETURN_IF_ERROR(ValidateFunctionAbi(function)); // Construct inputs. std::vector<RawSignatureParser::Description> input_descs; IREE_RETURN_IF_ERROR(ParseInputSignature(function, &input_descs)); IREE_CHECK_OK(ParseToVariantList(input_descs, iree_hal_device_allocator(device_), FLAG_function_inputs, &inputs_)); // Creates output signature. std::vector<RawSignatureParser::Description> output_descs; IREE_RETURN_IF_ERROR(ParseOutputSignature(function, &output_descs)); RegisterModuleBenchmarks(function_name, context_, function, inputs_.get(), output_descs); return iree::OkStatus(); } Status RegisterAllExportedFunctions() { IREE_TRACE_SCOPE0("IREEBenchmark::RegisterAllExportedFunctions"); iree_vm_function_t function; iree_vm_module_signature_t signature = input_module_->signature(input_module_->self); for (iree_host_size_t i = 0; i < signature.export_function_count; ++i) { iree_string_view_t name; IREE_CHECK_OK(input_module_->get_function(input_module_->self, IREE_VM_FUNCTION_LINKAGE_EXPORT, i, &function, &name, nullptr)); if (!ValidateFunctionAbi(function).ok()) continue; std::string function_name(name.data, name.size); std::vector<RawSignatureParser::Description> input_descs; IREE_RETURN_IF_ERROR(ParseInputSignature(function, &input_descs)); if (!input_descs.empty()) { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "expect not to have input arguments for '%.*s'", (int)name.size, name.data); } std::vector<RawSignatureParser::Description> output_descs; IREE_RETURN_IF_ERROR(ParseOutputSignature(function, &output_descs)); iree::RegisterModuleBenchmarks(function_name, context_, function, /*inputs=*/nullptr, output_descs); } return iree::OkStatus(); } std::string module_data_; iree_vm_instance_t* instance_ = nullptr; iree_hal_device_t* device_ = nullptr; iree_vm_module_t* hal_module_ = nullptr; iree_vm_context_t* context_ = nullptr; iree_vm_module_t* input_module_ = nullptr; iree::vm::ref<iree_vm_list_t> inputs_; }; } // namespace } // namespace iree int main(int argc, char** argv) { IREE_TRACE_SCOPE0("main"); // Pass through flags to benchmark (allowing --help to fall through). iree_flags_parse_checked(IREE_FLAGS_PARSE_MODE_UNDEFINED_OK | IREE_FLAGS_PARSE_MODE_CONTINUE_AFTER_HELP, &argc, &argv); ::benchmark::Initialize(&argc, argv); IREE_CHECK_OK(iree_hal_register_all_available_drivers( iree_hal_driver_registry_default())); iree::IREEBenchmark iree_benchmark; auto status = iree_benchmark.Register(); if (!status.ok()) { std::cout << status << std::endl; return static_cast<int>(status.code()); } ::benchmark::RunSpecifiedBenchmarks(); return 0; }
11,625
3,790
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "llvm/Support/Debug.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/Utils.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { namespace { // Chosen randomly for now. We can measure and see what makes sense. constexpr int64_t kMaxRematerializedConstantSizeInBytes = 1 * 1024; // Returns true if the constant value is under a certain threshold. // This threshold is fixed for all backends as a value that is assumed small // enough to be worth inlining possibly several times (at the cost of binary // bloat). bool isConstantSmall(ConstantOp constantOp) { if (auto shapedType = constantOp.getType().dyn_cast<ShapedType>()) { return shapedType.getSizeInBits() / 8 <= kMaxRematerializedConstantSizeInBytes; } // Assume anything unshaped is small. This may not always be true in custom // dialects but is in std for now. return true; } // Returns true if the dispatch region is allowed to have constants inside. // Certain regions that may get replaced or turned into kernel imports shouldn't // have the constants moved into them as they'll just get lost. bool canDispatchRegionContainConstants(DispatchRegionOp dispatchRegionOp) { for (auto &block : dispatchRegionOp.body()) { for (auto &op : block) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (isa<xla_hlo::DotOp>(&op) || isa<xla_hlo::ConvOp>(&op)) { return false; } } } return true; } // Recursively clones the given |sourceOp| and returns the newly cloned op. Operation *recursivelyCloneOp(Operation *sourceOp, OpBuilder &builder, BlockAndValueMapping *mapping) { // Note that we dedupe required operands in the case of multiple arguments // coming from the same source operation. SmallPtrSet<Operation *, 4> operandOps; for (auto operand : sourceOp->getOperands()) { operandOps.insert(operand.getDefiningOp()); } for (auto *operandOp : operandOps) { recursivelyCloneOp(operandOp, builder, mapping); } return builder.clone(*sourceOp, *mapping); } // Clones the |sourceValue| op tree into |targetBlock|. // |mapping| is used to lookup existing values that may be present in the block // such as block arguments or already cloned ancestor ops. |mapping| will be // updated as the tree is cloned. Value cloneOpTreeIntoBlock(Value sourceValue, Block *targetBlock, BlockAndValueMapping *mapping) { // If the op has already been cloned we can just reuse that. // This happens if multiple arguments reference the same trees. if (auto existingValue = mapping->lookupOrNull(sourceValue)) { return existingValue; } OpBuilder builder(targetBlock); builder.setInsertionPointToStart(targetBlock); auto *sourceOp = sourceValue.getDefiningOp(); auto *clonedOp = recursivelyCloneOp(sourceOp, builder, mapping); // Return only the result matching our source value (in the case of multiple // results). int resultIndex = std::distance( sourceOp->result_begin(), std::find(sourceOp->result_begin(), sourceOp->result_end(), sourceValue)); return clonedOp->getResult(resultIndex); } // Inlines use of the given |value| from outside of a dispatch region to inside // of it and removes the argument. Supports multiple arguments that reference // |value| and will clone the entire value tree. LogicalResult inlineDispatchRegionOperandsUsingValue( DispatchRegionOp dispatchRegionOp, Value value) { // Find all args that are using this value. SmallVector<unsigned, 4> argIndices; for (auto arg : llvm::enumerate(dispatchRegionOp.args())) { if (arg.value() == value) { argIndices.push_back(arg.index()); } } if (argIndices.empty()) { // Not used? Wasteful call! return success(); } // Clone the value (and the ops required to create it) into the entry block. auto &entryBlock = dispatchRegionOp.body().getBlocks().front(); BlockAndValueMapping mapping; auto clonedValue = cloneOpTreeIntoBlock(value, &entryBlock, &mapping); // Replace all uses of the inner operand with the new value. for (unsigned argIndex : argIndices) { entryBlock.getArgument(argIndex).replaceAllUsesWith(clonedValue); } // Remove the dispatch region args and the block args that have been // replaced. for (unsigned argIndex : llvm::reverse(argIndices)) { dispatchRegionOp.getOperation()->eraseOperand( dispatchRegionOp.mapArgOperandToOpOperand(argIndex)); entryBlock.eraseArgument(argIndex); } return success(); } // Rematerializes a constant inside of all dispatch regions that use it. // Afterward the constant is only removed if there are no other uses within the // non-dispatch block (such as by sequencer ops). LogicalResult rematerializeConstantInDispatchRegions(ConstantOp constantOp) { Value constantValue = constantOp.getResult(); SmallVector<DispatchRegionOp, 4> usingRegionOps; for (auto *user : constantValue.getUsers()) { if (auto dispatchRegionOp = dyn_cast<DispatchRegionOp>(user)) { // Ensure this isn't just the workload and is used as an arg. if (std::find(dispatchRegionOp.args().begin(), dispatchRegionOp.args().end(), constantValue) != dispatchRegionOp.args().end()) { if (canDispatchRegionContainConstants(dispatchRegionOp)) { usingRegionOps.push_back(dispatchRegionOp); } } } } for (auto &dispatchRegionOp : usingRegionOps) { if (failed(inlineDispatchRegionOperandsUsingValue(dispatchRegionOp, constantValue))) { return failure(); } } // Remove if there are no other uses within the block. if (constantOp.use_empty()) { constantOp.erase(); } return success(); } } // namespace // Finds constant arguments to dispatch regions that are too small to be worth // putting into constant pools. This prevents things like a CSE'd scalar // constant of 0.0 being passed by reference to a bunch of regions. Later // backend-specific passes running on the dispatch regions may also be able to // improve their constant propagation chances by having the full constant value // available. // // Note that this currently only operates at the block level. Constants that are // pushed across branches are assumed to have been rematerialized within blocks // already, but if that isn't the case then this pass can be extended to do // that. class RematerializeDispatchConstantsPass : public FunctionPass<RematerializeDispatchConstantsPass> { public: void runOnFunction() override { for (auto &block : getFunction()) { SmallVector<ConstantOp, 8> smallConstantOps; for (auto constantOp : block.getOps<ConstantOp>()) { if (isConstantSmall(constantOp)) { smallConstantOps.push_back(constantOp); } } // Note: we iterate in reverse so that the rematerialized constants appear // in the same order they did originally (as insertion is at the top). for (auto constantOp : llvm::reverse(smallConstantOps)) { if (failed(rematerializeConstantInDispatchRegions(constantOp))) { return signalPassFailure(); } } } } }; std::unique_ptr<OpPassBase<FuncOp>> createRematerializeDispatchConstantsPass() { return std::make_unique<RematerializeDispatchConstantsPass>(); } static PassRegistration<RematerializeDispatchConstantsPass> pass( "iree-flow-rematerialize-dispatch-constants", "Rematerializes small previously-CSE'd constants into dispatch regions"); } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir
8,771
2,540
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd 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. */ #include "JTPacketSender.h" #include "IPnPort.h" #include "Vector.h" #include "Packet.h" #include "PacketQueue.h" JTPacketSender:: JTPacketSender( QueuedPacketSender::SendQueue& sendQueue, PacketQueue* jobQueue, uint32 tcpLimit, uint32 excludePort, const Vector& tcpTypes, bool verbose ): ModulePacketSender( sendQueue, tcpLimit ), m_jobQueue( jobQueue ), m_excludePort( excludePort ), m_tcpTypes( tcpTypes ), m_sum( 0 ), m_cnt( 0 ), m_verbose( verbose ) { } bool JTPacketSender::sendPacket( Packet* packet, const IPnPort& destination ) { const int printEveryNpacket = 1; if ( packet == NULL ) { mc2dbg << warn << "[JobThread] Reply packet is NULL!" << endl; return false; } if ( destination == IPnPort( 0, 0 ) ) { mc2log << warn << "[JobThread] Reply packet has invalid IP/port" << "(0:0) " << endl; delete packet; return false; } if (m_verbose && packet->getLength() < 0) { packet->dump(true); m_sum += TimeUtility::getCurrentMicroTime() - packet->getDebInfo(); if (m_cnt % printEveryNpacket == 0) { mc2log << info << "[JobThread] Time to process packet: " << m_sum/printEveryNpacket << endl; if (dynamic_cast<PacketQueue*>(m_jobQueue) != NULL) mc2log << info << "[JobThread] " << ((PacketQueue*)m_jobQueue)->getStatistics() << endl; m_sum = 0; } m_cnt++; } // exclude port from tcp send if ( m_excludePort == destination.getPort() ) { sendUDP( packet, destination ); return true; } // some packets wants to be sent via tcp if ( m_tcpTypes. binarySearch( packet->getSubType() ) < MAX_UINT32 ) { sendTCP( packet, destination ); return true; } return ModulePacketSender::sendPacket( packet, destination ); }
3,535
1,158
/*************************************************************************** * * $Id$ * **************************************************************************/ /** * @file $HeadURL$ * @author $Author$(hoping@baimashi.com) * @date $Date$ * @version $Revision$ * @brief * **/ #include <gumbo-query/Selector.h> #include <gumbo-query/QueryUtil.h> bool CSelector::match(GumboNode* apNode) { switch (mOp) { case EDummy: return true; case EEmpty: { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboVector children = apNode->v.element.children; for (unsigned int i = 0; i < children.length; i++) { GumboNode* child = (GumboNode*) children.data[i]; if (child->type == GUMBO_NODE_TEXT || child->type == GUMBO_NODE_ELEMENT) { return false; } } return true; } case EOnlyChild: { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboNode* parent = apNode->parent; if (parent == NULL) { return false; } unsigned int count = 0; for (unsigned int i = 0; i < parent->v.element.children.length; i++) { GumboNode* child = (GumboNode*) parent->v.element.children.data[i]; if (child->type != GUMBO_NODE_ELEMENT || (mOfType && apNode->v.element.tag == child->v.element.tag)) { continue; } count++; if (count > 1) { return false; } } return count == 1; } case ENthChild: { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboNode* parent = apNode->parent; if (parent == NULL) { return false; } unsigned int i = 0; unsigned int count = 0; for (unsigned int j = 0; j < parent->v.element.children.length; j++) { GumboNode* child = (GumboNode*) parent->v.element.children.data[j]; if (child->type != GUMBO_NODE_ELEMENT || (mOfType && apNode->v.element.tag == child->v.element.tag)) { continue; } count++; if (apNode == child) { i = count; if (!mLast) { break; } } } if (mLast) { i = count - i + 1; } i -= mB; if (mA == 0) { return i == 0; } return i % mA == 0 && i / mA > 0; } case ETag: return apNode->type == GUMBO_NODE_ELEMENT && apNode->v.element.tag == mTag; default: return false; } } std::vector<GumboNode*> CSelector::filter(std::vector<GumboNode*> nodes) { std::vector<GumboNode*> ret; for (std::vector<GumboNode*>::iterator it = nodes.begin(); it != nodes.end(); it++) { GumboNode* n = *it; if (match(n)) { ret.push_back(n); } } return ret; } std::vector<GumboNode*> CSelector::matchAll(GumboNode* apNode) { std::vector<GumboNode*> ret; matchAllInto(apNode, ret); return ret; } void CSelector::matchAllInto(GumboNode* apNode, std::vector<GumboNode*>& nodes) { if (match(apNode)) { nodes.push_back(apNode); } if (apNode->type != GUMBO_NODE_ELEMENT) { return; } for (unsigned int i = 0; i < apNode->v.element.children.length; i++) { GumboNode* child = (GumboNode*) apNode->v.element.children.data[i]; matchAllInto(child, nodes); } } CBinarySelector::CBinarySelector(TOperator aOp, CSelector* apS1, CSelector* apS2) { mpS1 = apS1; mpS1->retain(); mpS2 = apS2; mpS2->retain(); mOp = aOp; mAdjacent = false; } CBinarySelector::~CBinarySelector() { if (mpS1 != NULL) { mpS1->release(); mpS1 = NULL; } if (mpS2 != NULL) { mpS2->release(); mpS2 = NULL; } } CBinarySelector::CBinarySelector(CSelector* apS1, CSelector* apS2, bool aAdjacent) { mpS1 = apS1; mpS1->retain(); mpS2 = apS2; mpS2->retain(); mOp = EAdjacent; mAdjacent = aAdjacent; } bool CBinarySelector::match(GumboNode* apNode) { switch (mOp) { case EUnion: return mpS1->match(apNode) || mpS2->match(apNode); case EIntersection: return mpS1->match(apNode) && mpS2->match(apNode); case EChild: return mpS2->match(apNode) && apNode->parent != NULL && mpS1->match(apNode->parent); case EDescendant: { if (!mpS2->match(apNode)) { return false; } for (GumboNode* p = apNode->parent; p != NULL; p = p->parent) { if (mpS1->match(p)) { return true; } } return false; } case EAdjacent: { if (!mpS2->match(apNode)) { return false; } if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } size_t pos = apNode->index_within_parent; GumboNode* parent = apNode->parent; if (mAdjacent) { for (long i = pos; i >= 0; i--) { GumboNode* sibling = (GumboNode*) parent->v.element.children.data[i]; if (sibling->type == GUMBO_NODE_TEXT || sibling->type == GUMBO_NODE_COMMENT) { continue; } return mpS1->match(sibling); } return false; } for (long i = pos; i >= 0; i--) { GumboNode* sibling = (GumboNode*) parent->v.element.children.data[i]; if (mpS1->match(sibling)) { return true; } } return false; } default: return false; } return false; } CAttributeSelector::CAttributeSelector(TOperator aOp, std::string aKey, std::string aValue) { mKey = aKey; mValue = aValue; mOp = aOp; } bool CAttributeSelector::match(GumboNode* apNode) { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboVector attributes = apNode->v.element.attributes; for (unsigned int i = 0; i < attributes.length; i++) { GumboAttribute* attr = (GumboAttribute*) attributes.data[i]; if (mKey != attr->name) { continue; } std::string value = attr->value; switch (mOp) { case EExists: return true; case EEquals: return mValue == value; case EIncludes: for (unsigned int i = 0, j = 0; i < value.size(); i++) { if (value[i] == ' ' || value[i] == '\t' || value[i] == '\r' || value[i] == '\n' || value[i] == '\f' || i == value.size() - 1) { unsigned int length = i - j; if (i == value.size() - 1) { length++; } std::string segment = value.substr(j, length); if (segment == mValue) { return true; } j = i + 1; } } return false; case EDashMatch: if (mValue == value) { return true; } if (value.size() < mValue.size()) { return false; } return value.substr(0, mValue.size()) == mValue && value[mValue.size()] == '-'; case EPrefix: return value.size() >= mValue.size() && value.substr(0, mValue.size()) == mValue; case ESuffix: return value.size() >= mValue.size() && value.substr(value.size() - mValue.size(), mValue.size()) == mValue; case ESubString: return value.find(mValue) != std::string::npos; default: return false; } } return false; } CUnarySelector::CUnarySelector(TOperator aOp, CSelector* apS) { mpS = apS; mpS->retain(); mOp = aOp; } CUnarySelector::~CUnarySelector() { if (mpS != NULL) { mpS->release(); mpS = NULL; } } bool CUnarySelector::hasDescendantMatch(GumboNode* apNode, CSelector* apS) { for (unsigned int i = 0; i < apNode->v.element.children.length; i++) { GumboNode* child = (GumboNode*) apNode->v.element.children.data[i]; if (apS->match(child) || (child->type == GUMBO_NODE_ELEMENT && hasDescendantMatch(child, apS))) { return true; } } return false; } bool CUnarySelector::hasChildMatch(GumboNode* apNode, CSelector* apS) { for (unsigned int i = 0; i < apNode->v.element.children.length; i++) { GumboNode* child = (GumboNode*) apNode->v.element.children.data[i]; if (apS->match(child)) { return true; } } return false; } bool CUnarySelector::match(GumboNode* apNode) { switch (mOp) { case ENot: return !mpS->match(apNode); case EHasDescendant: if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } return hasDescendantMatch(apNode, mpS); case EHasChild: if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } return hasChildMatch(apNode, mpS); default: return false; } } bool CTextSelector::match(GumboNode* apNode) { std::string text; switch (mOp) { case EContains: text = CQueryUtil::nodeText(apNode); break; case EOwnContains: text = CQueryUtil::nodeOwnText(apNode); break; default: return false; } text = CQueryUtil::tolower(text); return text.find(mValue) != std::string::npos; } /* vim: set ts=4 sw=4 sts=4 tw=100 noet: */
8,377
4,002
/* * Buffer.cpp * * Created on: Sep 26, 2012 * Author: sofa1011 */ using namespace std; #include "../includes/Buffer.h" #include <iostream> #include <fstream> #include <stdlib.h> #include <unistd.h> Buffer::Buffer( int bufferSize) { size = bufferSize; buffer1 = new char[bufferSize]; buffer2 = new char[bufferSize]; next = buffer1; lastReadIndex = 0; fillUpBuffer(buffer1); } Buffer::~Buffer() { } char Buffer::getCurrentChar() { return *next; } char Buffer::getNextChar(){ char c; c= *next; if (*next == NULL) { if (next == &buffer1[(size-1)]) { fillUpBuffer(buffer2); next = buffer2; return getNextChar(); } else if (next == &buffer2[(size-1)]) { fillUpBuffer(buffer1); next = buffer1; return getNextChar(); } } else { next ++; } return c; } char Buffer::returnCurrentChar(){ char c; if (next == &buffer1[0]) { cout << "[Buffer]: Set pointer 'next' back to end of buffer2." << endl; next = &buffer2[(size-1)]; } else if (next == &buffer2[0]) { cout << "[Buffer]: Set pointer 'next' back to end of buffer1." << endl; next = &buffer2[(size-1)]; } else { next--; } c = *next; return c; } int Buffer::fillUpBuffer(char* bufferIndex) { ifstream is ("buffer-test-file.txt", ios::binary | ios::ate); if (is) { int length = is.tellg(); int distanceToRead; if((size-1) > (length - lastReadIndex)) { distanceToRead = (length - lastReadIndex); } else { distanceToRead = (size-1); } is.seekg (lastReadIndex, is.beg); is.read (bufferIndex, distanceToRead); bufferIndex[distanceToRead] = NULL; is.close(); lastReadIndex += distanceToRead; } return 0; } void Buffer::printDebugInfo() { cout << "[BUFFER-DEBUG-INFO]: The size of the buffer has been set to " << size << endl; cout << "[BUFFER-DEBUG-INFO]: Start-Address for buffer 1: " << ((void *) buffer1) << endl; cout << "[BUFFER-DEBUG-INFO]: Start-Address for buffer 2: " << ((void *) buffer2) << endl; cout << "[BUFFER-DEBUG-INFO]: Start-Address for next: " << ((void *) next ) << endl; } /** * For debug purposes. */ void Buffer::printCurrentDirectory() { char cwd[256]; getcwd(cwd, sizeof(cwd)); cout << endl; printf("[BUFFER-DEBUG-INFO]: Current working directory is: %s\n", cwd); }
2,257
888
/** * @file * * @brief Tests for the Backend builder class * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #define ELEKTRA_PLUGINSPEC_WITH_COMPARE #include <backendbuilder.hpp> #include <backend.hpp> #include <backends.hpp> #include <plugindatabase.hpp> #include <algorithm> #include <iostream> #include <string> #include <unordered_map> #include <gtest/gtest.h> #include <kdb.hpp> #include <kdbconfig.h> #include <kdbhelper.h> // We disable certain tests on ASAN enabled builds: https://travis-ci.org/sanssecours/elektra/jobs/418573941 #ifdef ENABLE_ASAN #define GTEST_DISABLE_ASAN(name) DISABLED_##name #else #define GTEST_DISABLE_ASAN(name) name #endif TEST (BackendBuilder, withDatabase) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["ordering"] = "c"; mpd->data[PluginSpec ("b")]["ordering"] = "c"; mpd->data[PluginSpec ("c")]["ordering"]; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("b")); bb.addPlugin (PluginSpec ("c")); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("b")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } TEST (BackendBuilder, withDatabaseIrrelevantDep) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["ordering"] = "d"; mpd->data[PluginSpec ("b")]["ordering"] = "d"; mpd->data[PluginSpec ("c")]["ordering"]; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("b")); bb.addPlugin (PluginSpec ("c")); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("b")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } TEST (MountBackendBuilder, basicAddRem) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("dump")); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } MountBackendBuilder bb; bb.addPlugin (PluginSpec ("resolver")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("dump")); EXPECT_TRUE (bb.validated ()); bb.remPlugin (PluginSpec ("dump")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("dump")); EXPECT_TRUE (bb.validated ()); } TEST (GTEST_DISABLE_ASAN (MountBackendBuilder), basicSort) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("glob")); b.addPlugin (PluginSpec ("keytometa")); b.addPlugin (PluginSpec ("augeas")); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } MountBackendBuilder bb; bb.addPlugin (PluginSpec ("resolver")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("keytometa")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("glob")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("augeas")); // std::cout << "Solution: "; // for (auto const & p : bb) std::cout << p.getName() << " "; // std::cout << std::endl; EXPECT_TRUE (bb.validated ()) << "Reordering not successful?"; } TEST (GTEST_DISABLE_ASAN (MountBackendBuilder), allSort) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("glob")); b.addPlugin (PluginSpec ("keytometa")); b.addPlugin (PluginSpec ("augeas")); // b.addPlugin (PluginSpec ("type")); // b.addPlugin (PluginSpec ("validation")); // b.addPlugin (PluginSpec ("struct", KeySet(5, *Key("user:/module", KEY_END), KS_END))); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } std::vector<std::string> permutation = { "augeas", "glob", "keytometa", "resolver" // , "type", "validation" }; do { // for (auto const & p : permutation) std::cout << p << " "; // std::cout << std::endl; MountBackendBuilder bb; bb.addPlugin (PluginSpec (permutation[0])); bb.addPlugin (PluginSpec (permutation[1])); bb.addPlugin (PluginSpec (permutation[2])); bb.addPlugin (PluginSpec (permutation[3])); // bb.addPlugin (PluginSpec (permutation[4])); // bb.addPlugin (PluginSpec (permutation[5])); // bb.addPlugin (PluginSpec (permutation[6])); // std::cout << "Solution: "; // for (auto const & p : bb) std::cout << p.getName() << " "; // std::cout << std::endl; EXPECT_TRUE (bb.validated ()) << "Reordering not successful?"; } while (std::next_permutation (permutation.begin (), permutation.end ())); } TEST (MountBackendBuilder, resolveNeeds) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("line")); b.addPlugin (PluginSpec ("null")); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } MountBackendBuilder bb; bb.addPlugin (PluginSpec ("resolver")); EXPECT_FALSE (bb.validated ()) << "resolver+null should be missing"; bb.addPlugin (PluginSpec ("line")); EXPECT_FALSE (bb.validated ()) << "null should be missing"; bb.resolveNeeds (); EXPECT_TRUE (bb.validated ()) << "Did not add null automatically"; } TEST (BackendBuilder, resolveDoubleNeeds) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "c v"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } TEST (BackendBuilder, resolveDoubleNeedsVirtual) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "v c"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; EXPECT_EQ (mpd->lookupInfo (PluginSpec ("c"), "provides"), "v"); EXPECT_EQ (mpd->lookupInfo (PluginSpec ("c", "v"), "provides"), "v"); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c", "v")) << "remember it was virtual"; } TEST (BackendBuilder, doubleAddWithConf) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "v c"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); bb.addPlugin (PluginSpec ("v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); EXPECT_EQ (bb.cbegin ()[3], PluginSpec ("c", "v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))) << "remember it was virtual"; bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); } TEST (BackendBuilder, doubleAddWithConfVirtual) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "v c"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("noresolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))); bb.addPlugin (PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("noresolver", "resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c", "v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))); EXPECT_EQ (bb.cbegin ()[3], PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); } TEST (BackendBuilder, directPluginLoading) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["plugins"] = "x a=b"; mpd->data[PluginSpec ("a")]["needs"] = "resolver"; mpd->data[PluginSpec ("x")]["provides"] = "x"; mpd->data[PluginSpec ("noresolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("a")); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("x", KeySet (2, *Key ("user:/a", KEY_VALUE, "b", KEY_END), KS_END))); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("noresolver", "resolver")); } TEST (BackendBuilder, metadata) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("r")]["metadata"] = "rename/toupper"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needMetadata ("rename/toupper"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("r")); } TEST (BackendBuilder, metadataTwo) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("r1")]["metadata"] = "rename/toupper"; mpd->data[PluginSpec ("r1")]["status"] = "unittest"; mpd->data[PluginSpec ("r2")]["metadata"] = "rename/toupper rename/tolower"; mpd->data[PluginSpec ("r2")]["status"] = "memleak"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needMetadata ("rename/toupper rename/tolower"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("r2")); } TEST (BackendBuilder, metadataTwoRev) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("r1")]["metadata"] = "rename/tolower"; // relevant mpd->data[PluginSpec ("r1")]["status"] = "unittest"; mpd->data[PluginSpec ("r2")]["metadata"] = "rename/toupper rename/tolower"; mpd->data[PluginSpec ("r2")]["status"] = "memleak"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needMetadata ("rename/tolower rename/toupper"); // order not relevant ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("r1")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("r2")); } TEST (BackendBuilder, manualNeeds) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("n"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); } TEST (BackendBuilder, manualNeedsProvides) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("x"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n", "x")); } TEST (BackendBuilder, manualMultipleNeeds) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("n"); bb.needPlugin ("n"); bb.needPlugin ("x"); bb.needPlugin ("x"); bb.needPlugin ("y"); bb.needPlugin ("y"); bb.needPlugin ("z"); bb.needPlugin ("z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, manualMultipleNeedsSingleLine) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("n n x x y y z z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, manualRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); } TEST (BackendBuilder, manualNoRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (false); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); } TEST (BackendBuilder, manualRecommendsProvides) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("x"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (true); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n", "x")); } TEST (BackendBuilder, manualMultipleRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n"); bb.recommendPlugin ("n"); bb.recommendPlugin ("x"); bb.recommendPlugin ("x"); bb.recommendPlugin ("y"); bb.recommendPlugin ("y"); bb.recommendPlugin ("z"); bb.recommendPlugin ("z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, manualMultipleRecommendsSingleLine) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n n x x y y z z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, resolveDoubleRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["recommends"] = "c v"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } static int checkconfLookup (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::Key * k = ckdb::ksLookupByName (config, "/a", 0); if (k) { return 0; } return -1; } TEST (BackendBuilder, checkconfOkNoChange) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfLookup); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; Key a; a.setName ("user:/a"); a.setString ("abc"); pluginConfig.append (a); spec.appendConfig (pluginConfig); bb.addPlugin (spec); } TEST (BackendBuilder, checkconfNotOKmissing) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf3")]["c"] = "something"; mpd->setCheckconfFunction (checkconfLookup); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); EXPECT_THROW (bb.addPlugin (PluginSpec ("checkconf3")), PluginConfigInvalid); } static int checkconfAppend (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::ksAppendKey (config, ckdb::keyNew ("user:/b", KEY_VALUE, "test", KEY_END)); return 1; } TEST (BackendBuilder, checkconfOkChanged) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfAppend); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; spec.appendConfig (pluginConfig); bb.addPlugin (spec); // we expect b to be added now spec = *bb.begin (); EXPECT_EQ (spec.getConfig ().get<std::string> ("user:/b"), "test"); } static int checkconfDelete (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::ksCopy (config, NULL); return 1; } TEST (BackendBuilder, checkconfOkRemovedPluginConfig) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfDelete); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; Key a; a.setName ("user:/a"); a.setString ("abc"); pluginConfig.append (a); spec.appendConfig (pluginConfig); bb.addPlugin (spec); // we expect a to be removed now spec = *bb.begin (); EXPECT_THROW (spec.getConfig ().get<std::string> ("user:/a"), KeyNotFoundException); } TEST (BackendBuilder, checkconfOkRemovedBackendConfig) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfDelete); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; spec.appendConfig (pluginConfig); KeySet backendConfig; Key b; b.setName ("system:/b"); b.setString ("xyz"); backendConfig.append (b); bb.setBackendConfig (backendConfig); bb.addPlugin (spec); // we expect b to be removed now spec = *bb.begin (); EXPECT_THROW (bb.getBackendConfig ().get<std::string> ("system:/b"), KeyNotFoundException); } static int checkconfAppendBackendConf (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::ksAppendKey (config, ckdb::keyNew ("system:/a", KEY_VALUE, "abc", KEY_END)); return 1; } TEST (BackendBuilder, checkconfOkAppendBackendConfig) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfAppendBackendConf); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; spec.appendConfig (pluginConfig); bb.addPlugin (spec); // we expect b to be added now spec = *bb.begin (); EXPECT_EQ (bb.getBackendConfig ().get<std::string> ("system:/a"), "abc"); }
22,786
8,813
// // Created by __author__ on 18/01/2022. // #include <FairWindSdk/settings/FairComboBox.hpp> #include <FairWindSdk/settings/FairLineEdit.hpp> #include <FairWindSdk/settings/FairCheckBox.hpp> #include <FairWindSdk/settings/DisplaysBrowser.hpp> #include <FairWindSdk/settings/LayersBrowser.hpp> #include "Settings.hpp" #include "MainPage.hpp" #include "general/General.hpp" #include "extensions/Extensions.hpp" namespace fairwind::apps::settings { // Called when the app is loaded void Settings::onCreate() { // Call the framework onCreate() FairWindApp::onCreate(); // Get the FairWind singleton auto fairWind = fairwind::FairWind::getInstance(); // Register settings pages inside the FairWind singleton fairWind->registerSettingsTab(new general::General()); //fairWind->registerSettingsTab(new Connections()); fairWind->registerSettingsTab(new extensions::Extensions()); } //Called by the FairWind framework when the app is invoked for the first time void Settings::onStart() { // Call the framework onCreate() FairWindApp::onStart(); // Create the main page auto mainPage = new MainPage(nullptr, this); // Add the main page to the app pages as root page add(mainPage); // Show the root page show(); } // Called when the app is going to be in foreground void Settings::onResume() { // Call the framework onResume() FairWindApp::onResume(); } // Called when the app is going to be in background void Settings::onPause() { // Call the framework onPause() FairWindApp::onPause(); } // Called when the app is going to be stopped void Settings::onStop() { // Call the framework on onStop() FairWindApp::onStop(); } // Called when the app is going to be unloaded once and forever void Settings::onDestroy() { // Call the framework onDestroy() FairWindApp::onDestroy(); } // Called when the app is going to be unloaded once and forever void Settings::onConfigChanged() { // Call the framework onDestroy() FairWindApp::onConfigChanged(); } } // fairwind::apps::settings
2,278
666
/* --------------------------------------------------------------------------- * * Matrix2x2 class - Michael Brandon Williams * * Matrix2x2.cpp * * --------------------------------------------------------------------------- */ #include "Matrix3x3.h" Matrix3x3::Matrix3x3() { elements[0][0] = 1; elements[0][1] = 0; elements[0][2] = 0; elements[1][0] = 0; elements[1][1] = 1; elements[1][2] = 0; elements[2][0] = 0; elements[2][1] = 0; elements[2][2] = 1; } // constructor for when this matrix is to be intialized with // the same elements as another matrix Matrix3x3::Matrix3x3 (const Matrix3x3 &M) { elements[0][0] = M.elements[0][0]; elements[0][1] = M.elements[0][1]; elements[0][2] = M.elements[0][2]; elements[1][0] = M.elements[1][0]; elements[1][1] = M.elements[1][1]; elements[1][2] = M.elements[1][2]; elements[2][0] = M.elements[2][0]; elements[2][1] = M.elements[2][1]; elements[2][2] = M.elements[2][2]; } Matrix3x3::~Matrix3x3() { } // accessor float Matrix3x3::_e (const int j, const int k) const { return (elements[j][k]); } float Matrix3x3::operator () (const int j, const int k) const { return (elements[j][k]); } // modifier void Matrix3x3::set_e (const int j, const int k, const float e) { elements[j][k] = e; } // assignment const Matrix3x3& Matrix3x3::operator = (const Matrix3x3 &M) { elements[0][0] = M.elements[0][0]; elements[0][1] = M.elements[0][1]; elements[0][2] = M.elements[0][2]; elements[1][0] = M.elements[1][0]; elements[1][1] = M.elements[1][1]; elements[1][2] = M.elements[1][2]; elements[2][0] = M.elements[2][0]; elements[2][1] = M.elements[2][1]; elements[2][2] = M.elements[2][2]; return (*this); } // tests for equality const bool Matrix3x3::operator == (const Matrix3x3 &M) const { return ((elements[0][0] == M.elements[0][0]) && (elements[0][1] == M.elements[0][1]) && (elements[0][2] == M.elements[0][2]) && (elements[1][0] == M.elements[1][0]) && (elements[1][1] == M.elements[1][1]) && (elements[1][2] == M.elements[1][2]) && (elements[2][0] == M.elements[2][0]) && (elements[2][1] == M.elements[2][1]) && (elements[2][2] == M.elements[2][2])); } // tests for inequality const bool Matrix3x3::operator != (const Matrix3x3 &M) const { return ((elements[0][0] != M.elements[0][0]) && (elements[0][1] != M.elements[0][1]) && (elements[0][2] != M.elements[0][2]) && (elements[1][0] != M.elements[1][0]) && (elements[1][1] != M.elements[1][1]) && (elements[1][2] != M.elements[1][2]) && (elements[2][0] != M.elements[2][0]) && (elements[2][1] != M.elements[2][1]) && (elements[2][2] != M.elements[2][2])); } // checks if the matrix is a zero matrix bool Matrix3x3::Zero_Matrix () const { return ((elements[0][0] == 0.0f) && (elements[0][1] == 0.0f) && (elements[0][2] == 0.0f) && (elements[1][0] == 0.0f) && (elements[1][1] == 0.0f) && (elements[1][2] == 0.0f) && (elements[2][0] == 0.0f) && (elements[2][1] == 0.0f) && (elements[2][2] == 0.0f)); } // checks if the matrix is an identity matrix bool Matrix3x3::Identity_Matrix () const { return ((elements[0][0] == 1.0f) && (elements[0][1] == 0.0f) && (elements[0][2] == 0.0f) && (elements[1][0] == 0.0f) && (elements[1][1] == 1.0f) && (elements[1][2] == 0.0f) && (elements[2][0] == 0.0f) && (elements[2][1] == 0.0f) && (elements[2][2] == 1.0f)); } // turns the matrix into an identity matrix void Matrix3x3::Set_Identity_Matrix () { elements[0][0] = elements[1][1] = elements[2][2] = 1.0f; elements[0][1] = elements[0][2] = 0.0f; elements[1][0] = elements[1][2] = 0.0f; elements[2][0] = elements[2][1] = 0.0f; } // addition (+) const Matrix3x3 Matrix3x3::operator + (const Matrix3x3 &M) const { Matrix3x3 temp; temp.elements[0][0] = elements[0][0] + M.elements[0][0]; temp.elements[0][1] = elements[0][1] + M.elements[0][1]; temp.elements[0][2] = elements[0][2] + M.elements[0][2]; temp.elements[1][0] = elements[1][0] + M.elements[1][0]; temp.elements[1][1] = elements[1][1] + M.elements[1][1]; temp.elements[1][2] = elements[1][2] + M.elements[1][2]; temp.elements[2][0] = elements[2][0] + M.elements[2][0]; temp.elements[2][1] = elements[2][1] + M.elements[2][1]; temp.elements[2][2] = elements[2][2] + M.elements[2][2]; return (temp); } // addition (+=) const Matrix3x3& Matrix3x3::operator += (const Matrix3x3 &M) { elements[0][0] += M.elements[0][0]; elements[0][1] += M.elements[0][1]; elements[0][2] += M.elements[0][2]; elements[1][0] += M.elements[1][0]; elements[1][1] += M.elements[1][1]; elements[1][2] += M.elements[1][2]; elements[2][0] += M.elements[2][0]; elements[2][1] += M.elements[2][1]; elements[2][2] += M.elements[2][2]; return (*this); } // subtraction (-) const Matrix3x3 Matrix3x3::operator - (const Matrix3x3 &M) const { Matrix3x3 temp; temp.elements[0][0] = elements[0][0] - M.elements[0][0]; temp.elements[0][1] = elements[0][1] - M.elements[0][1]; temp.elements[0][2] = elements[0][2] - M.elements[0][2]; temp.elements[1][0] = elements[1][0] - M.elements[1][0]; temp.elements[1][1] = elements[1][1] - M.elements[1][1]; temp.elements[1][2] = elements[1][2] - M.elements[1][2]; temp.elements[2][0] = elements[2][0] - M.elements[2][0]; temp.elements[2][1] = elements[2][1] - M.elements[2][1]; temp.elements[2][2] = elements[2][2] - M.elements[2][2]; return (temp); } // subtraction (-=) const Matrix3x3& Matrix3x3::operator -= (const Matrix3x3 &M) { elements[0][0] -= M.elements[0][0]; elements[0][1] -= M.elements[0][1]; elements[0][2] -= M.elements[0][2]; elements[1][0] -= M.elements[1][0]; elements[1][1] -= M.elements[1][1]; elements[1][2] -= M.elements[1][2]; elements[2][0] -= M.elements[2][0]; elements[2][1] -= M.elements[2][1]; elements[2][2] -= M.elements[2][2]; return (*this); } // multiplication (*) const Matrix3x3 Matrix3x3::operator * (const Matrix3x3 &M) const { Matrix3x3 temp; temp.elements[0][0] = (elements[0][0] * M.elements[0][0]) + (elements[0][1] * M.elements[1][0]) + (elements[0][2] * M.elements[2][0]); temp.elements[1][0] = (elements[1][0] * M.elements[0][0]) + (elements[1][1] * M.elements[1][0]) + (elements[1][2] * M.elements[2][0]); temp.elements[2][0] = (elements[2][0] * M.elements[0][0]) + (elements[2][1] * M.elements[1][0]) + (elements[2][2] * M.elements[2][0]); temp.elements[0][1] = (elements[0][0] * M.elements[0][1]) + (elements[0][1] * M.elements[1][1]) + (elements[0][2] * M.elements[2][1]); temp.elements[1][1] = (elements[1][0] * M.elements[0][1]) + (elements[1][1] * M.elements[1][1]) + (elements[1][2] * M.elements[2][1]); temp.elements[2][1] = (elements[2][0] * M.elements[0][1]) + (elements[2][1] * M.elements[1][1]) + (elements[2][2] * M.elements[2][1]); temp.elements[0][2] = (elements[0][0] * M.elements[0][2]) + (elements[0][1] * M.elements[1][2]) + (elements[0][2] * M.elements[2][2]); temp.elements[1][2] = (elements[1][0] * M.elements[0][2]) + (elements[1][1] * M.elements[1][2]) + (elements[1][2] * M.elements[2][2]); temp.elements[2][2] = (elements[2][0] * M.elements[0][2]) + (elements[2][1] * M.elements[1][2]) + (elements[2][2] * M.elements[2][2]); return (temp); } // multiplcation (*=) const Matrix3x3& Matrix3x3::operator *= (const Matrix3x3 &M) { Matrix3x3 temp; temp = *this * M; *this = temp; return (*this); } // scalar-multiplication (*) const Matrix3x3 Matrix3x3::operator * (const float s) const { Matrix3x3 M; M.elements[0][0] = elements[0][0] * s; M.elements[0][1] = elements[0][1] * s; M.elements[0][2] = elements[0][2] * s; M.elements[1][0] = elements[1][0] * s; M.elements[1][1] = elements[1][1] * s; M.elements[1][2] = elements[1][2] * s; M.elements[2][0] = elements[2][0] * s; M.elements[2][1] = elements[2][1] * s; M.elements[2][2] = elements[2][2] * s; return (M); } // scalar-multiplication (*=) const Matrix3x3& Matrix3x3::operator *= (const float s) { elements[0][0] *= s; elements[0][1] *= s; elements[0][2] *= s; elements[1][0] *= s; elements[1][1] *= s; elements[1][2] *= s; elements[2][0] *= s; elements[2][1] *= s; elements[2][2] *= s; return (*this); } // vector-multiplication (*) const Vector3D Matrix3x3::operator * (const Vector3D &V) const { Vector3D temp; temp.x = (V.x * elements[0][0]) + (V.y * elements[0][1]) + (V.z * elements[0][2]); temp.y = (V.x * elements[1][0]) + (V.y * elements[1][1]) + (V.z * elements[1][2]); temp.z = (V.x * elements[2][0]) + (V.y * elements[2][1]) + (V.z * elements[2][2]); return (temp); } // matrix-division (/) const Matrix3x3 Matrix3x3::operator / (const Matrix3x3 &M) const { return (*this * M.Inverse ()); } // matrix-division (/=) const Matrix3x3& Matrix3x3::operator /= (const Matrix3x3 &M) { return (*this = *this * M.Inverse ()); } // scalar-division (/) const Matrix3x3 Matrix3x3::operator / (const float s) const { Matrix3x3 temp; temp.elements[0][0] = elements[0][0] / s; temp.elements[0][1] = elements[0][1] / s; temp.elements[0][2] = elements[0][2] / s; temp.elements[1][0] = elements[1][0] / s; temp.elements[1][1] = elements[1][1] / s; temp.elements[1][2] = elements[1][2] / s; temp.elements[2][0] = elements[2][0] / s; temp.elements[2][1] = elements[2][1] / s; temp.elements[2][2] = elements[2][2] / s; return (temp); } // scalar-division (/=) const Matrix3x3& Matrix3x3::operator /= (const float s) { elements[0][0] /= s; elements[0][1] /= s; elements[0][2] /= s; elements[1][0] /= s; elements[1][1] /= s; elements[1][2] /= s; elements[2][0] /= s; elements[2][1] /= s; elements[2][2] /= s; return (*this); } // matrix to an integer power const Matrix3x3 Matrix3x3::operator ^ (const int p) const { Matrix3x3 temp; for (int j = 0; j < p; j++) { temp *= *this; } return (temp); } // fills the matrix with random elements void Matrix3x3::Random_Elements (const int min, const int max) { Random_Number generator; for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { elements[j][k] = float (generator.Random (min, max)); } } } // sets the elements of the matrix to create a rotation matrix around the x-axis void Matrix3x3::Rotation_Matrix_X (const float sine, const float cosine) { elements[0][0] = 1; elements[0][1] = 0; elements[0][2] = 0; elements[1][0] = 0; elements[1][1] = cosine; elements[1][2] = -sine; elements[2][0] = 0; elements[2][1] = sine; elements[2][2] = cosine; } // sets the elements of the matrix to create a rotation matrix around the y-axis void Matrix3x3::Rotation_Matrix_Y (const float sine, const float cosine) { elements[0][0] = cosine; elements[0][1] = 0; elements[0][2] = sine; elements[1][0] = 0; elements[1][1] = 1; elements[1][2] = 0; elements[2][0] = -sine; elements[2][1] = 0; elements[2][2] = cosine; } // sets the elements of the matrix to create a rotation matrix around the z-axis void Matrix3x3::Rotation_Matrix_Z (const float sine, const float cosine) { elements[0][0] = cosine; elements[0][1] = -sine; elements[0][2] = 0; elements[1][0] = sine; elements[1][1] = cosine; elements[1][2] = 0; elements[2][0] = 0; elements[2][1] = 0; elements[2][2] = 1; } // sets the elements of the matrix to create a rotation matrix around an arbitrary axis void Matrix3x3::Rotation_Matrix_Axis (const float sine, const float cosine, const Vector3D &A) { float t = 1 - cosine; elements[0][0] = t * A.x * A.x + cosine; elements[0][1] = t * A.x * A.y - sine * A.z; elements[0][2] = t * A.x * A.z + sine * A.y; elements[1][0] = t * A.y * A.x + sine * A.z; elements[1][1] = t * A.y * A.y + cosine; elements[1][2] = t * A.y * A.z - sine * A.x; elements[2][0] = t * A.z * A.x - sine * A.y; elements[2][1] = t * A.z * A.y + sine * A.x; elements[2][2] = t * A.z * A.z + cosine; } // returns the inverse of an orthonormal matrix Matrix3x3 Matrix3x3::Orthonormal_Inverse () const { return (this->Transpose ()); } // returns the transpose of this matrix Matrix3x3 Matrix3x3::Transpose () const { Matrix3x3 temp; temp.elements[0][0] = elements[2][2]; temp.elements[0][1] = elements[2][1]; temp.elements[0][2] = elements[2][0]; temp.elements[1][0] = elements[1][2]; temp.elements[1][1] = elements[1][1]; temp.elements[1][2] = elements[1][0]; temp.elements[2][0] = elements[0][2]; temp.elements[2][1] = elements[0][1]; temp.elements[2][2] = elements[0][0]; return (temp); } // returns the determinant of the matrix float Matrix3x3::operator ! () const { return ((elements[0][0] * (elements[1][1] * elements[2][2] - elements[1][2] * elements[2][1])) - (elements[0][1] * (elements[1][0] * elements[2][2] - elements[1][2] * elements[2][0])) + (elements[0][2] * (elements[1][0] * elements[2][1] - elements[2][0] * elements[1][1]))); } // returns the inverse of the matrix Matrix3x3 Matrix3x3::Inverse () const { float det = !*this; Matrix3x3 temp; temp.elements[0][0] = (elements[1][1] * elements[2][2] - elements[1][2] * elements[2][1]) / det; temp.elements[0][1] = -(elements[0][1] * elements[2][2] - elements[2][1] * elements[0][2]) / det; temp.elements[0][2] = (elements[0][1] * elements[1][2] - elements[1][1] * elements[0][2]) / det; temp.elements[1][0] = -(elements[1][0] * elements[2][2] - elements[1][2] * elements[2][0]) / det; temp.elements[1][1] = (elements[0][0] * elements[2][2] - elements[2][0] * elements[0][2]) / det; temp.elements[1][2] = -(elements[0][0] * elements[1][2] - elements[1][0] * elements[0][2]) / det; temp.elements[2][0] = (elements[1][0] * elements[2][1] - elements[2][0] * elements[1][1]) / det; temp.elements[2][1] = -(elements[0][0] * elements[2][1] - elements[2][0] * elements[0][1]) / det; temp.elements[2][2] = (elements[0][0] * elements[1][1] - elements[0][1] * elements[1][0]) / det; return (temp); } // prints the properties of the maitrx void Matrix3x3::Matrix_Print (const char* name) const { cout << name << " :" << endl; cout << "[ " << elements[0][0] << " " << elements[0][1] << " " << elements[0][2] << " ]" << endl; cout << "[ " << elements[1][0] << " " << elements[1][1] << " " << elements[1][2] << " ]" << endl; cout << "[ " << elements[2][0] << " " << elements[2][1] << " " << elements[2][2] << " ]" << endl; cout << endl; }
14,982
6,796
/* // Copyright (c) 2016 Intel Corporation // // 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 "fully_connected_kernel_base.h" #include "kernel_selector_utils.h" #include "common_tools.h" namespace KernelSelector { JitConstants FullyConnectedKernelBase::GetJitConstants(const FullyConnectedParams& params, const FullyConnectedKernelBase::DispatchData&) const { return MakeFullyConnectedJitConstants(params); } std::unique_ptr<FullyConnectedKernelBase::DispatchData> FullyConnectedKernelBase::SetDefault(const FullyConnectedParams& params) const { std::unique_ptr<DispatchData> dispatchData = std::make_unique<DispatchData>(); dispatchData->fp16UnitUsed = params.inputs[0].GetDType() == Datatype::F16; // Determine global work sizes. dispatchData->gws0 = params.output.LogicalSize(); dispatchData->gws1 = dispatchData->gws2 = 1; // Find largest positive local work size that is divider for global work size. dispatchData->lws0 = std::min(std::max(dispatchData->gws0, static_cast<size_t>(1)), static_cast<size_t>(32)); while (dispatchData->gws0 % dispatchData->lws0 != 0) { --dispatchData->lws0; } dispatchData->lws1 = dispatchData->lws2 = 1; return std::move(dispatchData); } KernelsData FullyConnectedKernelBase::GetCommonKernelsData(const Params& params, const OptionalParams& options, DataLayout dl, std::vector<WeightsLayout> wl, float estimated_time) const { if (!Validate(params, options) || wl.empty()) { return KernelsData(); } const auto& orgParams = static_cast<const FullyConnectedParams&>(params); const auto& orgOptParams = static_cast<const FullyConnectedOptionalParams&>(options); bool bProperInput = orgParams.inputs[0].GetLayout() == dl; if (!bProperInput && !orgParams.inputs[0].PitchesDifferFromLogicalDims()) { bProperInput = (dl == DataLayout::fb && orgParams.inputs[0].GetLayout() == DataLayout::fyxb) || (dl == DataLayout::bf && orgParams.inputs[0].GetLayout() == DataLayout::bfyx); } const bool bSupportedInput = orgOptParams.allowInputReordering || bProperInput; if (!bSupportedInput) { return KernelsData(); } KernelData kd = KernelData::Default<FullyConnectedParams>(params); FullyConnectedParams& newParams = *static_cast<FullyConnectedParams*>(kd.params.get()); if (!bProperInput) { newParams.inputs[0] = newParams.inputs[0].TransformIgnorePadding(dl); kd.reorderInput = true; } bool succeed = UpdateWeightsParams( newParams, options, wl, kd.weightsReorderParams); if (!succeed) { return{}; } kd.kernels.resize(1); auto entry_point = GetEntryPoint(kernelName, orgParams.layerID, options); const std::unique_ptr<DispatchData> runInfo = SetDefault(newParams); auto cldnn_jit = GetJitConstants(newParams, *runInfo.get()); std::string jit = CreateJit(kernelName, cldnn_jit, entry_point); auto& kernel = kd.kernels[0]; FillCLKernelData(kernel, *runInfo.get(), kernelName, jit, entry_point, ROUND_ROBIN, true, !orgParams.bias.empty()); kd.estimatedTime = estimated_time; kd.autoTuneIndex = -1; return{ kd }; } }
4,054
1,250
// IPCLog.hpp - IOS to PowerPC logging through IPC // Written by Palapeli // // Copyright (C) 2022 Team Saoirse // SPDX-License-Identifier: MIT #pragma once #include <System/OS.hpp> #include <System/Types.h> class IPCLog { public: static IPCLog* sInstance; static constexpr int printSize = 256; IPCLog(); void Run(); void Print(const char* buffer); void Notify(); void WaitForStartRequest(); protected: void HandleRequest(IOS::Request* req); Queue<IOS::Request*> m_ipcQueue; Queue<IOS::Request*> m_responseQueue; Queue<int> m_startRequestQueue; };
600
219
// Copyright 2019 The Fuchsia 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 "lib/vfs/cpp/service.h" #include <fidl/examples/echo/cpp/fidl.h> #include <lib/fdio/vfs.h> #include <lib/fidl/cpp/binding_set.h> #include "lib/gtest/real_loop_fixture.h" #include "lib/vfs/cpp/pseudo_dir.h" class ServiceTest : public gtest::RealLoopFixture, public fidl::examples::echo::Echo { void EchoString(fidl::StringPtr value, EchoStringCallback callback) override { callback(answer_); } protected: ServiceTest() : answer_("my_fake_ans"), service_name_("echo_service"), second_loop_(&kAsyncLoopConfigNoAttachToThread) { auto service = std::make_unique<vfs::Service>( bindings_.GetHandler(this, second_loop_.dispatcher())); dir_.Serve(0, dir_ptr_.NewRequest().TakeChannel(), second_loop_.dispatcher()); dir_.AddEntry(service_name_, std::move(service)); second_loop_.StartThread("vfs test thread"); } const std::string& answer() const { return answer_; } const std::string& service_name() const { return service_name_; } void AssertInValidOpen(uint32_t flag, uint32_t mode, zx_status_t expected_status) { SCOPED_TRACE("flag: " + std::to_string(flag) + ", mode: " + std::to_string(mode)); fuchsia::io::NodePtr node_ptr; dir_ptr()->Open(flag | fuchsia::io::OPEN_FLAG_DESCRIBE, mode, service_name(), node_ptr.NewRequest()); bool on_open_called = false; node_ptr.events().OnOpen = [&](zx_status_t status, std::unique_ptr<fuchsia::io::NodeInfo> unused) { EXPECT_FALSE(on_open_called); // should be called only once on_open_called = true; EXPECT_EQ(expected_status, status); }; ASSERT_TRUE(RunLoopUntil([&]() { return on_open_called; }, zx::msec(1))); } fuchsia::io::DirectoryPtr& dir_ptr() { return dir_ptr_; } private: std::string answer_; std::string service_name_; fidl::BindingSet<Echo> bindings_; vfs::PseudoDir dir_; fuchsia::io::DirectoryPtr dir_ptr_; async::Loop second_loop_; }; TEST_F(ServiceTest, CanOpenAsNodeReferenceAndTestGetAttr) { fuchsia::io::NodeSyncPtr ptr; dir_ptr()->Open(fuchsia::io::OPEN_FLAG_NODE_REFERENCE, 0, service_name(), ptr.NewRequest()); zx_status_t s; fuchsia::io::NodeAttributes attr; ptr->GetAttr(&s, &attr); EXPECT_EQ(ZX_OK, s); EXPECT_EQ(fuchsia::io::MODE_TYPE_SERVICE, attr.mode & fuchsia::io::MODE_TYPE_SERVICE); } TEST_F(ServiceTest, CanCloneNodeReference) { fuchsia::io::NodeSyncPtr cloned_ptr; { fuchsia::io::NodeSyncPtr ptr; dir_ptr()->Open(fuchsia::io::OPEN_FLAG_NODE_REFERENCE, 0, service_name(), ptr.NewRequest()); ptr->Clone(0, cloned_ptr.NewRequest()); } zx_status_t s; fuchsia::io::NodeAttributes attr; cloned_ptr->GetAttr(&s, &attr); EXPECT_EQ(ZX_OK, s); EXPECT_EQ(fuchsia::io::MODE_TYPE_SERVICE, attr.mode & fuchsia::io::MODE_TYPE_SERVICE); } TEST_F(ServiceTest, TestDescribe) { fuchsia::io::NodeSyncPtr ptr; dir_ptr()->Open(fuchsia::io::OPEN_FLAG_NODE_REFERENCE, 0, service_name(), ptr.NewRequest()); fuchsia::io::NodeInfo info; ptr->Describe(&info); EXPECT_TRUE(info.is_service()); } TEST_F(ServiceTest, CanOpenAsAService) { uint32_t flags[] = {0, fuchsia::io::OPEN_RIGHT_READABLE, fuchsia::io::OPEN_RIGHT_WRITABLE}; uint32_t modes[] = { 0, fuchsia::io::MODE_TYPE_SERVICE, V_IRWXU, V_IRUSR, V_IWUSR, V_IXUSR}; for (uint32_t mode : modes) { for (uint32_t flag : flags) { SCOPED_TRACE("flag: " + std::to_string(flag) + ", mode: " + std::to_string(mode)); fidl::examples::echo::EchoSyncPtr ptr; dir_ptr()->Open(flag, mode, service_name(), fidl::InterfaceRequest<fuchsia::io::Node>( ptr.NewRequest().TakeChannel())); fidl::StringPtr ans; ptr->EchoString("hello", &ans); EXPECT_EQ(answer(), ans); } } } TEST_F(ServiceTest, CannotOpenServiceWithInvalidFlags) { uint32_t flags[] = {fuchsia::io::OPEN_RIGHT_ADMIN, fuchsia::io::OPEN_FLAG_CREATE, fuchsia::io::OPEN_FLAG_CREATE_IF_ABSENT, fuchsia::io::OPEN_FLAG_TRUNCATE, fuchsia::io::OPEN_FLAG_APPEND, fuchsia::io::OPEN_FLAG_NO_REMOTE}; for (uint32_t flag : flags) { AssertInValidOpen(flag, 0, ZX_ERR_NOT_SUPPORTED); } AssertInValidOpen(fuchsia::io::OPEN_FLAG_DIRECTORY, 0, ZX_ERR_NOT_DIR); } TEST_F(ServiceTest, CannotOpenServiceWithInvalidMode) { uint32_t modes[] = { fuchsia::io::MODE_TYPE_DIRECTORY, fuchsia::io::MODE_TYPE_BLOCK_DEVICE, fuchsia::io::MODE_TYPE_FILE, fuchsia::io::MODE_TYPE_SOCKET}; for (uint32_t mode : modes) { AssertInValidOpen(0, mode, ZX_ERR_INVALID_ARGS); } }
5,049
1,879
// Copyright (c) OpenMMLab. All rights reserved. // clang-format off #include "catch.hpp" // clang-format on #include "mmdeploy/core/logger.h" #include "mmdeploy/core/model.h" #include "mmdeploy/core/model_impl.h" #include "test_resource.h" using namespace mmdeploy; TEST_CASE("model constructor", "[model]") { SECTION("default constructor") { Model model; REQUIRE(!model); } SECTION("explicit constructor with model path") { REQUIRE_THROWS(Model{"path/to/not/existing/model"}); } SECTION("explicit constructor with buffer") { REQUIRE_THROWS(Model{nullptr, 0}); } } TEST_CASE("model init", "[model]") { auto& gResource = MMDeployTestResources::Get(); for (auto& codebase : gResource.codebases()) { if (auto img_list = gResource.LocateImageResources(fs::path{codebase} / "images"); !img_list.empty()) { Model model; REQUIRE(model.Init(img_list.front()).has_error()); break; } } for (auto& codebase : gResource.codebases()) { for (auto& backend : gResource.backends()) { if (auto model_list = gResource.LocateModelResources(fs::path{codebase} / backend); !model_list.empty()) { Model model; REQUIRE(!model.Init(model_list.front()).has_error()); REQUIRE(!model.ReadFile("deploy.json").has_error()); auto const& meta = model.meta(); REQUIRE(!model.GetModelConfig(meta.models[0].name).has_error()); REQUIRE(model.GetModelConfig("not-existing-model").has_error()); break; } } } } TEST_CASE("ModelRegistry", "[model]") { class ANewModelImpl : public ModelImpl { Result<void> Init(const std::string& sdk_model_path) override { return Status(eNotSupported); } Result<std::string> ReadFile(const std::string& file_path) const override { return Status(eNotSupported); } Result<deploy_meta_info_t> ReadMeta() const override { deploy_meta_info_t meta; return meta; } }; // Test duplicated register. `DirectoryModel` is already registered. (void)ModelRegistry::Get().Register("DirectoryModel", []() -> std::unique_ptr<ModelImpl> { return std::make_unique<ANewModelImpl>(); }); }
2,175
719
#include <SPI.h> #include "LedMatrix.h" #define NUMBER_OF_DEVICES 1 #define CS_PIN PB8 SPIClass SPI_2(PA7, PA6, PA5); LedMatrix ledMatrix = LedMatrix(NUMBER_OF_DEVICES, CS_PIN); int x = 0; void setup() { ledMatrix.init(); ledMatrix.setIntensity(3); ledMatrix.setText("MAX7219 Animation Demo"); ledMatrix.setNextText("Second text"); } void loop() { ledMatrix.clear(); ledMatrix.scrollTextLeft(); ledMatrix.drawText(); ledMatrix.commit(); delay(50); x = x + 1; if (x == 400) { ledMatrix.setNextText("Third text"); } }
584
241
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2018. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medWidgets.h> namespace medWidgets { namespace pluginManager { void initialize(const QString& path, bool verbose) { for(QString const& realpath : path.split(';')) { if(realpath.isEmpty()) break; } } } namespace generic { namespace _private { medAbstractProcessPresenterFactory factory; } medAbstractProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace morphomathOperation { namespace erodeImage { namespace _private { medAbstractErodeImageProcessPresenterFactory factory; } medAbstractErodeImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace dilateImage { namespace _private { medAbstractDilateImageProcessPresenterFactory factory; } medAbstractDilateImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace openingImage { namespace _private { medAbstractOpeningImageProcessPresenterFactory factory; } medAbstractOpeningImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace closingImage { namespace _private { medAbstractClosingImageProcessPresenterFactory factory; } medAbstractClosingImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } } namespace arithmeticOperation { namespace addImage { namespace _private { medAbstractAddImageProcessPresenterFactory factory; } medAbstractAddImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace subtractImage { namespace _private { medAbstractSubtractImageProcessPresenterFactory factory; } medAbstractSubtractImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace multiplyImage { namespace _private { medAbstractMultiplyImageProcessPresenterFactory factory; } medAbstractMultiplyImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace divideImage { namespace _private { medAbstractDivideImageProcessPresenterFactory factory; } medAbstractDivideImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } } namespace maskImage { namespace _private { medAbstractMaskImageProcessPresenterFactory factory; } medAbstractMaskImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace dwiMasking { namespace _private { medAbstractDWIMaskingProcessPresenterFactory factory; } medAbstractDWIMaskingProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace diffusionModelEstimation { namespace _private { medAbstractDiffusionModelEstimationProcessPresenterFactory factory; } medAbstractDiffusionModelEstimationProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace diffusionScalarMaps { namespace _private { medAbstractDiffusionScalarMapsProcessPresenterFactory factory; } medAbstractDiffusionScalarMapsProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace tractography { namespace _private { medAbstractTractographyProcessPresenterFactory factory; } medAbstractTractographyProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace singleFilterOperation { namespace addFilter { namespace _private { medAbstractAddFilterProcessPresenterFactory factory; } medAbstractAddFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace divideFilter { namespace _private { medAbstractDivideFilterProcessPresenterFactory factory; } medAbstractDivideFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace gaussianFilter { namespace _private { medAbstractGaussianFilterProcessPresenterFactory factory; } medAbstractGaussianFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace invertFilter { namespace _private { medAbstractInvertFilterProcessPresenterFactory factory; } medAbstractInvertFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace medianFilter { namespace _private { medAbstractMedianFilterProcessPresenterFactory factory; } medAbstractMedianFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace multiplyFilter { namespace _private { medAbstractMultiplyFilterProcessPresenterFactory factory; } medAbstractMultiplyFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace normalizeFilter { namespace _private { medAbstractNormalizeFilterProcessPresenterFactory factory; } medAbstractNormalizeFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace shrinkFilter { namespace _private { medAbstractShrinkFilterProcessPresenterFactory factory; } medAbstractShrinkFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace subtractFilter { namespace _private { medAbstractSubtractFilterProcessPresenterFactory factory; } medAbstractSubtractFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace windowingFilter { namespace _private { medAbstractWindowingFilterProcessPresenterFactory factory; } medAbstractWindowingFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace imageDenoising { namespace _private { medAbstractImageDenoisingProcessPresenterFactory factory; } medAbstractImageDenoisingProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace relaxometryEstimation { namespace _private { medAbstractRelaxometryEstimationProcessPresenterFactory factory; } medAbstractRelaxometryEstimationProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace symmetryAlignment { namespace _private { medAbstractSymmetryPlaneAlignmentProcessPresenterFactory factory; } medAbstractSymmetryPlaneAlignmentProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace biasCorrection { namespace _private { medAbstractBiasCorrectionProcessPresenterFactory factory; } medAbstractBiasCorrectionProcessPresenterFactory& presenterFactory() { return _private::factory; } } } } // end of medWidgets
8,709
2,147
#include <iostream> #include <sstream> #include <ios> #include <iomanip> #include <functional> #include <algorithm> #include <vector> #include <string> #include <list> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <climits> #include <cctype> using namespace std; #define XINF INT_ma #define INF 0x3FFFFFFF #define MP(X,Y) make_pair(X,Y) #define PB(X) push_back(X) #define REP(X,N) for(int X=0;X<N;X++) #define REP2(X,L,R) for(int X=L;X<=R;X++) #define DEP(X,R,L) for(int X=R;X>=L;X--) #define CLR(A,X) memset(A,X,sizeof(A)) #define INF 0x3FFFFFFF #define IT iterator typedef long long ll; typedef pair<int,int> PII; typedef vector<PII> VII; typedef vector<int> VI; //const int maN = 10010; int T; int n; double ma,mi,num,sum,ave; int main(){ cin>>T; while(T--){ cin>>n; mi = 1000; ma = -1000; num = 0;sum = 0;ave = 0; REP(i,n) { cin>>num; if(mi>num){mi = num;} if(ma<num){ma = num;} sum += num; } printf("%.2lf,%.2lf,%.2lf\n",mi,ma,(sum - mi - ma)/(n-2)); } return 0; }
1,152
587
#include <bits/stdc++.h> using namespace std; #define endll "\n" int baseTwo(int n){ int left,a[100]; left=n; int i=0; while(left>0){ a[i+1]=left%2; left=left/2; i++; a[0]= left==1? 0:1 ; } for(int j=i;j>0;j--){ cout<<a[j]; } } main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); for(int i=0;i<4;i++){ baseTwo(i); cout << endll; } }
377
221
#include "stack.hpp" #include <stack> #include <vector> #include <deque> # define G "\e[92m\e[1m" # define D "\e[39m\e[0m" # define R "\e[91m" # define Y "\e[93m" int main() { try { /****** CONSTRUCTOR ********/ { std::cout << Y "My constructor\n" D; std::deque<int> mydeque1 (3,100); // deque with 3 elements std::vector<int> myvector1 (2,200); // vector with 2 elements ft::stack<int> first1; // empty stack ft::stack<int, std::deque<int> > second1(mydeque1); // stack initialized to copy of deque ft::stack<int,std::vector<int> > third1; // empty stack using vector ft::stack<int,std::vector<int> > fourth1 (myvector1); std::cout << "size of first: " << first1.size() << '\n'; std::cout << "size of second: " << second1.size() << '\n'; std::cout << "size of third: " << third1.size() << '\n'; std::cout << "size of fourth: " << fourth1.size() << '\n'; std::cout << Y"\nOriginal constructor\n"D; std::deque<int> origdeque (3,100); // deque with 3 elements std::vector<int> origvector (2,200); // vector with 2 elements std::stack<int> first; // empty stack std::stack<int> second (origdeque); // stack initialized to copy of deque std::stack<int,std::vector<int> > third; // empty stack using vector std::stack<int,std::vector<int> > fourth (origvector); std::cout << "size of first: " << first.size() << '\n'; std::cout << "size of second: " << second.size() << '\n'; std::cout << "size of third: " << third.size() << '\n'; std::cout << "size of fourth: " << fourth.size() << '\n'; } { std::cout << Y"My member function\n"D; std::stack<char> myStack; std::cout << "myStack empty = " << myStack.empty() << std::endl; myStack.push('A'); myStack.push('B'); myStack.push('C'); std::cout << "myStack empty = " << myStack.empty() << std::endl; std::cout << "size of myStack: " << myStack.size() << '\n'; std::cout << "top = " << myStack.top() << '\n'; myStack.top() += 5; //change top element + 5 std::cout << "top = " << myStack.top() << '\n'; myStack.pop(); std::cout << "After metod pop\n"; std::cout << "size of myStack: " << myStack.size() << '\n'; std::cout << "top = " << myStack.top() << '\n'; std::cout << "size of myStack: " << myStack.size() << '\n'; std::cout << Y"Original member function\n"D; std::stack<char> origStack; std::cout << "origStack empty = " << origStack.empty() << std::endl; origStack.push('A'); origStack.push('B'); origStack.push('C'); std::cout << "origStack empty = " << origStack.empty() << std::endl; std::cout << "size of origStack: " << origStack.size() << '\n'; std::cout << "top = " << origStack.top() << '\n'; origStack.top() += 5; std::cout << "top = " << origStack.top() << '\n'; origStack.pop(); std::cout << "After metod pop\n"; std::cout << "size of origStack: " << origStack.size() << '\n'; std::cout << "top = " << origStack.top() << '\n'; std::cout << "size of origStack: " << origStack.size() << '\n'; } { std::cout <<Y "My non-member function\n" D; ft::stack<int> myStack1; myStack1.push(5); ft::stack<int> myStack2; myStack1.push(3); std::cout << "'==' = " << (myStack1 == myStack2) << "\n"; std::cout << "'!=' = " << (myStack1 != myStack2) << "\n"; std::cout << "'>' = " << (myStack1 > myStack2) << "\n"; std::cout << "'>=' = " << (myStack1 >= myStack2) << "\n"; std::cout << "'<' = " << (myStack1 < myStack2) << "\n"; std::cout << "'<=' = " << (myStack1 == myStack2) << "\n"; std::cout <<Y "Original non-member function\n" D; std::stack<int> origStack1; origStack1.push(5); std::stack<int> origStack2; origStack2.push(3); std::cout << "'==' = " << (origStack1 == origStack2) << "\n"; std::cout << "'!=' = " << (origStack1 != origStack2) << "\n"; std::cout << "'>' = " << (origStack1 > origStack2) << "\n"; std::cout << "'>=' = " << (origStack1 >= origStack2) << "\n"; std::cout << "'<' = " << (origStack1 < origStack2) << "\n"; std::cout << "'<=' = " << (origStack1 == origStack2) << "\n"; std::cout << Y"Now you can check memory leaks, with leaks a.out in other terminal" << D"\n"; std::cout << G"To exit press Enter" << D"\n"; getchar(); std::cout << G"Good bye" << D"\n"; } } catch(const char * e) { std::cerr << e << '\n'; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
5,358
1,739
/****************************************************************************** Copyright 2017-2019 object_database Authors 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. ******************************************************************************/ #pragma once #include "DatabaseConnectionState.hpp" #include "HashFunctions.hpp" #include <unordered_set> #include <unordered_map> /********** Views provide running (native)python threads with a snapshotted view of the current object-database's subscribed data. A view holds a reference to a collection of objects that have different representation at different transaction_ids, along with a single transaction_id. We show a coherent view of all the objects whose versions are <= the given transaction_id. We also track all objects and indices we read or write during execution. ***********/ class View { public: View(std::shared_ptr<DatabaseConnectionState> connection, transaction_id tid, bool allowWrites) : m_tid(tid), m_allow_writes(allowWrites), m_enclosing_view(nullptr), m_is_entered(false), m_ever_entered(false), m_versioned_objects(*connection->getVersionedObjects()), m_connection_state(connection) { m_connection_state->increfVersion(m_tid); m_serialization_context = m_connection_state->getContext(); } ~View() { if (!m_ever_entered) { m_connection_state->decrefVersion(m_tid); } } void setSerializationContext(std::shared_ptr<SerializationContext> context) { m_serialization_context = context; } std::shared_ptr<SerializationContext> getSerializationContext() { return m_serialization_context; } void enter() { if (m_is_entered || m_ever_entered) { throw std::runtime_error("Can't enter a view twice."); } m_ever_entered = true; m_is_entered = true; m_enclosing_view = s_current_view; s_current_view = this; } static View* currentView() { return s_current_view; } void exit() { if (!m_is_entered) { throw std::runtime_error("Can't exit an un-entered view."); } m_is_entered = false; s_current_view = m_enclosing_view; m_enclosing_view = nullptr; m_connection_state->decrefVersion(m_tid); } bool objectIsVisible(SchemaAndTypeName objType, object_id oid) { return m_connection_state->objectIsVisible(objType, oid, m_tid); } void loadLazyObjectIfNeeded(object_id oid) { m_connection_state->loadLazyObjectIfNeeded(oid); } void newObject(SchemaAndTypeName obType, object_id oid) { m_connection_state->markObjectSubscribed(obType, oid, m_tid); } // lookup the current value of an object. if we have written to it, use that value. // otherwise use the value in the view. If the value does not exist, returns a null pointer. // we also record what values were read instance_ptr getField(field_id field, object_id oid, Type* t, bool recordAccess=true) { auto delete_it = m_delete_cache.find(std::make_pair(field, oid)); if (delete_it != m_delete_cache.end()) { return nullptr; } auto write_it = m_write_cache.find(std::make_pair(field, oid)); if (write_it != m_write_cache.end()) { return write_it->second.data(); } instance_ptr i = m_versioned_objects.bestObjectVersion(t, m_serialization_context, field, oid, m_tid).first; if (recordAccess) { m_read_values.insert(std::make_pair(field, oid)); } return i; } bool fieldExists(field_id field, object_id oid, Type* t, bool recordAccess=true) { auto delete_it = m_delete_cache.find(std::make_pair(field, oid)); if (delete_it != m_delete_cache.end()) { return false; } auto write_it = m_write_cache.find(std::make_pair(field, oid)); if (write_it != m_write_cache.end()) { return true; } bool res = m_versioned_objects.existsAtTransaction(t, field, oid, m_tid); if (recordAccess) { m_read_values.insert(std::make_pair(field, oid)); } return res; } void setField(field_id field, object_id oid, Type* t, instance_ptr data) { if (!m_allow_writes) { throw std::runtime_error("Please use a transaction if you wish to write to object_database fields."); } auto delete_it = m_delete_cache.find(std::make_pair(field, oid)); if (delete_it != m_delete_cache.end()) { throw std::runtime_error("Value is deleted."); } if (data) { //if we're writing a new value, record whether this is a new object //that we're populating into 'm_new_writes' bool existsAlready = fieldExists(field, oid, t, false); if (!existsAlready) { m_new_writes.insert(std::make_pair(field, oid)); } m_write_cache[std::make_pair(field, oid)] = Instance(data, t); } else { bool wasNewWrite = m_new_writes.find(std::make_pair(field, oid)) != m_new_writes.end(); m_write_cache.erase(std::make_pair(field, oid)); if (!wasNewWrite) { //if the object already existed, we need to mark that we're deleting it m_delete_cache.insert(std::make_pair(field, oid)); } } } void indexAdd(field_id fid, index_value i, object_id o) { IndexKey key(fid, i); //check if we are adding something back to an index it was removed from already auto remove_it = m_set_removes.find(key); if (remove_it != m_set_removes.end()) { auto it = remove_it->second.find(o); if (it != remove_it->second.end()) { remove_it->second.erase(it); return; } } if (m_versioned_objects.indexContains(fid, i, m_tid, o)) { throw std::runtime_error("Index already contains this value."); } m_set_adds[key].insert(o); } void indexRemove(field_id fid, index_value i, object_id o) { IndexKey key(fid, i); //check if we are adding something back to an index it was removed from already auto add_it = m_set_adds.find(key); if (add_it != m_set_adds.end()) { auto it = add_it->second.find(o); if (it != add_it->second.end()) { add_it->second.erase(it); return; } } if (!m_versioned_objects.indexContains(fid, i, m_tid, o)) { throw std::runtime_error("Index doesn't contain this value."); } m_set_removes[key].insert(o); } bool shouldSuppressIndexValue(field_id fid, index_value i, object_id o) { auto remove_it = m_set_removes.find(IndexKey(fid, i)); if (remove_it == m_set_removes.end()) { return false; } return remove_it->second.find(o) != remove_it->second.end(); } object_id firstAddedIndexValue(field_id fid, index_value i) { auto add_it = m_set_adds.find(IndexKey(fid, i)); if (add_it == m_set_adds.end()) { return NO_OBJECT; } if (add_it->second.size() == 0) { return NO_OBJECT; } return *add_it->second.begin(); } object_id nextAddedIndexValue(field_id fid, index_value i, object_id o) { auto add_it = m_set_adds.find(IndexKey(fid, i)); if (add_it == m_set_adds.end()) { return NO_OBJECT; } auto next_ob_it = add_it->second.upper_bound(o); if (next_ob_it == add_it->second.end()) { return NO_OBJECT; } return *next_ob_it; } object_id indexLookupFirst(field_id fid, index_value i) { m_set_reads.insert(IndexKey(fid, i)); //we need to suppress anything in 'm_set_removes' and add anything in 'm_set_adds' object_id first = m_versioned_objects.indexLookupFirst(fid, i, m_tid); object_id firstAdded = firstAddedIndexValue(fid, i); if (first == NO_OBJECT) { return firstAdded; } //loop until we find a value in the main set that's lower than 'firstAdded' while (true) { if (firstAdded != NO_OBJECT && firstAdded < first) { return firstAdded; } if (!shouldSuppressIndexValue(fid, i, first)) { return first; } first = m_versioned_objects.indexLookupNext(fid, i, m_tid, first); if (first == NO_OBJECT) { return firstAdded; } } } object_id indexLookupNext(field_id fid, index_value i, object_id o) { m_set_reads.insert(IndexKey(fid, i)); object_id next = m_versioned_objects.indexLookupNext(fid, i, m_tid, o); object_id nextAdded = nextAddedIndexValue(fid, i, o); if (next == NO_OBJECT) { return nextAdded; } //loop until we find a value in the main set that's lower than 'firstAdded' while (true) { if (nextAdded != NO_OBJECT && nextAdded < next) { return nextAdded; } if (!shouldSuppressIndexValue(fid, i, next)) { return next; } next = m_versioned_objects.indexLookupNext(fid, i, m_tid, next); if (next == NO_OBJECT) { return nextAdded; } } } DatabaseConnectionState& getConnectionState() { return *m_connection_state; } bool isWriteable() const { return m_allow_writes; } const std::unordered_set<std::pair<field_id, object_id> >& getReadValues() const { return m_read_values; } const std::unordered_map<std::pair<field_id, object_id>, Instance>& getWriteCache() const { return m_write_cache; } const std::unordered_set<std::pair<field_id, object_id> >& getDeleteCache() const { return m_delete_cache; } const std::unordered_map<IndexKey, std::set<object_id> >& getSetAdds() const { return m_set_adds; } const std::unordered_map<IndexKey, std::set<object_id> >& getSetRemoves() const { return m_set_removes; } const std::unordered_set<IndexKey >& getSetReads() const { return m_set_reads; } transaction_id getTransactionId() const { return m_tid; } private: static thread_local View* s_current_view; //the transaction id that snapshots this view transaction_id m_tid; //is this a view or a transaction? bool m_allow_writes; View* m_enclosing_view; bool m_is_entered; bool m_ever_entered; std::unordered_set<std::pair<field_id, object_id> > m_read_values; std::unordered_map<std::pair<field_id, object_id>, Instance> m_write_cache; std::unordered_set<std::pair<field_id, object_id> > m_new_writes; std::unordered_set<std::pair<field_id, object_id> > m_delete_cache; std::unordered_map<IndexKey, std::set<object_id> > m_set_adds; std::unordered_map<IndexKey, std::set<object_id> > m_set_removes; std::unordered_set<IndexKey > m_set_reads; VersionedObjects& m_versioned_objects; std::shared_ptr<DatabaseConnectionState> m_connection_state; std::shared_ptr<SerializationContext> m_serialization_context; };
11,551
3,843
// Copyright (c) 2013-2020 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: https://opensource.org/licenses/AFL-3.0 #pragma once namespace hg { // Allow us to represent the game's version in a major.minor.micro format struct GameVersion { int major; int minor; int micro; [[nodiscard]] constexpr bool operator<( const GameVersion& rhs) const noexcept { if(major != rhs.major) { return major < rhs.major; } if(minor != rhs.minor) { return minor < rhs.minor; } return micro < rhs.micro; } [[nodiscard]] constexpr bool operator==( const GameVersion& other) const noexcept { return (major == other.major) && (minor == other.minor) && (micro == other.micro); } [[nodiscard]] constexpr bool operator!=( const GameVersion& other) const noexcept { return !(*this == other); } }; inline constexpr GameVersion GAME_VERSION{2, 1, 4}; inline constexpr auto& GAME_VERSION_STR = "2.1.4"; } // namespace hg
1,121
368
// IOStream_T.cpp,v 4.20 2000/04/19 02:49:34 brunsch Exp #ifndef ACE_IOSTREAM_T_C #define ACE_IOSTREAM_T_C #include "ace/IOStream_T.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ ACE_RCSID(ace, IOStream_T, "IOStream_T.cpp,v 4.20 2000/04/19 02:49:34 brunsch Exp") #if !defined (ACE_LACKS_ACE_IOSTREAM) #if defined (ACE_HAS_MINIMUM_IOSTREAMH_INCLUSION) && defined (__GNUG__) # if !defined (ACE_IOSTREAM_T_H) // _Only_ define this when compiling this .cpp file standalone, not // when instantiating templates. Its purpose is to provide something // for global constructors and destructors to be tied to. Without it, // they would be tied to the file(name). With Cygnus g++ 2.7.2/VxWorks, // that name is used directly in variable names in the munched ctor/dtor // file. That name contains a ".", so it's not a legal C variable name. // The root of all this trouble is a static instance (of Iostream_init) // declared in the iostream.h header file. int ACE_IOStream_global_of_builtin_type_to_avoid_munch_problems = 0; # endif /* ! ACE_IOSTREAM_T_H */ #endif /* ACE_HAS_MINIMUM_IOSTREAMH_INCLUSION && __GNUG__ */ #if !defined (__ACE_INLINE__) #include "ace/IOStream_T.i" #endif /* !__ACE_INLINE__ */ // We will be given a STREAM by the iostream object which creates us. // See the ACE_IOStream template for how that works. Like other // streambuf objects, we can be input-only, output-only or both. template <class STREAM> ACE_Streambuf_T<STREAM>::ACE_Streambuf_T (STREAM *peer, u_int streambuf_size, int io_mode) : ACE_Streambuf (streambuf_size, io_mode), peer_ (peer) { // A streambuf allows for unbuffered IO where every character is // read as requested and written as provided. To me, this seems // terribly inefficient for socket-type operations, so I've disabled // it. All of the work would be done by the underflow/overflow // functions anyway and I haven't implemented anything there to // support unbuffered IO. #if !defined (ACE_LACKS_UNBUFFERED_STREAMBUF) this->unbuffered (0); #endif /* ! ACE_LACKS_UNBUFFERED_STREAMBUF */ // Linebuffered is similar to unbuffered. Again, I don't have any // need for this and I don't see the advantage. I believe this // would have to be supported by underflow/overflow to be effective. #if !defined (ACE_LACKS_LINEBUFFERED_STREAMBUF) this->linebuffered (0); #endif /* ! ACE_LACKS_LINEBUFFERED_STREAMBUF */ } // The typical constructor. This will initiailze your STREAM and then // setup the iostream baseclass to use a custom streambuf based on // STREAM. template <class STREAM> ACE_IOStream<STREAM>::ACE_IOStream (STREAM &stream, u_int streambuf_size) : iostream (0), STREAM (stream) { ACE_NEW (streambuf_, ACE_Streambuf_T<STREAM> ((STREAM *) this, streambuf_size)); iostream::init (this->streambuf_); } template <class STREAM> ACE_IOStream<STREAM>::ACE_IOStream (u_int streambuf_size) : iostream (0) { ACE_NEW (this->streambuf_, ACE_Streambuf_T<STREAM> ((STREAM *) this, streambuf_size)); iostream::init (this->streambuf_); } // We have to get rid of the streambuf_ ourselves since we gave it to // iostream () template <class STREAM> ACE_IOStream<STREAM>::~ACE_IOStream (void) { delete this->streambuf_; } // The only ambituity in the multiple inheritance is the close () // function. template <class STREAM> int ACE_IOStream<STREAM>::close (void) { return STREAM::close (); } template <class STREAM> ACE_IOStream<STREAM> & ACE_IOStream<STREAM>::operator>> (ACE_Time_Value *&tv) { ACE_Time_Value *old_tv = this->streambuf_->recv_timeout (tv); tv = old_tv; return *this; } #if defined (ACE_HAS_STRING_CLASS) // A simple string operator. The base iostream has 'em for char* but // that isn't always the best thing for a String. If we don't provide // our own here, we may not get what we want. template <class STREAM> ACE_IOStream<STREAM> & ACE_IOStream<STREAM>::operator>> (ACE_IOStream_String &v) { if (ipfx0 ()) { char c; this->get (c); for (v = c; this->get (c) && !isspace (c); v += c) continue; } isfx (); return *this; } template <class STREAM> ACE_IOStream<STREAM> & ACE_IOStream<STREAM>::operator<< (ACE_IOStream_String &v) { if (opfx ()) { #if defined (ACE_WIN32) && defined (_MSC_VER) for (int i = 0; i < v.GetLength (); ++i) #else for (u_int i = 0; i < (u_int) v.length (); ++i) #endif /* ACE_WIN32 && defined (_MSC_VER) */ this->put (v[i]); } osfx (); return *this; } // A more clever put operator for strings that knows how to deal with // quoted strings containing back-quoted quotes. template <class STREAM> STREAM & operator>> (STREAM &stream, ACE_Quoted_String &str) { char c; if (!(stream >> c)) // eat space up to the first char // stream.set (ios::eofbit|ios::failbit); return stream; str = ""; // Initialize the string // if we don't have a quote, append until we see space if (c != '"') for (str = c; stream.get (c) && !isspace (c); str += c) continue; else for (; stream.get (c) && c != '"'; str += c) if (c == '\\') { stream.get (c); if (c != '"') str += '\\'; } return stream; } template <class STREAM> STREAM & operator<< (STREAM &stream, ACE_Quoted_String &str) { stream.put ('"'); for (u_int i = 0; i < str.length (); ++i) { if (str[i] == '"') stream.put ('\\'); stream.put (str[i]); } stream.put ('"'); return stream; } #endif /* ACE_HAS_STRING_CLASS */ #endif /* ACE_LACKS_ACE_IOSTREAM */ #endif /* ACE_IOSTREAM_T_C */
6,153
2,304
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> using namespace std; vector<string> split(const string &s, char delim) { vector<string> elems; stringstream ss; string item; ss.str(s); while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } int main() { string cadena; vector<string> beverages; ifstream fe("data.in"); while(!fe.eof()) { getline(fe, cadena); beverages = split(cadena, ' '); } fe.close(); return 0; }
568
209
#include <gtest/gtest.h> #include "lcd/backlight/Backlight.h" #include "hardware/lcd/MockBacklightDriver.h" #include "freertos/MockThread.h" int main( int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } TEST( BacklightConstructor, Create ) { hardware::lcd::MockBacklightDriver mockBacklightDriver; const lcd::Backlight backlight( mockBacklightDriver ); SUCCEED(); }
432
155
// Copyright 2015 The Chromium OS 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 "attestation/server/pkcs11_key_store.h" #include <map> #include <string> #include <vector> #include <base/logging.h> #include <base/strings/string_number_conversions.h> #include <chaps/attributes.h> #include <chaps/chaps_proxy_mock.h> #include <chaps/token_manager_client_mock.h> #include <brillo/cryptohome.h> #include <brillo/map_utils.h> #include <gmock/gmock.h> #include <gtest/gtest.h> using ::testing::_; using ::testing::DoAll; using ::testing::Invoke; using ::testing::NiceMock; using ::testing::Return; using ::testing::SetArgPointee; namespace { const uint64_t kSession = 7; // Arbitrary non-zero value. const char kDefaultUser[] = "test_user"; const char kValidRsaPublicKeyHex[] = "3082010A0282010100" "961037BC12D2A298BEBF06B2D5F8C9B64B832A2237F8CF27D5F96407A6041A4D" "AD383CB5F88E625F412E8ACD5E9D69DF0F4FA81FCE7955829A38366CBBA5A2B1" "CE3B48C14B59E9F094B51F0A39155874C8DE18A0C299EBF7A88114F806BE4F25" "3C29A509B10E4B19E31675AFE3B2DA77077D94F43D8CE61C205781ED04D183B4" "C349F61B1956C64B5398A3A98FAFF17D1B3D9120C832763EDFC8F4137F6EFBEF" "46D8F6DE03BD00E49DEF987C10BDD5B6F8758B6A855C23C982DDA14D8F0F2B74" "E6DEFA7EEE5A6FC717EB0FF103CB8049F693A2C8A5039EF1F5C025DC44BD8435" "E8D8375DADE00E0C0F5C196E04B8483CC98B1D5B03DCD7E0048B2AB343FFC11F" "0203" "010001"; const char kValidRsaCertificateHex[] = "3082040f308202f7a003020102020900bd0f8fd6bf496b67300d06092a864886" "f70d01010b050030819d310b3009060355040613025553311330110603550408" "0c0a43616c69666f726e69613116301406035504070c0d4d6f756e7461696e20" "5669657731133011060355040a0c0a4368726f6d69756d4f533111300f060355" "040b0c08556e6974546573743117301506035504030c0e506b637331314b6579" "53746f72653120301e06092a864886f70d010901161174657374406368726f6d" "69756d2e6f7267301e170d3135303231383137303132345a170d313731313133" "3137303132345a30819d310b3009060355040613025553311330110603550408" "0c0a43616c69666f726e69613116301406035504070c0d4d6f756e7461696e20" "5669657731133011060355040a0c0a4368726f6d69756d4f533111300f060355" "040b0c08556e6974546573743117301506035504030c0e506b637331314b6579" "53746f72653120301e06092a864886f70d010901161174657374406368726f6d" "69756d2e6f726730820122300d06092a864886f70d01010105000382010f0030" "82010a0282010100a8fb9e12b1e5298b9a24fabc3901d00c32057392c763836e" "0b55cff8e67d39b9b9853920fd615688b3e13c03a10cb5668187819172d1d269" "70f0ff8d4371ac581f6970a0e43a1d0d61a94741a771fe86aee45ab0ca059b1f" "c067f7416f08544cc4d08ec884b6d4327bb3ec0dc0789639375bd159df0efd87" "1cf4d605778c7a68c96b94cf0a6c29f9a23bc027e8250084eb2dfca817b20f57" "a6fe09513f884389db7b90788aea70c6e1638f24e39553ac0f859e585965c425" "9ed7b9680fde3e059f254d8c9494f6ab425ede80d63366dfcb7cc311f5bc6fb0" "1c27d81f4c5112d04b7614c37ba19c014916816372c773e4e44564fac34565ad" "ebf38fe56c1413170203010001a350304e301d0603551d0e04160414fe13c7db" "459bd2881e9113198e1f072e16cea144301f0603551d23041830168014fe13c7" "db459bd2881e9113198e1f072e16cea144300c0603551d13040530030101ff30" "0d06092a864886f70d01010b05000382010100a163d636ac64bd6f67eca53708" "5f92abc993a40fd0c0222a56b262c29f88057a3edf9abac024756ad85d7453d8" "4782e0be65d176aecfb0fbfc88ca567d17124fa190cb5ce832264360dd6daee1" "e121428de28dda0b8ba117a1be3cf438efd060a3b5fc812e7eba70cec12cb609" "738fc7d0912546c42b5aaadb142adce2167c7f30cd9e0049687d384334335aff" "72aebd1745a0aac4be816365969347f064f36f7fdec69f970f28b87061650470" "c63be8475bb23d0485985fb77c7cdd9d9fe008211a9ddd0fe68efb0b47cf629c" "941d31e3c2f88e670e7e4ef1129febad000e6a16222779fbfe34641e5243ca38" "74e2ad06f9585a00bec014744d3175ecc4808d"; constexpr char kValidEccPublicKeyHex[] = "3059301306072A8648CE3D020106082A8648CE3D030107034200045C9633047E7518B3E0DF" "6C019BAA7CC8D0CB1F18DB781B382E02273054A304CCBEEAD2ED273DA1D6FCDFAB8B55DE4E" "830FF43899F82DB6104381615992542F3D"; constexpr char kValidEccCertificateHex[] = "3082032930820211a00302010202160174fb9852da9f991b7fd47ebd190000000000001418" "300d06092a864886f70d01010505003081853120301e060355040313175072697661637920" "434120496e7465726d65646961746531123010060355040b13094368726f6d65204f533113" "3011060355040a130a476f6f676c6520496e63311630140603550407130d4d6f756e746169" "6e2056696577311330110603550408130a43616c69666f726e6961310b3009060355040613" "025553301e170d3230313030363034313032395a170d3232313030363034313032395a303d" "31183016060355040b130f73746174653a646576656c6f7065723121301f060355040a1318" "4368726f6d652044657669636520456e74657270726973653059301306072a8648ce3d0201" "06082a8648ce3d030107034200045c9633047e7518b3e0df6c019baa7cc8d0cb1f18db781b" "382e02273054a304ccbeead2ed273da1d6fcdfab8b55de4e830ff43899f82db61043816159" "92542f3da381a030819d30290603551d0e04220420837f40ecb000f7ffccda6dab8cd526d9" "43b6fe8ce56c84be5dc70cd3ed8f7410302b0603551d23042430228020f420b6d9d862f68b" "0915ce8b57a4fc574eb8c17ca5f9e656dbd0529429bd6d7f300e0603551d0f0101ff040403" "020780300c0603551d130101ff0402300030110603551d20040a300830060604551d200030" "12060a2b06010401d679020113040404020802300d06092a864886f70d0101050500038201" "010028a2e3a90c10a850cbee4e575da068bee21753212cc551b0f09eb327a15df01dffec87" "2509dedf06c9f34a5e9c987fb5c0d0878a400056c082f015d3153159a38dd71b6dd73e8dad" "2f1ce6ac43ed7cf550e8627b5d21dcf41661fcbc58075be7993b8cd7c06941b712ae052609" "6a20e559c9fb0cf3da807d261563cdddc74c18998ebd2859b26156d0c8bee2784dc8d6aeff" "d5400331466bdec5f6384cdad7f5e5eb620a246eb0e0ac8624e2f76d70207a4574adb53277" "4974ef08aedfb8dd3c05979b126414d17a7c1ad5bbc13f0bf95b1cded312837839aa344979" "151dc4f70ad86c842091d305a9b667b4e4bd67d6b2e3aa1df385a09553ae2028c9f18b45"; std::string HexDecode(const std::string hex) { std::vector<uint8_t> output; CHECK(base::HexStringToBytes(hex, &output)); return std::string(reinterpret_cast<char*>(output.data()), output.size()); } class ScopedFakeSalt { public: ScopedFakeSalt() : salt_(128, 0) { brillo::cryptohome::home::SetSystemSalt(&salt_); } ~ScopedFakeSalt() { brillo::cryptohome::home::SetSystemSalt(nullptr); } private: std::string salt_; }; class ScopedDisableVerboseLogging { public: ScopedDisableVerboseLogging() : original_severity_(logging::GetMinLogLevel()) { logging::SetMinLogLevel(logging::LOG_INFO); } ~ScopedDisableVerboseLogging() { logging::SetMinLogLevel(original_severity_); } private: logging::LogSeverity original_severity_; }; } // namespace namespace attestation { typedef chaps::ChapsProxyMock Pkcs11Mock; // Implements a fake PKCS #11 object store. Labeled data blobs can be stored // and later retrieved. The mocked interface is ChapsInterface so these // tests must be linked with the Chaps PKCS #11 library. The mock class itself // is part of the Chaps package; it is reused here to avoid duplication (see // chaps_proxy_mock.h). class KeyStoreTest : public testing::Test { public: KeyStoreTest() : pkcs11_(false), // Do not pre-initialize the mock PKCS #11 library. // This just controls whether the first call to // C_Initialize returns 'already initialized'. next_handle_(1) {} ~KeyStoreTest() override = default; void SetUp() override { std::vector<uint64_t> slot_list = {0, 1}; ON_CALL(pkcs11_, GetSlotList(_, _, _)) .WillByDefault(DoAll(SetArgPointee<2>(slot_list), Return(0))); ON_CALL(pkcs11_, OpenSession(_, _, _, _)) .WillByDefault(DoAll(SetArgPointee<3>(kSession), Return(0))); ON_CALL(pkcs11_, CloseSession(_, _)).WillByDefault(Return(0)); ON_CALL(pkcs11_, CreateObject(_, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::CreateObject)); ON_CALL(pkcs11_, DestroyObject(_, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::DestroyObject)); ON_CALL(pkcs11_, GetAttributeValue(_, _, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::GetAttributeValue)); ON_CALL(pkcs11_, SetAttributeValue(_, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::SetAttributeValue)); ON_CALL(pkcs11_, FindObjectsInit(_, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::FindObjectsInit)); ON_CALL(pkcs11_, FindObjects(_, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::FindObjects)); ON_CALL(pkcs11_, FindObjectsFinal(_, _)).WillByDefault(Return(0)); base::FilePath system_path("/var/lib/chaps"); ON_CALL(token_manager_, GetTokenPath(_, 0, _)) .WillByDefault(DoAll(SetArgPointee<2>(system_path), Return(true))); base::FilePath user_path( brillo::cryptohome::home::GetDaemonStorePath(kDefaultUser, "chaps")); ON_CALL(token_manager_, GetTokenPath(_, 1, _)) .WillByDefault(DoAll(SetArgPointee<2>(user_path), Return(true))); } // Stores a new labeled object, only CKA_LABEL and CKA_VALUE are relevant. virtual uint32_t CreateObject(const brillo::SecureBlob& isolate, uint64_t session_id, const std::vector<uint8_t>& attributes, uint64_t* new_object_handle) { *new_object_handle = next_handle_++; std::string label = GetValue(attributes, CKA_LABEL); handles_[*new_object_handle] = label; values_[label] = GetValue(attributes, CKA_VALUE); labels_[label] = *new_object_handle; return CKR_OK; } // Deletes a labeled object. virtual uint32_t DestroyObject(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t object_handle) { std::string label = handles_[object_handle]; handles_.erase(object_handle); values_.erase(label); labels_.erase(label); return CKR_OK; } // Supports reading CKA_VALUE. virtual uint32_t GetAttributeValue(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t object_handle, const std::vector<uint8_t>& attributes_in, std::vector<uint8_t>* attributes_out) { std::string label = handles_[object_handle]; std::string value = values_[label]; chaps::Attributes parsed; parsed.Parse(attributes_in); if (parsed.num_attributes() == 1 && parsed.attributes()[0].type == CKA_LABEL) value = label; if (parsed.num_attributes() != 1 || (parsed.attributes()[0].type != CKA_VALUE && parsed.attributes()[0].type != CKA_LABEL) || (parsed.attributes()[0].pValue && parsed.attributes()[0].ulValueLen != value.size())) return CKR_GENERAL_ERROR; parsed.attributes()[0].ulValueLen = value.size(); if (parsed.attributes()[0].pValue) memcpy(parsed.attributes()[0].pValue, value.data(), value.size()); parsed.Serialize(attributes_out); return CKR_OK; } // Supports writing CKA_VALUE. virtual uint32_t SetAttributeValue(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t object_handle, const std::vector<uint8_t>& attributes) { values_[handles_[object_handle]] = GetValue(attributes, CKA_VALUE); return CKR_OK; } // Finds stored objects by CKA_LABEL or CKA_VALUE. If no CKA_LABEL or // CKA_VALUE, find all objects. virtual uint32_t FindObjectsInit(const brillo::SecureBlob& isolate, uint64_t session_id, const std::vector<uint8_t>& attributes) { std::string label = GetValue(attributes, CKA_LABEL); std::string value = GetValue(attributes, CKA_VALUE); found_objects_.clear(); if (label.empty() && value.empty()) { // Find all objects. found_objects_ = brillo::GetMapKeysAsVector(handles_); } else if (!label.empty() && labels_.count(label) > 0) { // Find only the object with |label|. found_objects_.push_back(labels_[label]); } else { // Find all objects with |value|. for (const auto& item : values_) { if (item.second == value && labels_.count(item.first) > 0) { found_objects_.push_back(labels_[item.first]); } } } return CKR_OK; } // Reports a 'found' object based on find_status_. virtual uint32_t FindObjects(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t max_object_count, std::vector<uint64_t>* object_list) { while (!found_objects_.empty() && object_list->size() < max_object_count) { object_list->push_back(found_objects_.back()); found_objects_.pop_back(); } return CKR_OK; } protected: NiceMock<Pkcs11Mock> pkcs11_; NiceMock<chaps::TokenManagerClientMock> token_manager_; private: // A helper to pull the value for a given attribute out of a serialized // template. std::string GetValue(const std::vector<uint8_t>& attributes, CK_ATTRIBUTE_TYPE type) { chaps::Attributes parsed; parsed.Parse(attributes); CK_ATTRIBUTE_PTR array = parsed.attributes(); for (CK_ULONG i = 0; i < parsed.num_attributes(); ++i) { if (array[i].type == type) { if (!array[i].pValue) return ""; return std::string(reinterpret_cast<char*>(array[i].pValue), array[i].ulValueLen); } } return ""; } std::map<std::string, std::string> values_; // The fake store: label->value std::map<uint64_t, std::string> handles_; // The fake store: handle->label std::map<std::string, uint64_t> labels_; // The fake store: label->handle std::vector<uint64_t> found_objects_; // The most recent search results uint64_t next_handle_; // Tracks handle assignment ScopedFakeSalt fake_system_salt_; // We want to avoid all the Chaps verbose logging. ScopedDisableVerboseLogging no_verbose_logging; DISALLOW_COPY_AND_ASSIGN(KeyStoreTest); }; // This test assumes that chaps in not available on the system running the test. // The purpose of this test is to exercise the C_Initialize failure code path. // Without a mock, the Chaps library will attempt to connect to the Chaps daemon // unsuccessfully, resulting in a C_Initialize failure. TEST(KeyStoreTest_NoMock, Pkcs11NotAvailable) { chaps::TokenManagerClient token_manager; Pkcs11KeyStore key_store(&token_manager); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_FALSE(key_store.Write(kDefaultUser, "test", blob)); EXPECT_FALSE(key_store.Read("", "test", &blob)); EXPECT_FALSE(key_store.Write("", "test", blob)); } // Exercises the key store when PKCS #11 returns success. This exercises all // non-error-handling code paths. TEST_F(KeyStoreTest, Pkcs11Success) { Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_EQ("test_data", blob); // Try with a different key name. EXPECT_FALSE(key_store.Read(kDefaultUser, "test2", &blob)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test2", "test_data2")); EXPECT_TRUE(key_store.Read(kDefaultUser, "test2", &blob)); EXPECT_EQ("test_data2", blob); // Read the original key again. EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_EQ("test_data", blob); // Replace key data. EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data3")); EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_EQ("test_data3", blob); // Delete key data. EXPECT_TRUE(key_store.Delete(kDefaultUser, "test2")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test2", &blob)); EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); } TEST_F(KeyStoreTest, Pkcs11Success_NoUser) { Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Read("", "test", &blob)); EXPECT_TRUE(key_store.Write("", "test", "test_data")); EXPECT_TRUE(key_store.Read("", "test", &blob)); EXPECT_EQ("test_data", blob); // Try with a different key name. EXPECT_FALSE(key_store.Read("", "test2", &blob)); EXPECT_TRUE(key_store.Write("", "test2", "test_data2")); EXPECT_TRUE(key_store.Read("", "test2", &blob)); EXPECT_EQ("test_data2", blob); // Read the original key again. EXPECT_TRUE(key_store.Read("", "test", &blob)); EXPECT_EQ("test_data", blob); // Replace key data. EXPECT_TRUE(key_store.Write("", "test", "test_data3")); EXPECT_TRUE(key_store.Read("", "test", &blob)); EXPECT_EQ("test_data3", blob); // Delete key data. EXPECT_TRUE(key_store.Delete("", "test2")); EXPECT_FALSE(key_store.Read("", "test2", &blob)); EXPECT_TRUE(key_store.Read("", "test", &blob)); } // Tests the key store when PKCS #11 has no token for the given user. TEST_F(KeyStoreTest, TokenNotAvailable) { EXPECT_CALL(token_manager_, GetTokenPath(_, _, _)) .WillRepeatedly(Return(false)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_FALSE(key_store.Write(kDefaultUser, "test", blob)); EXPECT_FALSE(key_store.Read("", "test", &blob)); EXPECT_FALSE(key_store.Write("", "test", blob)); } // Tests the key store when PKCS #11 fails to open a session. TEST_F(KeyStoreTest, NoSession) { EXPECT_CALL(pkcs11_, OpenSession(_, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 fails to create an object. TEST_F(KeyStoreTest, CreateObjectFail) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 fails to read attribute values. TEST_F(KeyStoreTest, ReadValueFail) { EXPECT_CALL(pkcs11_, GetAttributeValue(_, _, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 fails to delete key data. TEST_F(KeyStoreTest, DeleteValueFail) { EXPECT_CALL(pkcs11_, DestroyObject(_, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Write(kDefaultUser, "test", "test_data2")); EXPECT_FALSE(key_store.Delete(kDefaultUser, "test")); } // Tests the key store when PKCS #11 fails to find objects. Tests each part of // the multi-part find operation individually. TEST_F(KeyStoreTest, FindFail) { EXPECT_CALL(pkcs11_, FindObjectsInit(_, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_CALL(pkcs11_, FindObjectsInit(_, _, _)).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(pkcs11_, FindObjects(_, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_CALL(pkcs11_, FindObjects(_, _, _, _)).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(pkcs11_, FindObjectsFinal(_, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 successfully finds zero objects. TEST_F(KeyStoreTest, FindNoObjects) { std::vector<uint64_t> empty; EXPECT_CALL(pkcs11_, FindObjects(_, _, _, _)) .WillRepeatedly(DoAll(SetArgPointee<3>(empty), Return(CKR_OK))); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } TEST_F(KeyStoreTest, RegisterKeyWithoutCertificate) { Pkcs11KeyStore key_store(&token_manager_); // Try with a malformed public key. EXPECT_FALSE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", "bad_pubkey", "")); // Try with a well-formed public key. std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(2) // Public, private (no certificate). .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterKeyWithCertificate) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); std::string certificate_der = HexDecode(kValidRsaCertificateHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); // Also try with the system token. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); } TEST_F(KeyStoreTest, RegisterEccKeyWithoutCertificate) { Pkcs11KeyStore key_store(&token_manager_); // Try with a malformed public key. EXPECT_FALSE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", "bad_pubkey", "")); // Try with a well-formed public key. std::string public_key_der = HexDecode(kValidEccPublicKeyHex); EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(2) // Public, private (no certificate). .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterEccKeyWithCertificate) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidEccPublicKeyHex); std::string certificate_der = HexDecode(kValidEccCertificateHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); // Also try with the system token. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); } TEST_F(KeyStoreTest, RegisterKeyWithBadCertificate) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "bad_certificate")); } TEST_F(KeyStoreTest, RegisterWithWrongKeyType) { Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_FALSE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterDecryptionKey) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)).WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_DECRYPT, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterCertificate) { Pkcs11KeyStore key_store(&token_manager_); std::string certificate_der = HexDecode(kValidRsaCertificateHex); EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(2); // Once for valid, once for invalid. // Try with a valid certificate (hit multiple times to check dup logic). EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); // Try with an invalid certificate. EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, "bad_certificate")); } TEST_F(KeyStoreTest, RegisterCertificateError) { Pkcs11KeyStore key_store(&token_manager_); std::string certificate_der = HexDecode(kValidRsaCertificateHex); // Handle an error from PKCS #11. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .WillOnce(Return(CKR_GENERAL_ERROR)); EXPECT_FALSE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); } TEST_F(KeyStoreTest, RegisterCertificateSystemToken) { Pkcs11KeyStore key_store(&token_manager_); std::string certificate_der = HexDecode(kValidRsaCertificateHex); // Try with the system token. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)).WillOnce(Return(CKR_OK)); EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); } // Tests that the DeleteByPrefix() method removes the correct objects and only // the correct objects. TEST_F(KeyStoreTest, DeleteByPrefix) { Pkcs11KeyStore key_store(&token_manager_); // Test with no keys. ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); // Test with a single matching key. ASSERT_TRUE(key_store.Write(kDefaultUser, "prefix_test", "test")); ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "prefix_test", &blob)); // Test with a single non-matching key. ASSERT_TRUE(key_store.Write(kDefaultUser, "_prefix_", "test")); ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); EXPECT_TRUE(key_store.Read(kDefaultUser, "_prefix_", &blob)); // Test with an empty prefix. ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "")); EXPECT_FALSE(key_store.Read(kDefaultUser, "_prefix_", &blob)); // Test with multiple matching and non-matching keys. const int kNumKeys = 110; // Pkcs11KeyStore max is 100 for FindObjects. key_store.Write(kDefaultUser, "other1", "test"); for (int i = 0; i < kNumKeys; ++i) { std::string key_name = std::string("prefix") + base::NumberToString(i); key_store.Write(kDefaultUser, key_name, std::string(key_name)); } ASSERT_TRUE(key_store.Write(kDefaultUser, "other2", "test")); ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); EXPECT_TRUE(key_store.Read(kDefaultUser, "other1", &blob)); EXPECT_TRUE(key_store.Read(kDefaultUser, "other2", &blob)); for (int i = 0; i < kNumKeys; ++i) { std::string key_name = std::string("prefix") + base::NumberToString(i); EXPECT_FALSE(key_store.Read(kDefaultUser, key_name, &blob)); } } } // namespace attestation
28,928
12,796
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "GeoMesh.h" #include "GeoElementSide.h" ///\cond #include <stdio.h> #include <algorithm> ///\endcond GeoElementSide::GeoElementSide() { } GeoElementSide::GeoElementSide(const GeoElementSide& copy) { fElement = copy.fElement; fSide = copy.fSide; } GeoElementSide& GeoElementSide::operator=(const GeoElementSide& copy) { fElement = copy.fElement; fSide = copy.fSide; return *this; } GeoElementSide GeoElementSide::Neighbour() const { return fElement ? fElement->Neighbour(fSide) : GeoElementSide(); } void GeoElementSide::SetNeighbour(const GeoElementSide& neighbour) { fElement->SetNeighbour(fSide, neighbour); } bool GeoElementSide::IsNeighbour(const GeoElementSide& candidate) const { if (candidate == *this) return true; GeoElementSide neighbour = Neighbour(); if (!(neighbour.Element() != 0 && neighbour.Side() > -1)) return false; while ((neighbour == *this) == false) { if (candidate == neighbour) return true; neighbour = neighbour.Neighbour(); } return false; } void GeoElementSide::IsertConnectivity(GeoElementSide& candidate) { if (this->IsNeighbour(candidate)) return; GeoElementSide neigh1 = Neighbour(); GeoElementSide neigh2 = candidate.Neighbour(); SetNeighbour(neigh2); candidate.SetNeighbour(neigh1); } void GeoElementSide::AllNeighbours(std::vector<GeoElementSide>& allneigh) const { if (fElement->NSideNodes(fSide) != 1) DebugStop(); GeoElementSide neigh = Neighbour(); int nodeindex = fElement->SideNodeIndex(fSide, 0); while (neigh != *this) { int neighnode = neigh.fElement->SideNodeIndex(neigh.fSide, 0); if (neighnode != nodeindex) DebugStop(); allneigh.push_back(neigh); neigh = neigh.Neighbour(); } } void GeoElementSide::ComputeNeighbours(std::vector<GeoElementSide>& compneigh) { if (fSide < fElement->NCornerNodes()) { AllNeighbours(compneigh); return; } int nsnodes = fElement->NSideNodes(fSide); std::vector<GeoElementSide> GeoElSideSet; std::vector<std::vector<int> > GeoElSet; GeoElSet.resize(nsnodes); int in; VecInt nodeindexes(nsnodes); for (in = 0; in < nsnodes; in++) { int nodeindex = fElement->SideNodeIndex(fSide, in); nodeindexes[in] = nodeindex; } // compute the neighbours along the cornernodes for (in = 0; in < nsnodes; in++) { int locindex = fElement->SideNodeLocIndex(fSide, in); int nodeindex = fElement->SideNodeIndex(fSide, in); GeoElSideSet.resize(0); GeoElementSide locside(fElement, locindex); int nodeindex_again = locside.Element()->SideNodeIndex(locside.Side(), 0); if (nodeindex != nodeindex_again) DebugStop(); locside.AllNeighbours(GeoElSideSet); for (auto& gelside : GeoElSideSet) { int node = gelside.Element()->SideNodeIndex(gelside.Side(), 0); if (node != nodeindex) DebugStop(); } int nel = GeoElSideSet.size(); int el; for (el = 0; el < nel; el++) { GeoElSet[in].push_back(GeoElSideSet[el].Element()->GetIndex()); } std::sort(GeoElSet[in].begin(), GeoElSet[in].end()); } std::vector<int> result; std::vector<int> result_aux; // build the neighbours along the higher dimension sides switch (nsnodes) { case 1: { result = GeoElSet[0]; } break; case 2: std::set_intersection(GeoElSet[0].begin(), GeoElSet[0].end(), GeoElSet[1].begin(), GeoElSet[1].end(), std::back_inserter(result)); break; case 3: std::set_intersection(GeoElSet[0].begin(), GeoElSet[0].end(), GeoElSet[1].begin(), GeoElSet[1].end(), std::back_inserter(result_aux)); std::set_intersection(result_aux.begin(), result_aux.end(), GeoElSet[2].begin(), GeoElSet[2].end(), std::back_inserter(result)); break; case 4: { std::vector<int> inter1, inter2; std::set_intersection(GeoElSet[0].begin(), GeoElSet[0].end(), GeoElSet[2].begin(), GeoElSet[2].end(), std::back_inserter(inter1)); if (inter1.size() == 0) break; std::set_intersection(GeoElSet[1].begin(), GeoElSet[1].end(), GeoElSet[3].begin(), GeoElSet[3].end(), std::back_inserter(inter2)); if (inter2.size() == 0) break; std::set_intersection(inter1.begin(), inter1.end(), inter2.begin(), inter2.end(), std::back_inserter(result)); inter1.clear(); inter2.clear(); } break; default: { std::vector<int> inter1, inter2; inter1 = GeoElSet[0]; for (in = 0; in < nsnodes - 1; in++) { std::set_intersection(inter1.begin(), inter1.end(), GeoElSet[in + 1].begin(), GeoElSet[in + 1].end(), std::back_inserter(inter2)); if (inter2.size() == 0) break; inter1 = inter2; } inter1.clear(); inter2.clear(); result = inter2; } } int el, nel = result.size(); GeoMesh* geoMesh = fElement->GetMesh(); for (el = 0; el < nel; el++) { GeoElement* gelResult = geoMesh->Element(result[el]); int whichSd = gelResult->WhichSide(nodeindexes); if (whichSd < 0) { std::cout << "nodeindexes " << nodeindexes << std::endl; std::cout << "neighbouring element index " << gelResult->GetIndex() << std::endl; std::cout << "neighbouring element nodes "; for (int i = 0; i < gelResult->NNodes(); i++) std::cout << gelResult->NodeIndex(i) << " "; std::cout << std::endl; for (int i = 0; i < nsnodes; i++) { auto gelset = GeoElSet[i]; std::cout << "GeoElSet along node " << i << " is "; for (auto g : gelset) std::cout << g << " "; std::cout << std::endl; } DebugStop(); } GeoElementSide gelside(gelResult, whichSd); if (gelside == *this) continue; if (whichSd > 0) { compneigh.push_back(GeoElementSide(gelResult, whichSd)); } } GeoElSideSet.clear(); GeoElSet.clear(); nodeindexes.resize(0); result.clear(); result_aux.clear(); } // Print the element index and side void GeoElementSide::Print(std::ostream& out) const { if (!fElement) { out << "GeoElSide empty\n"; } else { out << "elid " << fElement->GetIndex() << " side " << fSide << std::endl; } }
6,695
2,297
// PX2CURLDownload.inl //---------------------------------------------------------------------------- inline CURLDownload::DownType CURLDownload::GetDownType () const { return mDownType; } //---------------------------------------------------------------------------- inline char *CURLDownload::GetDownloadMemory () { return mDownloadMemory; } //---------------------------------------------------------------------------- inline const char *CURLDownload::GetDownloadMemory () const { return mDownloadMemory; } //---------------------------------------------------------------------------- inline bool CURLDownload::IsDownLoadOK () const { return mIsDownLoadOK; } //---------------------------------------------------------------------------- inline float CURLDownload::GetDownLoadProgress () const { return mDownLoadProgress; } //----------------------------------------------------------------------------
913
177
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * TestDistributed creates a dumbbell topology and logically splits it in * half. The left half is placed on logical processor 0 and the right half * is placed on logical processor 1. * * ------- ------- * RANK 0 RANK 1 * ------- | ------- * | * n0 ---------| | |---------- n6 * | | | * n1 -------\ | | | /------- n7 * n4 ----------|---------- n5 * n2 -------/ | | | \------- n8 * | | | * n3 ---------| | |---------- n9 * * * OnOff clients are placed on each left leaf node. Each right leaf node * is a packet sink for a left leaf node. As a packet travels from one * logical processor to another (the link between n4 and n5), MPI messages * are passed containing the serialized packet. The message is then * deserialized into a new packet and sent on as normal. * * One packet is sent from each left leaf node. The packet sinks on the * right leaf nodes output logging information when they receive the packet. */ #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/mpi-interface.h" #include "ns3/ipv4-global-routing-helper.h" #include "ns3/point-to-point-helper.h" #include "ns3/internet-stack-helper.h" #include "ns3/ipv4-nix-vector-helper.h" #include "ns3/ipv4-address-helper.h" #include "ns3/on-off-helper.h" #include "ns3/packet-sink-helper.h" #ifdef NS3_MPI #include <mpi.h> #endif using namespace ns3; NS_LOG_COMPONENT_DEFINE ("SimpleDistributed"); int main (int argc, char *argv[]) { #ifdef NS3_MPI bool nix = true; bool nullmsg = false; bool tracing = false; // Parse command line CommandLine cmd; cmd.AddValue ("nix", "Enable the use of nix-vector or global routing", nix); cmd.AddValue ("nullmsg", "Enable the use of null-message synchronization", nullmsg); cmd.AddValue ("tracing", "Enable pcap tracing", tracing); cmd.Parse (argc, argv); // Distributed simulation setup; by default use granted time window algorithm. if(nullmsg) { GlobalValue::Bind ("SimulatorImplementationType", StringValue ("ns3::NullMessageSimulatorImpl")); } else { GlobalValue::Bind ("SimulatorImplementationType", StringValue ("ns3::DistributedSimulatorImpl")); } // Enable parallel simulator with the command line arguments MpiInterface::Enable (&argc, &argv); LogComponentEnable ("PacketSink", LOG_LEVEL_INFO); uint32_t systemId = MpiInterface::GetSystemId (); uint32_t systemCount = MpiInterface::GetSize (); // Check for valid distributed parameters. // Must have 2 and only 2 Logical Processors (LPs) if (systemCount != 2) { std::cout << "This simulation requires 2 and only 2 logical processors." << std::endl; return 1; } // Some default values Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (512)); Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("1Mbps")); Config::SetDefault ("ns3::OnOffApplication::MaxBytes", UintegerValue (512)); // Create leaf nodes on left with system id 0 NodeContainer leftLeafNodes; leftLeafNodes.Create (4, 0); // Create router nodes. Left router // with system id 0, right router with // system id 1 NodeContainer routerNodes; Ptr<Node> routerNode1 = CreateObject<Node> (0); Ptr<Node> routerNode2 = CreateObject<Node> (1); routerNodes.Add (routerNode1); routerNodes.Add (routerNode2); // Create leaf nodes on right with system id 1 NodeContainer rightLeafNodes; rightLeafNodes.Create (4, 1); PointToPointHelper routerLink; routerLink.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); routerLink.SetChannelAttribute ("Delay", StringValue ("5ms")); PointToPointHelper leafLink; leafLink.SetDeviceAttribute ("DataRate", StringValue ("1Mbps")); leafLink.SetChannelAttribute ("Delay", StringValue ("2ms")); // Add link connecting routers NetDeviceContainer routerDevices; routerDevices = routerLink.Install (routerNodes); // Add links for left side leaf nodes to left router NetDeviceContainer leftRouterDevices; NetDeviceContainer leftLeafDevices; for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer temp = leafLink.Install (leftLeafNodes.Get (i), routerNodes.Get (0)); leftLeafDevices.Add (temp.Get (0)); leftRouterDevices.Add (temp.Get (1)); } // Add links for right side leaf nodes to right router NetDeviceContainer rightRouterDevices; NetDeviceContainer rightLeafDevices; for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer temp = leafLink.Install (rightLeafNodes.Get (i), routerNodes.Get (1)); rightLeafDevices.Add (temp.Get (0)); rightRouterDevices.Add (temp.Get (1)); } InternetStackHelper stack; if (nix) { Ipv4NixVectorHelper nixRouting; stack.SetRoutingHelper (nixRouting); // has effect on the next Install () } stack.InstallAll (); Ipv4InterfaceContainer routerInterfaces; Ipv4InterfaceContainer leftLeafInterfaces; Ipv4InterfaceContainer leftRouterInterfaces; Ipv4InterfaceContainer rightLeafInterfaces; Ipv4InterfaceContainer rightRouterInterfaces; Ipv4AddressHelper leftAddress; leftAddress.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4AddressHelper routerAddress; routerAddress.SetBase ("10.2.1.0", "255.255.255.0"); Ipv4AddressHelper rightAddress; rightAddress.SetBase ("10.3.1.0", "255.255.255.0"); // Router-to-Router interfaces routerInterfaces = routerAddress.Assign (routerDevices); // Left interfaces for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer ndc; ndc.Add (leftLeafDevices.Get (i)); ndc.Add (leftRouterDevices.Get (i)); Ipv4InterfaceContainer ifc = leftAddress.Assign (ndc); leftLeafInterfaces.Add (ifc.Get (0)); leftRouterInterfaces.Add (ifc.Get (1)); leftAddress.NewNetwork (); } // Right interfaces for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer ndc; ndc.Add (rightLeafDevices.Get (i)); ndc.Add (rightRouterDevices.Get (i)); Ipv4InterfaceContainer ifc = rightAddress.Assign (ndc); rightLeafInterfaces.Add (ifc.Get (0)); rightRouterInterfaces.Add (ifc.Get (1)); rightAddress.NewNetwork (); } if (!nix) { Ipv4GlobalRoutingHelper::PopulateRoutingTables (); } if (tracing == true) { if (systemId == 0) { routerLink.EnablePcap("router-left", routerDevices, true); leafLink.EnablePcap("leaf-left", leftLeafDevices, true); } if (systemId == 1) { routerLink.EnablePcap("router-right", routerDevices, true); leafLink.EnablePcap("leaf-right", rightLeafDevices, true); } } // Create a packet sink on the right leafs to receive packets from left leafs uint16_t port = 50000; if (systemId == 1) { Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port)); PacketSinkHelper sinkHelper ("ns3::UdpSocketFactory", sinkLocalAddress); ApplicationContainer sinkApp; for (uint32_t i = 0; i < 4; ++i) { sinkApp.Add (sinkHelper.Install (rightLeafNodes.Get (i))); } sinkApp.Start (Seconds (1.0)); sinkApp.Stop (Seconds (5)); } // Create the OnOff applications to send if (systemId == 0) { OnOffHelper clientHelper ("ns3::UdpSocketFactory", Address ()); clientHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); clientHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); ApplicationContainer clientApps; for (uint32_t i = 0; i < 4; ++i) { AddressValue remoteAddress (InetSocketAddress (rightLeafInterfaces.GetAddress (i), port)); clientHelper.SetAttribute ("Remote", remoteAddress); clientApps.Add (clientHelper.Install (leftLeafNodes.Get (i))); } clientApps.Start (Seconds (1.0)); clientApps.Stop (Seconds (5)); } Simulator::Stop (Seconds (5)); Simulator::Run (); Simulator::Destroy (); // Exit the MPI execution environment MpiInterface::Disable (); return 0; #else NS_FATAL_ERROR ("Can't use distributed simulator without MPI compiled in"); #endif }
9,241
2,983
// // $Id$ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2007 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // 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 "pwiz/data/msdata/RAMPAdapter.hpp" #include "pwiz/utility/misc/Std.hpp" using namespace pwiz::msdata; void test(const char* filename) { RAMPAdapter adapter(filename); InstrumentStruct instrument; adapter.getInstrument(instrument); cout << "manufacturer: " << instrument.manufacturer << endl; cout << "model: " << instrument.model << endl; cout << "ionisation: " << instrument.ionisation << endl; cout << "analyzer : " << instrument.analyzer << endl; cout << "detector: " << instrument.detector << endl; size_t scanCount = adapter.scanCount(); cout << "scanCount: " << scanCount << "\n\n"; for (size_t i=0; i<scanCount; i++) { ScanHeaderStruct header; adapter.getScanHeader(i, header); cout << "index: " << i << endl; cout << "seqNum: " << header.seqNum << endl; cout << "acquisitionNum: " << header.acquisitionNum << endl; cout << "msLevel: " << header.msLevel << endl; cout << "peaksCount: " << header.peaksCount << endl; cout << "precursorScanNum: " << header.precursorScanNum << endl; cout << "filePosition: " << header.filePosition << endl; vector<double> peaks; adapter.getScanPeaks(i, peaks); for (unsigned int j=0; j<min(peaks.size(),(size_t)20); j+=2) cout << " (" << peaks[j] << ", " << peaks[j+1] << ")\n"; cout << endl; } } int main(int argc, char* argv[]) { try { if (argc<2) throw runtime_error("Usage: hello_ramp filename"); test(argv[1]); return 0; } catch (exception& e) { cerr << e.what() << endl; } catch (...) { cerr << "Caught unknown exception.\n"; } return 1; }
2,534
834
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2019, Robótica de la Mixteca * 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 Universidad Tecnológica de la Mixteca 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. *********************************************************************/ ///////////////////////////////////////////////////////////////////////////////////////// /// @file ROS msv_main node of the MSV-01 rescue robot for general control using the ROS /// Joy messages. The node publishes the teleoperation commands, as well as the control /// commands for the robotic arm and an orientation system for the RGBD sensor. /// @author Victor Esteban Sandoval-Luna /// /// Based on the "rescue" ROS metapackage from José Armando Sánchez-Rojas. /// Based on the Modbus protocol "lightmodbus" library (RTU) from Jacek Wieczorek, /// please see https://github.com/Jacajack/liblightmodbus. ///////////////////////////////////////////////////////////////////////////////////////// #include <msv_main/msv_main.h> #include <boost/asio.hpp> int main (int argc, char **argv) { //Initialize ROS ros::init(argc, argv, "msv_main"); try { //Create an object of class MsvMain that will do the job MsvMain *robot; MsvMain msv01; robot = &msv01; ros::Rate loop_rate(10); while (ros::ok()) { // Node callbacks handling ros::spinOnce(); loop_rate.sleep(); } return 0; } catch (boost::system::system_error ex) { ROS_ERROR("Error instantiating msv_main object. Error: %s", ex.what()); return -1; } }
3,084
1,017
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Net.ICredentials #include "System/Net/ICredentials.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: System::Security namespace System::Security { // Forward declaring type: SecureString class SecureString; } // Forward declaring namespace: System namespace System { // Forward declaring type: Uri class Uri; } // Completed forward declares // Type namespace: System.Net namespace System::Net { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Net.NetworkCredential class NetworkCredential : public ::Il2CppObject/*, public System::Net::ICredentials*/ { public: // private System.String m_domain // Size: 0x8 // Offset: 0x10 ::Il2CppString* m_domain; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.String m_userName // Size: 0x8 // Offset: 0x18 ::Il2CppString* m_userName; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.Security.SecureString m_password // Size: 0x8 // Offset: 0x20 System::Security::SecureString* m_password; // Field size check static_assert(sizeof(System::Security::SecureString*) == 0x8); // Creating value type constructor for type: NetworkCredential NetworkCredential(::Il2CppString* m_domain_ = {}, ::Il2CppString* m_userName_ = {}, System::Security::SecureString* m_password_ = {}) noexcept : m_domain{m_domain_}, m_userName{m_userName_}, m_password{m_password_} {} // Creating interface conversion operator: operator System::Net::ICredentials operator System::Net::ICredentials() noexcept { return *reinterpret_cast<System::Net::ICredentials*>(this); } // public System.Void .ctor(System.String userName, System.String password) // Offset: 0x164634C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NetworkCredential* New_ctor(::Il2CppString* userName, ::Il2CppString* password) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::NetworkCredential::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NetworkCredential*, creationType>(userName, password))); } // public System.Void .ctor(System.String userName, System.String password, System.String domain) // Offset: 0x16463BC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NetworkCredential* New_ctor(::Il2CppString* userName, ::Il2CppString* password, ::Il2CppString* domain) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::NetworkCredential::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NetworkCredential*, creationType>(userName, password, domain))); } // public System.String get_UserName() // Offset: 0x16465A8 ::Il2CppString* get_UserName(); // public System.Void set_UserName(System.String value) // Offset: 0x164649C void set_UserName(::Il2CppString* value); // public System.String get_Password() // Offset: 0x16465B0 ::Il2CppString* get_Password(); // public System.Void set_Password(System.String value) // Offset: 0x164650C void set_Password(::Il2CppString* value); // public System.String get_Domain() // Offset: 0x16465C8 ::Il2CppString* get_Domain(); // public System.Void set_Domain(System.String value) // Offset: 0x1646538 void set_Domain(::Il2CppString* value); // System.String InternalGetUserName() // Offset: 0x16465D0 ::Il2CppString* InternalGetUserName(); // System.String InternalGetPassword() // Offset: 0x16465BC ::Il2CppString* InternalGetPassword(); // System.String InternalGetDomain() // Offset: 0x16465D8 ::Il2CppString* InternalGetDomain(); // public System.Net.NetworkCredential GetCredential(System.Uri uri, System.String authType) // Offset: 0x16465E0 System::Net::NetworkCredential* GetCredential(System::Uri* uri, ::Il2CppString* authType); }; // System.Net.NetworkCredential #pragma pack(pop) static check_size<sizeof(NetworkCredential), 32 + sizeof(System::Security::SecureString*)> __System_Net_NetworkCredentialSizeCheck; static_assert(sizeof(NetworkCredential) == 0x28); } DEFINE_IL2CPP_ARG_TYPE(System::Net::NetworkCredential*, "System.Net", "NetworkCredential");
5,015
1,687
// Version information for the "UsageEnvironment" library // Copyright (c) 1996-2016 Live Networks, Inc. All rights reserved. #ifndef _USAGEENVIRONMENT_VERSION_HH #define _USAGEENVIRONMENT_VERSION_HH #define USAGEENVIRONMENT_LIBRARY_VERSION_STRING "2016.10.11" #define USAGEENVIRONMENT_LIBRARY_VERSION_INT 1476144000 #endif
329
135
/* #include <iostream> #include <cstdlib> #include <cmath> #include <algorithm> #include <stack> #include <string> #include <cstring> using namespace std; stack<int> st; int main(){ string s; cin>>s; //cout<<"F@ck you"; for(int i=0;i<s.length();i++){ if(s[i]=='(') st.push(i); if(s[i]==')') st.pop(); if(s[i]=='*') cout<<st.size(); } return 0; } */
396
167
#include "Runtime/MP1/CSamusFaceReflection.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/GameGlobalObjects.hpp" #include "Runtime/Camera/CFirstPersonCamera.hpp" #include "Runtime/World/CPlayer.hpp" #include "Runtime/World/CWorld.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace metaforce::MP1 { static const zeus::CTransform PreXf = zeus::CTransform::Scale(0.3f) * zeus::CTransform::Translate(0.f, 0.5f, 0.f); CSamusFaceReflection::CSamusFaceReflection(CStateManager& stateMgr) : x0_modelData(CAnimRes(g_ResFactory->GetResourceIdByName("ACS_SamusFace")->id, 0, zeus::skOne3f, 0, true)) , x4c_lights(std::make_unique<CActorLights>(8, zeus::skZero3f, 4, 4, false, false, false, 0.1f)) { x60_lookDir = zeus::skForward; constexpr CAnimPlaybackParms parms(0, -1, 1.f, true); x0_modelData.GetAnimationData()->SetAnimation(parms, false); } void CSamusFaceReflection::PreDraw(const CStateManager& mgr) { if (x6c_ != 2 && (x4c_lights->GetActiveLightCount() >= 1 || (x6c_ != 0 && x6c_ != 3))) { if (!TCastToConstPtr<CFirstPersonCamera>(mgr.GetCameraManager()->GetCurrentCamera(mgr))) { x70_hidden = true; } else { x70_hidden = false; x0_modelData.GetAnimationData()->PreRender(); } } } void CSamusFaceReflection::Draw(const CStateManager& mgr) { if (x70_hidden) return; if (TCastToConstPtr<CFirstPersonCamera> fpCam = (mgr.GetCameraManager()->GetCurrentCamera(mgr))) { SCOPED_GRAPHICS_DEBUG_GROUP("CSamusFaceReflection::Draw", zeus::skBlue); zeus::CQuaternion camRot(fpCam->GetTransform().basis); float dist = ITweakGui::FaceReflectionDistanceDebugValueToActualValue(g_tweakGui->GetFaceReflectionDistance()); float height = ITweakGui::FaceReflectionHeightDebugValueToActualValue(g_tweakGui->GetFaceReflectionHeight()); float aspect = ITweakGui::FaceReflectionAspectDebugValueToActualValue(g_tweakGui->GetFaceReflectionAspect()); float orthoWidth = ITweakGui::FaceReflectionOrthoWidthDebugValueToActualValue(g_tweakGui->GetFaceReflectionOrthoWidth()); float orthoHeight = ITweakGui::FaceReflectionOrthoHeightDebugValueToActualValue(g_tweakGui->GetFaceReflectionOrthoHeight()); zeus::CTransform modelXf = zeus::CTransform(camRot * x50_lookRot, fpCam->GetTransform().basis[1] * dist + fpCam->GetTransform().origin + fpCam->GetTransform().basis[2] * height) * PreXf; CGraphics::SetViewPointMatrix(fpCam->GetTransform()); CGraphics::SetOrtho(aspect * -orthoWidth, aspect * orthoWidth, orthoHeight, -orthoHeight, -10.f, 10.f); CActorLights* lights = x6c_ == 1 ? nullptr : x4c_lights.get(); if (x6c_ == 3) { x0_modelData.Render(mgr, modelXf, lights, CModelFlags(0, 0, 3, zeus::skWhite)); } else { float transFactor; if (mgr.GetPlayerState()->GetActiveVisor(mgr) == CPlayerState::EPlayerVisor::Combat) transFactor = mgr.GetPlayerState()->GetVisorTransitionFactor(); else transFactor = 0.f; if (transFactor > 0.f) { x0_modelData.Render(mgr, modelXf, nullptr, CModelFlags(7, 0, 3, zeus::skBlack)); x0_modelData.Render(mgr, modelXf, lights, CModelFlags(7, 0, 1, zeus::CColor(1.f, transFactor))); } } } } void CSamusFaceReflection::Update(float dt, const CStateManager& mgr, CRandom16& rand) { if (TCastToConstPtr<CFirstPersonCamera> fpCam = (mgr.GetCameraManager()->GetCurrentCamera(mgr))) { x0_modelData.AdvanceAnimationIgnoreParticles(dt, rand, true); x4c_lights->SetFindShadowLight(false); TAreaId areaId = mgr.GetPlayer().GetAreaIdAlways(); if (areaId == kInvalidAreaId) return; zeus::CAABox aabb(fpCam->GetTranslation() - 0.125f, fpCam->GetTranslation() + 0.125f); const CGameArea* area = mgr.GetWorld()->GetAreaAlways(areaId); x4c_lights->BuildFaceLightList(mgr, *area, aabb); zeus::CUnitVector3f lookDir(fpCam->GetTransform().basis[1]); zeus::CUnitVector3f xfLook = zeus::CQuaternion::lookAt(lookDir, zeus::skForward, 2.f * M_PIF).transform(x60_lookDir); zeus::CQuaternion xfLook2 = zeus::CQuaternion::lookAt(zeus::skForward, xfLook, 2.f * M_PIF); xfLook2 *= xfLook2; zeus::CMatrix3f newXf(xfLook2); zeus::CMatrix3f prevXf(x50_lookRot); float lookDot = prevXf[1].dot(newXf[1]); if (std::fabs(lookDot) > 1.f) lookDot = lookDot > 0.f ? 1.f : -1.f; float lookAng = std::acos(lookDot); x50_lookRot = zeus::CQuaternion::slerp( x50_lookRot, xfLook2, zeus::clamp(0.f, 18.f * dt * ((lookAng > 0.f) ? 0.5f * dt * g_tweakPlayer->GetFreeLookSpeed() / lookAng : 0.f), 1.f)); x60_lookDir = lookDir; } } } // namespace metaforce::MP1
4,759
1,842
/**************************************************************************** ** Meta object code from reading C++ file 'pic.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../External-Interface/pic.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'pic.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_pic[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 10, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: signature, parameters, type, tag, flags 12, 5, 4, 4, 0x05, 38, 35, 4, 4, 0x05, 74, 35, 4, 4, 0x05, // slots: signature, parameters, type, tag, flags 110, 35, 4, 4, 0x0a, 146, 35, 4, 4, 0x0a, 184, 4, 4, 4, 0x08, 201, 4, 4, 4, 0x08, 220, 4, 4, 4, 0x08, 239, 4, 4, 4, 0x08, 260, 4, 4, 4, 0x08, 0 // eod }; static const char qt_meta_stringdata_pic[] = { "pic\0\0frame,\0canSend(can_frame,int)\0" ",,\0Signal_pic_to_Test(QString,int,int)\0" "Signal_pic_to_Main(QString,int,int)\0" "Pubs_from_main(QStringList,int,int)\0" "Pubs_from_Switchover(int,int32_t,int)\0" "Timer_Order_Go()\0L_Cylinder_Up_Go()\0" "R_Cylinder_Up_Go()\0Cylinder_Real_Back()\0" "IO_Join_Reset()\0" }; void pic::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); pic *_t = static_cast<pic *>(_o); switch (_id) { case 0: _t->canSend((*reinterpret_cast< can_frame(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 1: _t->Signal_pic_to_Test((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 2: _t->Signal_pic_to_Main((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 3: _t->Pubs_from_main((*reinterpret_cast< QStringList(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 4: _t->Pubs_from_Switchover((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int32_t(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 5: _t->Timer_Order_Go(); break; case 6: _t->L_Cylinder_Up_Go(); break; case 7: _t->R_Cylinder_Up_Go(); break; case 8: _t->Cylinder_Real_Back(); break; case 9: _t->IO_Join_Reset(); break; default: ; } } } const QMetaObjectExtraData pic::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject pic::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_pic, qt_meta_data_pic, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &pic::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *pic::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *pic::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_pic)) return static_cast<void*>(const_cast< pic*>(this)); return QObject::qt_metacast(_clname); } int pic::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 10) qt_static_metacall(this, _c, _id, _a); _id -= 10; } return _id; } // SIGNAL 0 void pic::canSend(can_frame _t1, int _t2) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void pic::Signal_pic_to_Test(QString _t1, int _t2, int _t3) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void pic::Signal_pic_to_Main(QString _t1, int _t2, int _t3) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } QT_END_MOC_NAMESPACE
5,160
2,092
// Copyright (c) Iwer Petersen. All rights reserved. #include "SumoNetworkAssetFactory.h" #include "SumoNetworkAsset.h" #include "SumoNetworkParser.h" USumoNetworkAssetFactory::USumoNetworkAssetFactory( const FObjectInitializer& ObjectInitializer ) : Super(ObjectInitializer) { SupportedClass = USumoNetworkAsset::StaticClass(); bCreateNew = false; bEditorImport = true; Formats.Add(TEXT("xml;Sumo network definition file")); } UObject * USumoNetworkAssetFactory::FactoryCreateFile(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext* Warn, bool& bOutOperationCanceled) { USumoNetworkAsset* Asset = NewObject<USumoNetworkAsset>(InParent, InClass, InName, Flags); // populate Asset USumoNetworkParser parser; parser.ParseFile(Filename, Asset); return Asset; } bool USumoNetworkAssetFactory::FactoryCanImport(const FString & Filename) { if(!Filename.EndsWith(TEXT(".net.xml"))){ return false; } return true; }
1,423
372
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * Standard JSON compiler interface. */ #include <libsolidity/interface/StandardCompiler.h> #include <libsolidity/interface/SourceReferenceFormatter.h> #include <libsolidity/ast/ASTJsonConverter.h> #include <libevmasm/Instruction.h> #include <libdevcore/JSON.h> #include <libdevcore/SHA3.h> using namespace std; using namespace dev; using namespace dev::solidity; namespace { Json::Value formatError( bool _warning, string const& _type, string const& _component, string const& _message, string const& _formattedMessage = "", Json::Value const& _sourceLocation = Json::Value() ) { Json::Value error = Json::objectValue; error["type"] = _type; error["component"] = _component; error["severity"] = _warning ? "warning" : "error"; error["message"] = _message; error["formattedMessage"] = (_formattedMessage.length() > 0) ? _formattedMessage : _message; if (_sourceLocation.isObject()) error["sourceLocation"] = _sourceLocation; return error; } Json::Value formatFatalError(string const& _type, string const& _message) { Json::Value output = Json::objectValue; output["errors"] = Json::arrayValue; output["errors"].append(formatError(false, _type, "general", _message)); return output; } Json::Value formatErrorWithException( Exception const& _exception, bool const& _warning, string const& _type, string const& _component, string const& _message, function<Scanner const&(string const&)> const& _scannerFromSourceName ) { string message; string formattedMessage = SourceReferenceFormatter::formatExceptionInformation(_exception, _type, _scannerFromSourceName); // NOTE: the below is partially a copy from SourceReferenceFormatter SourceLocation const* location = boost::get_error_info<errinfo_sourceLocation>(_exception); if (string const* description = boost::get_error_info<errinfo_comment>(_exception)) message = ((_message.length() > 0) ? (_message + ":") : "") + *description; else message = _message; if (location && location->sourceName) { Json::Value sourceLocation = Json::objectValue; sourceLocation["file"] = *location->sourceName; sourceLocation["start"] = location->start; sourceLocation["end"] = location->end; } return formatError(_warning, _type, _component, message, formattedMessage, location); } set<string> requestedContractNames(Json::Value const& _outputSelection) { set<string> names; for (auto const& sourceName: _outputSelection.getMemberNames()) { for (auto const& contractName: _outputSelection[sourceName].getMemberNames()) { /// Consider the "all sources" shortcuts as requesting everything. if (contractName == "*" || contractName == "") return set<string>(); names.insert((sourceName == "*" ? "" : sourceName) + ":" + contractName); } } return names; } /// Returns true iff @a _hash (hex with 0x prefix) is the Keccak256 hash of the binary data in @a _content. bool hashMatchesContent(string const& _hash, string const& _content) { try { return dev::h256(_hash) == dev::keccak256(_content); } catch (dev::BadHexCharacter) { return false; } } StringMap createSourceList(Json::Value const& _input) { StringMap sources; Json::Value const& jsonSources = _input["sources"]; if (jsonSources.isObject()) for (auto const& sourceName: jsonSources.getMemberNames()) sources[sourceName] = jsonSources[sourceName]["content"].asString(); return sources; } Json::Value formatLinkReferences(std::map<size_t, std::string> const& linkReferences) { Json::Value ret(Json::objectValue); for (auto const& ref: linkReferences) { string const& fullname = ref.second; size_t colon = fullname.find(':'); solAssert(colon != string::npos, ""); string file = fullname.substr(0, colon); string name = fullname.substr(colon + 1); Json::Value fileObject = ret.get(file, Json::objectValue); Json::Value libraryArray = fileObject.get(name, Json::arrayValue); Json::Value entry = Json::objectValue; entry["start"] = Json::UInt(ref.first); entry["length"] = 20; libraryArray.append(entry); fileObject[name] = libraryArray; ret[file] = fileObject; } return ret; } Json::Value collectEVMObject(eth::LinkerObject const& _object, string const* _sourceMap) { Json::Value output = Json::objectValue; output["object"] = _object.toHex(); output["opcodes"] = solidity::disassemble(_object.bytecode); output["sourceMap"] = _sourceMap ? *_sourceMap : ""; output["linkReferences"] = formatLinkReferences(_object.linkReferences); return output; } } Json::Value StandardCompiler::compileInternal(Json::Value const& _input) { m_compilerStack.reset(false); if (!_input.isObject()) return formatFatalError("JSONError", "Input is not a JSON object."); if (_input["language"] != "Solidity") return formatFatalError("JSONError", "Only \"Solidity\" is supported as a language."); Json::Value const& sources = _input["sources"]; if (!sources) return formatFatalError("JSONError", "No input sources specified."); Json::Value errors = Json::arrayValue; for (auto const& sourceName: sources.getMemberNames()) { string hash; if (!sources[sourceName].isObject()) return formatFatalError("JSONError", "Source input is not a JSON object."); if (sources[sourceName]["keccak256"].isString()) hash = sources[sourceName]["keccak256"].asString(); if (sources[sourceName]["content"].isString()) { string content = sources[sourceName]["content"].asString(); if (!hash.empty() && !hashMatchesContent(hash, content)) errors.append(formatError( false, "IOError", "general", "Mismatch between content and supplied hash for \"" + sourceName + "\"" )); else m_compilerStack.addSource(sourceName, content); } else if (sources[sourceName]["urls"].isArray()) { if (!m_readFile) return formatFatalError("JSONError", "No import callback supplied, but URL is requested."); bool found = false; vector<string> failures; for (auto const& url: sources[sourceName]["urls"]) { ReadCallback::Result result = m_readFile(url.asString()); if (result.success) { if (!hash.empty() && !hashMatchesContent(hash, result.responseOrErrorMessage)) errors.append(formatError( false, "IOError", "general", "Mismatch between content and supplied hash for \"" + sourceName + "\" at \"" + url.asString() + "\"" )); else { m_compilerStack.addSource(sourceName, result.responseOrErrorMessage); found = true; break; } } else failures.push_back("Cannot import url (\"" + url.asString() + "\"): " + result.responseOrErrorMessage); } for (auto const& failure: failures) { /// If the import succeeded, let mark all the others as warnings, otherwise all of them are errors. errors.append(formatError( found ? true : false, "IOError", "general", failure )); } } else return formatFatalError("JSONError", "Invalid input source specified."); } Json::Value const& settings = _input.get("settings", Json::Value()); vector<string> remappings; for (auto const& remapping: settings.get("remappings", Json::Value())) remappings.push_back(remapping.asString()); m_compilerStack.setRemappings(remappings); Json::Value optimizerSettings = settings.get("optimizer", Json::Value()); bool const optimize = optimizerSettings.get("enabled", Json::Value(false)).asBool(); unsigned const optimizeRuns = optimizerSettings.get("runs", Json::Value(200u)).asUInt(); m_compilerStack.setOptimiserSettings(optimize, optimizeRuns); map<string, h160> libraries; Json::Value jsonLibraries = settings.get("libraries", Json::Value()); for (auto const& sourceName: jsonLibraries.getMemberNames()) { auto const& jsonSourceName = jsonLibraries[sourceName]; for (auto const& library: jsonSourceName.getMemberNames()) // @TODO use libraries only for the given source libraries[library] = h160(jsonSourceName[library].asString()); } m_compilerStack.setLibraries(libraries); Json::Value metadataSettings = settings.get("metadata", Json::Value()); m_compilerStack.useMetadataLiteralSources(metadataSettings.get("useLiteralContent", Json::Value(false)).asBool()); Json::Value outputSelection = settings.get("outputSelection", Json::Value()); m_compilerStack.setRequestedContractNames(requestedContractNames(outputSelection)); auto scannerFromSourceName = [&](string const& _sourceName) -> solidity::Scanner const& { return m_compilerStack.scanner(_sourceName); }; try { m_compilerStack.compile(); for (auto const& error: m_compilerStack.errors()) { Error const& err = dynamic_cast<Error const&>(*error); errors.append(formatErrorWithException( *error, err.type() == Error::Type::Warning, err.typeName(), "general", "", scannerFromSourceName )); } } /// This is only thrown in a very few locations. catch (Error const& _error) { errors.append(formatErrorWithException( _error, false, _error.typeName(), "general", "Uncaught error: ", scannerFromSourceName )); } /// This should not be leaked from compile(). catch (FatalError const& _exception) { errors.append(formatError( false, "FatalError", "general", "Uncaught fatal error: " + boost::diagnostic_information(_exception) )); } catch (CompilerError const& _exception) { errors.append(formatErrorWithException( _exception, false, "CompilerError", "general", "Compiler error (" + _exception.lineInfo() + ")", scannerFromSourceName )); } catch (InternalCompilerError const& _exception) { errors.append(formatErrorWithException( _exception, false, "InternalCompilerError", "general", "Internal compiler error (" + _exception.lineInfo() + ")", scannerFromSourceName )); } catch (UnimplementedFeatureError const& _exception) { errors.append(formatErrorWithException( _exception, false, "UnimplementedFeatureError", "general", "Unimplemented feature (" + _exception.lineInfo() + ")", scannerFromSourceName )); } catch (Exception const& _exception) { errors.append(formatError( false, "Exception", "general", "Exception during compilation: " + boost::diagnostic_information(_exception) )); } catch (...) { errors.append(formatError( false, "Exception", "general", "Unknown exception during compilation." )); } bool const analysisSuccess = m_compilerStack.state() >= CompilerStack::State::AnalysisSuccessful; bool const compilationSuccess = m_compilerStack.state() == CompilerStack::State::CompilationSuccessful; /// Inconsistent state - stop here to receive error reports from users if (!compilationSuccess && (errors.size() == 0)) return formatFatalError("InternalCompilerError", "No error reported, but compilation failed."); Json::Value output = Json::objectValue; if (errors.size() > 0) output["errors"] = errors; output["sources"] = Json::objectValue; unsigned sourceIndex = 0; for (string const& sourceName: analysisSuccess ? m_compilerStack.sourceNames() : vector<string>()) { Json::Value sourceResult = Json::objectValue; sourceResult["id"] = sourceIndex++; sourceResult["ast"] = ASTJsonConverter(false, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(sourceName)); sourceResult["legacyAST"] = ASTJsonConverter(true, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(sourceName)); output["sources"][sourceName] = sourceResult; } Json::Value contractsOutput = Json::objectValue; for (string const& contractName: compilationSuccess ? m_compilerStack.contractNames() : vector<string>()) { size_t colon = contractName.find(':'); solAssert(colon != string::npos, ""); string file = contractName.substr(0, colon); string name = contractName.substr(colon + 1); // ABI, documentation and metadata Json::Value contractData(Json::objectValue); contractData["abi"] = m_compilerStack.contractABI(contractName); contractData["metadata"] = m_compilerStack.metadata(contractName); contractData["userdoc"] = m_compilerStack.natspecUser(contractName); contractData["devdoc"] = m_compilerStack.natspecDev(contractName); // EVM Json::Value evmData(Json::objectValue); // @TODO: add ir evmData["assembly"] = m_compilerStack.assemblyString(contractName, createSourceList(_input)); evmData["legacyAssembly"] = m_compilerStack.assemblyJSON(contractName, createSourceList(_input)); evmData["methodIdentifiers"] = m_compilerStack.methodIdentifiers(contractName); evmData["gasEstimates"] = m_compilerStack.gasEstimates(contractName); evmData["bytecode"] = collectEVMObject( m_compilerStack.object(contractName), m_compilerStack.sourceMapping(contractName) ); evmData["deployedBytecode"] = collectEVMObject( m_compilerStack.runtimeObject(contractName), m_compilerStack.runtimeSourceMapping(contractName) ); contractData["evm"] = evmData; if (!contractsOutput.isMember(file)) contractsOutput[file] = Json::objectValue; contractsOutput[file][name] = contractData; } output["contracts"] = contractsOutput; return output; } Json::Value StandardCompiler::compile(Json::Value const& _input) { try { return compileInternal(_input); } catch (Json::LogicError const& _exception) { return formatFatalError("InternalCompilerError", string("JSON logic exception: ") + _exception.what()); } catch (Json::RuntimeError const& _exception) { return formatFatalError("InternalCompilerError", string("JSON runtime exception: ") + _exception.what()); } catch (Exception const& _exception) { return formatFatalError("InternalCompilerError", "Internal exception in StandardCompiler::compileInternal: " + boost::diagnostic_information(_exception)); } catch (...) { return formatFatalError("InternalCompilerError", "Internal exception in StandardCompiler::compileInternal"); } } string StandardCompiler::compile(string const& _input) { Json::Value input; Json::Reader reader; try { if (!reader.parse(_input, input, false)) return jsonCompactPrint(formatFatalError("JSONError", reader.getFormattedErrorMessages())); } catch(...) { return "{\"errors\":\"[{\"type\":\"JSONError\",\"component\":\"general\",\"severity\":\"error\",\"message\":\"Error parsing input JSON.\"}]}"; } // cout << "Input: " << input.toStyledString() << endl; Json::Value output = compile(input); // cout << "Output: " << output.toStyledString() << endl; try { return jsonCompactPrint(output); } catch(...) { return "{\"errors\":\"[{\"type\":\"JSONError\",\"component\":\"general\",\"severity\":\"error\",\"message\":\"Error writing output JSON.\"}]}"; } }
15,341
5,194
/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. * * Use of this source code is governed by a BSD-style license that * * can be found in the LICENSE file. */ unsigned char vulkan_textureshader_frag_spv[] = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x90, 0x01, 0x00, 0x00, 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00, 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, 0x68, 0x61, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x34, 0x32, 0x30, 0x70, 0x61, 0x63, 0x6b, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x6f, 0x75, 0x74, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x10, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, 0x55, 0x76, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x57, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 }; unsigned int vulkan_textureshader_frag_spv_len = 740;
4,888
4,615
//blackScholesAnalyticEngine.cpp //Functions for running black scholes using the analytic engine (from Quantlib) on the GPU #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/time.h> #include <time.h> #define NUM_DIFF_SETTINGS 37 //needed for optionInputStruct #include "blackScholesAnalyticEngineStructs.h" //needed for the kernel(s) to run on the GPU #include "blackScholesAnalyticEngineKernels.cpp" #include "blackScholesAnalyticEngineKernelsCpu.cpp" //function to run the black scholes analytic engine on the gpu void runBlackScholesAnalyticEngine() { int numberOfSamples = 50000000; { int numVals = numberOfSamples;//nSamplesArray[numTime]; optionInputStruct* values = new optionInputStruct[numVals]; for (int numOption = 0; numOption < numVals; numOption++) { if ((numOption % NUM_DIFF_SETTINGS) == 0) { optionInputStruct currVal = { CALL, 40.00, 42.00, 0.08, 0.04, 0.75, 0.35, 5.0975, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 1) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.10, 0.15, 0.0205, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 2) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.10, 0.15, 1.8734, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 3) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.10, 0.15, 9.9413, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 4) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.10, 0.25, 0.3150, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 5) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.10, 0.25, 3.1217, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 6) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.10, 0.25, 10.3556, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 7) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.10, 0.35, 0.9474, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 8) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.10, 0.35, 4.3693, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 9) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.10, 0.35, 11.1381, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 10) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.50, 0.15, 0.8069, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 11) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.50, 0.15, 4.0232, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 12) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.50, 0.15, 10.5769, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 13) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.50, 0.25, 2.7026, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 14) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.50, 0.25, 6.6997, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 15) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.50, 0.25, 12.7857, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 16) { optionInputStruct currVal = { CALL, 100.00, 90.00, 0.10, 0.10, 0.50, 0.35, 4.9329, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 17) { optionInputStruct currVal = { CALL, 100.00, 100.00, 0.10, 0.10, 0.50, 0.35, 9.3679, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 18) { optionInputStruct currVal = { CALL, 100.00, 110.00, 0.10, 0.10, 0.50, 0.35, 15.3086, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 19) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.10, 0.15, 9.9210, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 20) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.10, 0.15, 1.8734, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 21) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.10, 0.15, 0.0408, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 22) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.10, 0.25, 10.2155, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 23) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.10, 0.25, 3.1217, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 24) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.10, 0.25, 0.4551, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 25) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.10, 0.35, 10.8479, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 26) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.10, 0.35, 4.3693, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 27) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.10, 0.35, 1.2376, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 28) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.50, 0.15, 10.3192, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 29) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.50, 0.15, 4.0232, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 30) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.50, 0.15, 1.0646, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 31) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.50, 0.25, 12.2149, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 32) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.50, 0.25, 6.6997, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 33) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.50, 0.25, 3.2734, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 34) { optionInputStruct currVal = { PUT, 100.00, 90.00, 0.10, 0.10, 0.50, 0.35, 14.4452, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 35) { optionInputStruct currVal = { PUT, 100.00, 100.00, 0.10, 0.10, 0.50, 0.35, 9.3679, 1.0e-4}; values[numOption] = currVal; } if ((numOption % NUM_DIFF_SETTINGS) == 36) { optionInputStruct currVal = { PUT, 100.00, 110.00, 0.10, 0.10, 0.50, 0.35, 5.7963, 1.0e-4}; values[numOption] = currVal; } } // Run GPU code //initialize the arrays //declare and allocate the input and output data on the CPU float* outputVals = (float*)malloc(numVals * sizeof(float)); printf("Number of options: %d\n\n", numVals); long seconds, useconds; float mtimeCpu, mtimeGpu; struct timeval start; gettimeofday(&start, NULL); #pragma omp target map(to: values[0:numVals]) map(from: outputVals[0:numVals]) { #pragma omp teams distribute parallel for simd thread_limit(THREAD_BLOCK_SIZE) for (int optionNum = 0; optionNum < numVals; optionNum++) { optionInputStruct threadOption = values[optionNum]; payoffStruct currPayoff; currPayoff.type = threadOption.type; currPayoff.strike = threadOption.strike; yieldTermStruct qTS; qTS.timeYearFraction = threadOption.t; qTS.forward = threadOption.q; yieldTermStruct rTS; rTS.timeYearFraction = threadOption.t; rTS.forward = threadOption.r; blackVolStruct volTS; volTS.timeYearFraction = threadOption.t; volTS.volatility = threadOption.vol; blackScholesMertStruct stochProcess; stochProcess.x0 = threadOption.spot; stochProcess.dividendTS = qTS; stochProcess.riskFreeTS = rTS; stochProcess.blackVolTS = volTS; optionStruct currOption; currOption.payoff = currPayoff; currOption.yearFractionTime = threadOption.t; currOption.pricingEngine = stochProcess; float variance = getBlackVolBlackVar(currOption.pricingEngine.blackVolTS); float dividendDiscount = getDiscountOnDividendYield(currOption.yearFractionTime, currOption.pricingEngine.dividendTS); float riskFreeDiscount = getDiscountOnRiskFreeRate(currOption.yearFractionTime, currOption.pricingEngine.riskFreeTS); float spot = currOption.pricingEngine.x0; float forwardPrice = spot * dividendDiscount / riskFreeDiscount; //declare the blackCalcStruct blackCalcStruct blackCalc; //initialize the calculator initBlackCalculator(blackCalc, currOption.payoff, forwardPrice, sqrtf(variance), riskFreeDiscount); //retrieve the results values float resultVal = getResultVal(blackCalc); //write the resulting value to global memory outputVals[optionNum] = resultVal; } } struct timeval end; gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtimeGpu = ((seconds) * 1000 + ((float)useconds)/1000.0) + 0.5f; printf("Run on GPU\n"); printf("Processing time on GPU: %f (ms)\n", mtimeGpu); float totResult = 0.0f; for (int i=0; i<numVals; i++) { totResult += outputVals[i]; } printf("Summation of output prices on GPU: %f\n", totResult); printf("Output price at index %d on GPU: %f\n\n", numVals/2, outputVals[numVals/2]); //run on CPU gettimeofday(&start, NULL); for (size_t numOption=0; numOption < numVals; numOption++) { getOutValOptionCpu(values, outputVals, numOption, numVals); } gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtimeCpu = ((seconds) * 1000 + ((float)useconds)/1000.0) + 0.5f; printf("Run on CPU\n"); printf("Processing time on CPU: %f (ms)\n", mtimeCpu); totResult = 0.0f; for (int i=0; i<numVals; i++) { totResult += outputVals[i]; } printf("Summation of output prices on CPU: %f\n", totResult); printf("Output price at index %d on CPU:: %f\n\n", numVals/2, outputVals[numVals/2]); printf("Speedup on GPU: %f\n", mtimeCpu / mtimeGpu); delete [] values; free(outputVals); } } //////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { runBlackScholesAnalyticEngine(); return 0; }
12,463
5,609
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2018, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /// \file X3DImporter_Shape.cpp /// \brief Parsing data from nodes of "Shape" set of X3D. /// \date 2015-2016 /// \author smal.root@gmail.com #ifndef ASSIMP_BUILD_NO_X3D_IMPORTER #include "X3DImporter.hpp" #include "X3DImporter_Macro.hpp" namespace Assimp { // <Shape // DEF="" ID // USE="" IDREF // bboxCenter="0 0 0" SFVec3f [initializeOnly] // bboxSize="-1 -1 -1" SFVec3f [initializeOnly] // > // <!-- ShapeChildContentModel --> // "ShapeChildContentModel is the child-node content model corresponding to X3DShapeNode. ShapeChildContentModel can contain a single Appearance node and a // single geometry node, in any order. // A ProtoInstance node (with the proper node type) can be substituted for any node in this content model." // </Shape> // A Shape node is unlit if either of the following is true: // The shape's appearance field is NULL (default). // The material field in the Appearance node is NULL (default). // NOTE Geometry nodes that represent lines or points do not support lighting. void X3DImporter::ParseNode_Shape_Shape() { std::string use, def; CX3DImporter_NodeElement* ne( nullptr ); MACRO_ATTRREAD_LOOPBEG; MACRO_ATTRREAD_CHECKUSEDEF_RET(def, use); MACRO_ATTRREAD_LOOPEND; // if "USE" defined then find already defined element. if(!use.empty()) { MACRO_USE_CHECKANDAPPLY(def, use, ENET_Shape, ne); } else { // create and if needed - define new geometry object. ne = new CX3DImporter_NodeElement_Shape(NodeElement_Cur); if(!def.empty()) ne->ID = def; // check for child nodes if(!mReader->isEmptyElement()) { ParseHelper_Node_Enter(ne); MACRO_NODECHECK_LOOPBEGIN("Shape"); // check for appearance node if(XML_CheckNode_NameEqual("Appearance")) { ParseNode_Shape_Appearance(); continue; } // check for X3DGeometryNodes if(XML_CheckNode_NameEqual("Arc2D")) { ParseNode_Geometry2D_Arc2D(); continue; } if(XML_CheckNode_NameEqual("ArcClose2D")) { ParseNode_Geometry2D_ArcClose2D(); continue; } if(XML_CheckNode_NameEqual("Circle2D")) { ParseNode_Geometry2D_Circle2D(); continue; } if(XML_CheckNode_NameEqual("Disk2D")) { ParseNode_Geometry2D_Disk2D(); continue; } if(XML_CheckNode_NameEqual("Polyline2D")) { ParseNode_Geometry2D_Polyline2D(); continue; } if(XML_CheckNode_NameEqual("Polypoint2D")) { ParseNode_Geometry2D_Polypoint2D(); continue; } if(XML_CheckNode_NameEqual("Rectangle2D")) { ParseNode_Geometry2D_Rectangle2D(); continue; } if(XML_CheckNode_NameEqual("TriangleSet2D")) { ParseNode_Geometry2D_TriangleSet2D(); continue; } if(XML_CheckNode_NameEqual("Box")) { ParseNode_Geometry3D_Box(); continue; } if(XML_CheckNode_NameEqual("Cone")) { ParseNode_Geometry3D_Cone(); continue; } if(XML_CheckNode_NameEqual("Cylinder")) { ParseNode_Geometry3D_Cylinder(); continue; } if(XML_CheckNode_NameEqual("ElevationGrid")) { ParseNode_Geometry3D_ElevationGrid(); continue; } if(XML_CheckNode_NameEqual("Extrusion")) { ParseNode_Geometry3D_Extrusion(); continue; } if(XML_CheckNode_NameEqual("IndexedFaceSet")) { ParseNode_Geometry3D_IndexedFaceSet(); continue; } if(XML_CheckNode_NameEqual("Sphere")) { ParseNode_Geometry3D_Sphere(); continue; } if(XML_CheckNode_NameEqual("IndexedLineSet")) { ParseNode_Rendering_IndexedLineSet(); continue; } if(XML_CheckNode_NameEqual("LineSet")) { ParseNode_Rendering_LineSet(); continue; } if(XML_CheckNode_NameEqual("PointSet")) { ParseNode_Rendering_PointSet(); continue; } if(XML_CheckNode_NameEqual("IndexedTriangleFanSet")) { ParseNode_Rendering_IndexedTriangleFanSet(); continue; } if(XML_CheckNode_NameEqual("IndexedTriangleSet")) { ParseNode_Rendering_IndexedTriangleSet(); continue; } if(XML_CheckNode_NameEqual("IndexedTriangleStripSet")) { ParseNode_Rendering_IndexedTriangleStripSet(); continue; } if(XML_CheckNode_NameEqual("TriangleFanSet")) { ParseNode_Rendering_TriangleFanSet(); continue; } if(XML_CheckNode_NameEqual("TriangleSet")) { ParseNode_Rendering_TriangleSet(); continue; } if(XML_CheckNode_NameEqual("TriangleStripSet")) { ParseNode_Rendering_TriangleStripSet(); continue; } // check for X3DMetadataObject if(!ParseHelper_CheckRead_X3DMetadataObject()) XML_CheckNode_SkipUnsupported("Shape"); MACRO_NODECHECK_LOOPEND("Shape"); ParseHelper_Node_Exit(); }// if(!mReader->isEmptyElement()) else { NodeElement_Cur->Child.push_back(ne);// add made object as child to current element } NodeElement_List.push_back(ne);// add element to node element list because its a new object in graph }// if(!use.empty()) else } // <Appearance // DEF="" ID // USE="" IDREF // > // <!-- AppearanceChildContentModel --> // "Child-node content model corresponding to X3DAppearanceChildNode. Appearance can contain FillProperties, LineProperties, Material, any Texture node and // any TextureTransform node, in any order. No more than one instance of these nodes is allowed. Appearance may also contain multiple shaders (ComposedShader, // PackagedShader, ProgramShader). // A ProtoInstance node (with the proper node type) can be substituted for any node in this content model." // </Appearance> void X3DImporter::ParseNode_Shape_Appearance() { std::string use, def; CX3DImporter_NodeElement* ne( nullptr ); MACRO_ATTRREAD_LOOPBEG; MACRO_ATTRREAD_CHECKUSEDEF_RET(def, use); MACRO_ATTRREAD_LOOPEND; // if "USE" defined then find already defined element. if(!use.empty()) { MACRO_USE_CHECKANDAPPLY(def, use, ENET_Appearance, ne); } else { // create and if needed - define new geometry object. ne = new CX3DImporter_NodeElement_Appearance(NodeElement_Cur); if(!def.empty()) ne->ID = def; // check for child nodes if(!mReader->isEmptyElement()) { ParseHelper_Node_Enter(ne); MACRO_NODECHECK_LOOPBEGIN("Appearance"); if(XML_CheckNode_NameEqual("Material")) { ParseNode_Shape_Material(); continue; } if(XML_CheckNode_NameEqual("ImageTexture")) { ParseNode_Texturing_ImageTexture(); continue; } if(XML_CheckNode_NameEqual("TextureTransform")) { ParseNode_Texturing_TextureTransform(); continue; } // check for X3DMetadataObject if(!ParseHelper_CheckRead_X3DMetadataObject()) XML_CheckNode_SkipUnsupported("Appearance"); MACRO_NODECHECK_LOOPEND("Appearance"); ParseHelper_Node_Exit(); }// if(!mReader->isEmptyElement()) else { NodeElement_Cur->Child.push_back(ne);// add made object as child to current element } NodeElement_List.push_back(ne);// add element to node element list because its a new object in graph }// if(!use.empty()) else } // <Material // DEF="" ID // USE="" IDREF // ambientIntensity="0.2" SFFloat [inputOutput] // diffuseColor="0.8 0.8 0.8" SFColor [inputOutput] // emissiveColor="0 0 0" SFColor [inputOutput] // shininess="0.2" SFFloat [inputOutput] // specularColor="0 0 0" SFColor [inputOutput] // transparency="0" SFFloat [inputOutput] // /> void X3DImporter::ParseNode_Shape_Material() { std::string use, def; float ambientIntensity = 0.2f; float shininess = 0.2f; float transparency = 0; aiColor3D diffuseColor(0.8f, 0.8f, 0.8f); aiColor3D emissiveColor(0, 0, 0); aiColor3D specularColor(0, 0, 0); CX3DImporter_NodeElement* ne( nullptr ); MACRO_ATTRREAD_LOOPBEG; MACRO_ATTRREAD_CHECKUSEDEF_RET(def, use); MACRO_ATTRREAD_CHECK_RET("ambientIntensity", ambientIntensity, XML_ReadNode_GetAttrVal_AsFloat); MACRO_ATTRREAD_CHECK_RET("shininess", shininess, XML_ReadNode_GetAttrVal_AsFloat); MACRO_ATTRREAD_CHECK_RET("transparency", transparency, XML_ReadNode_GetAttrVal_AsFloat); MACRO_ATTRREAD_CHECK_REF("diffuseColor", diffuseColor, XML_ReadNode_GetAttrVal_AsCol3f); MACRO_ATTRREAD_CHECK_REF("emissiveColor", emissiveColor, XML_ReadNode_GetAttrVal_AsCol3f); MACRO_ATTRREAD_CHECK_REF("specularColor", specularColor, XML_ReadNode_GetAttrVal_AsCol3f); MACRO_ATTRREAD_LOOPEND; // if "USE" defined then find already defined element. if(!use.empty()) { MACRO_USE_CHECKANDAPPLY(def, use, ENET_Material, ne); } else { // create and if needed - define new geometry object. ne = new CX3DImporter_NodeElement_Material(NodeElement_Cur); if(!def.empty()) ne->ID = def; ((CX3DImporter_NodeElement_Material*)ne)->AmbientIntensity = ambientIntensity; ((CX3DImporter_NodeElement_Material*)ne)->Shininess = shininess; ((CX3DImporter_NodeElement_Material*)ne)->Transparency = transparency; ((CX3DImporter_NodeElement_Material*)ne)->DiffuseColor = diffuseColor; ((CX3DImporter_NodeElement_Material*)ne)->EmissiveColor = emissiveColor; ((CX3DImporter_NodeElement_Material*)ne)->SpecularColor = specularColor; // check for child nodes if(!mReader->isEmptyElement()) ParseNode_Metadata(ne, "Material"); else NodeElement_Cur->Child.push_back(ne);// add made object as child to current element NodeElement_List.push_back(ne);// add element to node element list because its a new object in graph }// if(!use.empty()) else } }// namespace Assimp #endif // !ASSIMP_BUILD_NO_X3D_IMPORTER
10,865
3,902
/******************************************************************************* * Copyright 2016 -- 2022 IBM Corporation * * 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. *******************************************************************************/ /***************************************************************************** * @file commom.cpp * @brief Common functions for testbenches - body. * * @date September 2021 * @author FAB, WEI, NGL, DID, DCO * * @ingroup IBMZRL * @addtogroup IBMZRL * \{ *****************************************************************************/ #include "../include/common.hpp" using namespace std; /***************************************************************************** * @brief Initialize an input data stream from a file. * * @param[in] sDataStream the input data stream to set. * @param[in] dataStreamName the name of the data stream. * @param[in] inpFileName the name of the input file to read from. * @return OK if successful otherwise KO. ******************************************************************************/ bool setInputDataStream(stream<UdpWord> &sDataStream, const string dataStreamName, const string inpFileName, int simCnt) { string strLine; ifstream inpFileStream; string datFile = "../../../../test/" + inpFileName; UdpWord udpWord=NetworkWord(0,0,0); //-- STEP-1 : OPEN FILE inpFileStream.open(datFile.c_str()); if ( !inpFileStream ) { cout << "### ERROR : Could not open the input data file " << datFile << endl; return(KO); } //-- STEP-2 : SET DATA STREAM while (inpFileStream) { if (!inpFileStream.eof()) { getline(inpFileStream, strLine); if (strLine.empty()) continue; sscanf(strLine.c_str(), "%llx %x %d", &udpWord.tdata, &udpWord.tkeep, &udpWord.tlast); // Write to sDataStream if (sDataStream.full()) { printf("### ERROR : Stream is full. Cannot write stream with data from file \"%s\".\n", inpFileName.c_str()); return(KO); } else { sDataStream.write(udpWord); // Print Data to console #if DEBUG_LEVEL == TRACE_ALL printf("[%4.4d] TB is filling input stream [%s] - Data write = {D=0x%16.16llX, K=0x%2.2X, L=%d} \n", simCnt, dataStreamName.c_str(), udpWord.tdata.to_long(), udpWord.tkeep.to_int(), udpWord.tlast.to_int()); #endif } } } //-- STEP-3: CLOSE FILE inpFileStream.close(); //strLine.clear(); return(OK); } /***************************************************************************** * @brief Read data from a stream. * * @param[in] sDataStream, the output data stream to read. * @param[in] dataStreamName, the name of the data stream. * @param[out] udpWord, a pointer to the storage location of the data * to read. * @return VALID if a data was read, otherwise UNVALID. ******************************************************************************/ bool readDataStream(stream <UdpWord> &sDataStream, UdpWord *udpWord) { // Get the DUT/Data results sDataStream.read(*udpWord); return(VALID); } /***************************************************************************** * @brief Pack an array of 8 x ap_uint<8> into a ap_uint<64> word. * * @param[in] buffer A pointer to an array of 8 x ap_uint<8> * @return An ap_uint<64> word. ******************************************************************************/ ap_uint<64> pack_ap_uint_64_ (ap_uint<8> *buffer) { ap_uint<64> value = 0; value = buffer[7]; value = (value << 8 ) + buffer[6]; value = (value << 8 ) + buffer[5]; value = (value << 8 ) + buffer[4]; value = (value << 8 ) + buffer[3]; value = (value << 8 ) + buffer[2]; value = (value << 8 ) + buffer[1]; value = (value << 8 ) + buffer[0]; return value ; } /***************************************************************************** * @brief Unpack an ap_uint<64> word to an array of 8 x ap_uint<8>. * * @param[in] buffer A pointer to an ap_uint<64> word * @return An ap_uint<64> word. ******************************************************************************/ void unpack_ap_uint_64_ (ap_uint<64> value, ap_uint<8> *buffer) { for (unsigned int i=0; i<8; i++) { buffer[i] = (value >> 8*i ); } } /***************************************************************************** * @brief Dump a data word to a file. * * @param[in] udpWord, a pointer to the data word to dump. * @param[in] outFileStream,the output file stream to write to. * @return OK if successful, otherwise KO. ******************************************************************************/ bool dumpDataToFile(UdpWord *udpWord, ofstream &outFileStream) { if (!outFileStream.is_open()) { printf("### ERROR : Output file stream is not open. \n"); return(KO); } outFileStream << hex << noshowbase << setfill('0') << setw(16) << udpWord->tdata.to_uint64(); outFileStream << " "; outFileStream << hex << noshowbase << setfill('0') << setw(2) << udpWord->tkeep.to_int(); outFileStream << " "; outFileStream << setw(1) << udpWord->tlast.to_int() << "\n"; return(OK); } /***************************************************************************** * @brief Fill an output file with data from an output stream. * * @param[in] sDataStream, the output data stream to set. * @param[in] dataStreamName, the name of the data stream. * @param[in] outFileName, the name of the output file to write to. * @return OK if successful, otherwise KO. ******************************************************************************/ bool getOutputDataStream(stream<UdpWord> &sDataStream, const string dataStreamName, const string outFileName, int simCnt) { //string strLine; ofstream outFileStream; string datFile = "../../../../test/" + outFileName; UdpWord udpWord=NetworkWord(0,0,0); bool rc = OK; //-- STEP-1 : OPEN FILE outFileStream.open(datFile.c_str()); if ( !outFileStream ) { cout << "### ERROR : Could not open the output data file " << datFile << endl; return(KO); } //-- STEP-2 : EMPTY STREAM AND DUMP DATA TO FILE while (!sDataStream.empty()) { if (readDataStream(sDataStream, &udpWord) == VALID) { // Print DUT/Data to console #if DEBUG_LEVEL == TRACE_ALL printf("[%4.4d] TB is draining output stream [%s] - Data read = {D=0x%16.16llX, K=0x%2.2X, L=%d} \n", simCnt, dataStreamName.c_str(), udpWord.tdata.to_long(), udpWord.tkeep.to_int(), udpWord.tlast.to_int()); #endif if (!dumpDataToFile(&udpWord, outFileStream)) { rc = KO; break; } } } //-- STEP-3: CLOSE FILE outFileStream.close(); return(rc); } /***************************************************************************** * @brief Fill an output file with data from an image. * * * @param[in] sDataStream the input image in xf::cv::Mat format. * @param[in] outFileName the name of the output file to write to. * @return OK if successful, otherwise KO. ******************************************************************************/ bool dumpStringToFile(const string s, const string outFileName, int simCnt) { //string strLine; ofstream outFileStream; string datFile = "../../../../test/" + outFileName; UdpWord udpWord=NetworkWord(0,0,0); bool rc = OK; unsigned int bytes_per_line = 8; //-- STEP-1 : OPEN FILE outFileStream.open(datFile.c_str()); if ( !outFileStream ) { cout << "### ERROR : Could not open the output data file " << datFile << endl; return(KO); } #if DEBUG_LEVEL == TRACE_ALL printf("came to dumpStringToFile: s.length()=%u\n", s.length()); #endif ap_uint<8> value[bytes_per_line]; unsigned int total_bytes = 0; //-- STEP-2 : DUMP STRING DATA TO FILE for (unsigned int i = 0; i < s.length(); i+=bytes_per_line, total_bytes+=bytes_per_line) { //if (NPIX == XF_NPPC8) { for (unsigned int k = 0; k < bytes_per_line; k++) { if (i+k < s.length()) { value[k] = s[i+k]; } else { value[k] = 0; } #if DEBUG_LEVEL == TRACE_ALL printf("DEBUG: In dumpStringToFile: value[%u]=%c\n", k, (char)value[k]); #endif } udpWord.tdata = pack_ap_uint_64_(value); udpWord.tkeep = 255; // We are signaling a packet termination either at the end of the image or the end of MTU if ((total_bytes >= (s.length() - bytes_per_line)) || ((total_bytes + bytes_per_line) % PACK_SIZE == 0)) { udpWord.tlast = 1; } else { udpWord.tlast = 0; } #if DEBUG_LEVEL == TRACE_ALL printf("[%4.4d] IMG TB is dumping string to file [%s] - Data read [%u] = {val=%u, D=0x%16.16llX, K=0x%2.2X, L=%d} \n", simCnt, datFile.c_str(), total_bytes, value, udpWord.tdata.to_long(), udpWord.tkeep.to_int(), udpWord.tlast.to_int()); #endif if (!dumpDataToFile(&udpWord, outFileStream)) { rc = KO; break; } } //-- STEP-3: CLOSE FILE outFileStream.close(); return(rc); } /***************************************************************************** * @brief Fill an output file with data from an image. * * * @param[in] sDataStream the input image in xf::cv::Mat format. * @param[in] outFileName the name of the output file to write to. * @return OK if successful, otherwise KO. ******************************************************************************/ bool dumpStringToFileOnlyRawData(const string s, const string outFileName, int simCnt, size_t out_size) { //printStringHex(s, out_size); //string strLine; ofstream outFileStream; string datFile = outFileName; //"../../../../test/" + outFileName; bool rc = OK; unsigned int bytes_per_line = 8; ap_uint<64> tdata = 0; //-- STEP-1 : OPEN FILE outFileStream.open(datFile.c_str()); if ( !outFileStream ) { cout << "### ERROR : Could not open the output data file " << datFile << endl; return(KO); } #if DEBUG_LEVEL == TRACE_ALL printf("came to dumpStringToFileOnlyRawData: s.length()=%u\n", out_size); #endif ap_uint<8> value[bytes_per_line]; unsigned int total_bytes = 0; //-- STEP-2 : DUMP STRING DATA TO FILE for (unsigned int i = 0; i < out_size; i+=bytes_per_line, total_bytes+=bytes_per_line) { for (unsigned int k = 0; k < bytes_per_line; k++) { if (i+k < out_size) { value[k] = s[i+k]; } else { value[k] = 0; } #if DEBUG_LEVEL == TRACE_ALL printf("DEBUG: In dumpStringToFileOnlyRawData: value[%u]=%c\n", k, (char)value[k]); #endif } tdata = pack_ap_uint_64_(value); #if DEBUG_LEVEL == TRACE_ALL printf("[%4.4d] IMG TB is dumping string to file [%s] - Data read [%u] = {val=%u, D=0x%16.16llX} \n", simCnt, datFile.c_str(), total_bytes, value, tdata.to_long()); #endif outFileStream << hex << setfill('0') << setw(16) << tdata.to_uint64(); //outFileStream << hex << noshowbase << setfill('0') << setw(16) << tdata.to_uint64(); outFileStream << "\n"; } //-- STEP-3: CLOSE FILE outFileStream.close(); return(rc); } /***************************************************************************** * @brief Fill an output file with data from a string and * set the tlast every gno packets * * * @param[in] sDataStream the input image in xf::cv::Mat format. * @param[in] outFileName the name of the output file to write to. * @param[in] simCnt * @param[in] gno the counter value at which this function set the tlast=1 * @return OK if successful, otherwise KO. ******************************************************************************/ bool dumpStringToFileWithLastSetEveryGnoPackets(string s, const string outFileName, int simCnt, int gno) { string strLine; ofstream outFileStream; string datFile = "../../../../test/" + outFileName; UdpWord udpWord=NetworkWord(0,0,0); bool rc = OK; unsigned int bytes_per_line = 8; //-- STEP-1 : OPEN FILE outFileStream.open(datFile.c_str()); if ( !outFileStream ) { cout << "### ERROR : Could not open the output data file " << datFile << endl; return(KO); } #if DEBUG_LEVEL == TRACE_ALL printf("came to dumpStringToFile: s.length()=%u\n", s.length()); #endif ap_uint<8> value[bytes_per_line]; unsigned int total_bytes = 0; int cntr = 0; //-- STEP-2 : DUMP STRING DATA TO FILE for (unsigned int i = 0; i < s.length(); cntr += 1, i+=bytes_per_line, total_bytes+=bytes_per_line) { //if (NPIX == XF_NPPC8) { for (unsigned int k = 0; k < bytes_per_line; k++) { if (i+k < s.length()) { value[k] = s[i+k]; } else { value[k] = 0; } #if DEBUG_LEVEL == TRACE_ALL printf("DEBUG: In dumpStringToFile: value[%u]=%c\n", k, (char)value[k]); #endif } udpWord.tdata = pack_ap_uint_64_(value); udpWord.tkeep = 255; // We are signaling a packet termination either at the end of the image or the end of MTU if ((total_bytes >= (s.length() - bytes_per_line)) || ((total_bytes + bytes_per_line) % PACK_SIZE == 0) || ( cntr!= 0 && ((cntr+1) % gno == 0))) { udpWord.tlast = 1; } else { udpWord.tlast = 0; } #if DEBUG_LEVEL == TRACE_ALL printf("[%4.4d] IMG TB is dumping string to file [%s] - Data read [%u] = {val=%u, D=0x%16.16llX, K=0x%2.2X, L=%d} \n", simCnt, datFile.c_str(), total_bytes, value, udpWord.tdata.to_long(), udpWord.tkeep.to_int(), udpWord.tlast.to_int()); #endif if (!dumpDataToFile(&udpWord, outFileStream)) { rc = KO; break; } } //-- STEP-3: CLOSE FILE outFileStream.close(); return(rc); } /***************************************************************************** * @brief Initialize an input data stream from a file. * * @param[in] inpFileName the name of the input file to read from. * @param[out] strOutput the output string to set. * @return OK if successful otherwise KO. ******************************************************************************/ bool dumpFileToString(const string inpFileName, char* charOutput, int simCnt) { string strLine; ifstream inpFileStream; string datFile = "../../../../test/" + inpFileName; UdpWord udpWord=NetworkWord(0,0,0); unsigned int i = 0; unsigned int bytes_per_line = 8; ap_uint<8> value[bytes_per_line]; for(i=0; i < bytes_per_line; i++){ value[i]=0; } i=0; //-- STEP-1 : OPEN FILE inpFileStream.open(datFile.c_str()); if ( !inpFileStream ) { cout << "### ERROR : Could not open the input data file " << datFile << endl; return(KO); } //-- STEP-2 : SET DATA STREAM while (inpFileStream) { if (!inpFileStream.eof()) { getline(inpFileStream, strLine); //cout << strLine << endl; if (strLine.empty()) continue; sscanf(strLine.c_str(), "%llx %x %d", &udpWord.tdata, &udpWord.tkeep, &udpWord.tlast); // Write to strOutput //printf("Debug: (char)udpWord.tdata.to_long()=%c\n", (char)udpWord.tdata.to_long()); unpack_ap_uint_64_(udpWord.tdata, value); for (unsigned int k = 0; k < bytes_per_line; k++) { charOutput[i++] = value[k]; // Print Data to console #if DEBUG_LEVEL == TRACE_ALL printf("[%4.4d] TB is filling string with character %c\n", simCnt, (char)value[k]); #endif } } } //-- STEP-3: CLOSE FILE inpFileStream.close(); //strLine.clear(); return(OK); } /***************************************************************************** * @brief Initialize an input data stream from a file with only data * * @param[in] inpFileName the name of the input file to read from. * @param[out] strOutput the output string to set. * @return OK if successful otherwise KO. ******************************************************************************/ template<unsigned int bytes_per_line = 8> string dumpFileToStringRawDataString(const string inpFileName, int * rawdatalines, size_t outputSize) { string strLine; string tmp_Out; ifstream inpFileStream; string datFile = inpFileName; string charOutput; //charOutput.reserve(outputSize); //strLine.reserve(outputSize); //tmp_Out.reserve(bytes_per_line); unsigned long long int mylongunsigned; unsigned long long int zero_byte=0; unsigned int i = 0; char my_tmp_buf [bytes_per_line]; //-- STEP-1 : OPEN FILE inpFileStream.open(datFile.c_str()); if ( !inpFileStream ) { cout << "### ERROR : Could not open the input data file " << datFile << endl; return ""; } //-- STEP-2 : SET DATA STREAM while (inpFileStream) { if (!inpFileStream.eof()) { getline(inpFileStream, strLine); memcpy(my_tmp_buf,&zero_byte, bytes_per_line); if (strLine.empty()) continue; *rawdatalines+=1; mylongunsigned=stoul(strLine,nullptr,16); hex2ascii(strLine, tmp_Out); // Write to strOutput memcpy(my_tmp_buf,(char *)&mylongunsigned, sizeof(unsigned long long int)); charOutput.append(my_tmp_buf, bytes_per_line); i++; } } //-- STEP-3: CLOSE FILE inpFileStream.close(); //tmp_Out.clear(); return string(charOutput); } /***************************************************************************** * @brief convert a char to its hexadecimal representation. * * @param[in] c the standard char value to convert to hex * @return the hexadecimal value of the input ******************************************************************************/ // C++98 guarantees that '0', '1', ... '9' are consecutive. // It only guarantees that 'a' ... 'f' and 'A' ... 'F' are // in increasing order, but the only two alternative encodings // of the basic source character set that are still used by // anyone today (ASCII and EBCDIC) make them consecutive. unsigned char hexval(unsigned char c) { if ('0' <= c && c <= '9') return c - '0'; else if ('a' <= c && c <= 'f') return c - 'a' + 10; else if ('A' <= c && c <= 'F') return c - 'A' + 10; else abort(); } /***************************************************************************** * @brief Convert a hexadecimal string to a ascii string *FIXME: * @param[in] in the input hexadecimal string * @param[out] out the output ascii string ******************************************************************************/ void hex2ascii(const string& in, string& out) { out.clear(); out.reserve(in.length() / 2); for (string::const_iterator p = in.begin(); p != in.end(); p++) { unsigned char c = hexval(*p); p++; if (p == in.end()) break; // incomplete last digit - should report error c = (c << 4) + hexval(*p); // + takes precedence over << out.push_back(c); } } /***************************************************************************** * @brief Convert a ascii string to a hexadecimal string *FIXME: * @param[in] in the input ascii string * @param[out] out the output hexadecimal string ******************************************************************************/ void ascii2hex(const string& in, string& out) { std::stringstream sstream; for ( string::const_iterator item = in.begin(); item != in.end(); item++){ sstream << std::hex << int(*item); } out=sstream.str(); } /***************************************************************************** * @brief Convert a ascii string to a hexadecimal string *FIXME: * @param[in] in the input ascii string * @param[out] out the output hexadecimal string * @param[in] bytesize the input ascii string size ******************************************************************************/ void ascii2hexWithSize(const string& in, string& out, size_t bytesize) { std::stringstream sstream; for ( int i=0; i<bytesize; i++){ sstream << std::hex << int(in[i]); } out=sstream.str(); } /***************************************************************************** * @brief Check the presence of a given corner value at the begin and the end of a string * * @param[in] str the input string to be checked * @param[in] corner the corner char to find * @return true if it is present, false otherwise ******************************************************************************/ bool isCornerPresent(string str, string corner) { int n = str.length(); int cl = corner.length(); // If length of corner string is more, it // cannot be present at corners. if (n < cl) return false; // Return true if corner string is present at // both corners of given string. return (str.substr(0, cl).compare(corner) == 0 && str.substr(n-cl, cl).compare(corner) == 0); } /***************************************************************************** * @brief Convert a hex string to a integer into a char buffer with the SAME dimensions *FIXME: * @param[in] in the input hex string * @param[out] out the output numerical hexadec string string * @param[in] byteSize the bytesize of the input string and the buffer, it assumes equal dimension ******************************************************************************/ template<typename T> void string2hexnumerics(const string& in, char * out, size_t byteSize) { for (unsigned int i = 0; i < byteSize; i++) { std::sprintf(out+i, "%d", (T)in[i]); } } void stringHex2Unsigned(const string& in, unsigned int * out, size_t byteSize) { for (unsigned int i = 0; i < byteSize; i++) { std::sprintf((char*)out+i, "%u", (unsigned int)in[i]); } } /***************************************************************************** * @brief Convert a hex string to a integer into a char buffer with the SAME dimensions * FIXME: * @param[in] in the input hex string * @param[out] out the output numerical hexadec string string * @param[in] byteSize the bytesize of the input string and the buffer, it assumes equal dimension ******************************************************************************/ void string2hexnumericsString(const string& in, string &out, size_t byteSize) { char tmp_out [byteSize]; for (unsigned int i = 0; i < byteSize; i++) { std::sprintf(tmp_out+i, "%d", (int)in[i]); } out.append(tmp_out); } /***************************************************************************** * @brief Create the commands for a memory test with start/max address to test-nop to execute-stop * * @param[in] mem_address max target address to test * @param[out] out the output string with start/max address-nops4trgtCCsNeeded-stop * @param[in] testingNumber the number of tests to perform on the memory * ******************************************************************************/ template<unsigned int bytes_per_line = 8> string createMemTestCommands(unsigned long long int mem_address, unsigned int testingNumber, unsigned int burst_size) { string out; char start_cmd [bytes_per_line]; char stop_cmd [bytes_per_line]; char value_cmd[bytes_per_line]; char burst_cmd[bytes_per_line]; //WARNING: currently hardcoded way of start and stop commands with a 1 and 2 for start and stop respectively for (unsigned int k = 0; k < bytes_per_line; k++) { value_cmd[k] = (char)0; if (k != 0) { stop_cmd[k] = (char)0; start_cmd[k] = (char)0; burst_cmd[k] = (char)0; } else { start_cmd[k] = (char)1; stop_cmd[k] = (char)2; burst_cmd[k] = (char)4; } } memcpy(start_cmd+1, (char*)&testingNumber, 2); out = out.append(start_cmd,3); memcpy(value_cmd, (char*)&mem_address, 5); out = out.append(value_cmd,5); memcpy(burst_cmd+1,(char*)&burst_size,2); out = out.append(burst_cmd,8); return string(out); } /***************************************************************************** * @brief Create the expected output results for the memory test (with FAULT INJECTION) * * @param[in] mem_address max target address to test * @param[out] out the results of the memory test (with FAULT INJECTION) * @param[in] testingNumber the number of tests to perform on the memory * ******************************************************************************/ template<unsigned int bytes_per_line = 8> string createMemTestGoldenOutput(unsigned long long int mem_address, unsigned int testingNumber, bool with_bw_analysis) { char addr_cmd [bytes_per_line]; // Half of the command filled with start other half with the address char fault_cntr_cmd [bytes_per_line]; char fault_addr_cmd [bytes_per_line]; char filler_cmd [bytes_per_line]; char clock_cycles_cmd [bytes_per_line]; char end_of_tests_cmd [bytes_per_line]; char stop_cmd [bytes_per_line]; unsigned int fault_addr = 0; unsigned int clock_cycles = 0; const unsigned int first_faultTests = 3; string out; //given parameters unsigned int mem_word_size = 512; unsigned int mem_size_of_word_size = 20; // computations the first faulty address and the the fault counter unsigned int mem_addr_per_word = mem_word_size / 8; // byte size of this word unsigned int fault_cntr = 0; //precomputing the cc clock_cycles = mem_address % mem_addr_per_word == 0 ? mem_address / mem_addr_per_word : (unsigned int) mem_address / mem_addr_per_word + 1; //simulating the fault injection for (unsigned int j = 1; j < mem_address/64; j++) { ap_uint<512> currentNumber = j; ap_uint<512> nextNumber = (currentNumber+1) xor 1; ap_uint<512> tmpNumber = nextNumber; tmpNumber = nextNumber & 0; if( nextNumber != (tmpNumber)){ fault_cntr+=1; } } // for (unsigned int j = 0; j < mem_address; j+=mem_addr_per_word) // { // ap_uint<32> currentNumber = j; // ap_uint<32> nextNumber = (currentNumber+1) xor 1; // ap_uint<32> prevNumber = currentNumber; // ap_uint<32> tmpNumber = nextNumber; // ap_uint<32> mask = 0; // for (unsigned int i = 0; i < mem_word_size/32 && j > 0; i++){ // tmpNumber = nextNumber & 0; // if( nextNumber != (tmpNumber)){ // fault_cntr+=1; // } // prevNumber = currentNumber; // currentNumber = nextNumber; // nextNumber = (nextNumber + 1 ) xor i; // } // } //init the commands and fill em out of the fault simulation before for(unsigned int i = 0; i < testingNumber; i++){ for (unsigned int k = 0; k < bytes_per_line; k++) { addr_cmd[k] = (char)0; filler_cmd[k] = (char)0; fault_cntr_cmd[k] = (char)0; fault_addr_cmd[k] = (char)0; stop_cmd[k] = (char)0; stop_cmd[k] = (char)0; end_of_tests_cmd[k] = (char)0; clock_cycles_cmd[k] = (char)0; } stop_cmd[0] = (char)2; end_of_tests_cmd[0] = (char)3; memcpy(end_of_tests_cmd+1, (char*)&testingNumber, 2); memcpy(addr_cmd, (char*)&mem_address, sizeof(unsigned long long int)); out = out.append(addr_cmd,bytes_per_line); //if not yet in the fault injection point just let em empty as expected from good tests if(i < first_faultTests-1 || mem_address <= mem_addr_per_word) { out = out.append(filler_cmd,bytes_per_line); out = out.append(filler_cmd,bytes_per_line); }else{ memcpy(fault_cntr_cmd, (char*)&fault_cntr, sizeof(unsigned int)); out = out.append(fault_cntr_cmd,bytes_per_line); memcpy(fault_addr_cmd, (char*)&mem_addr_per_word, sizeof(unsigned int)); out = out.append(fault_addr_cmd,bytes_per_line); } // memcpy(clock_cycles_cmd, (char*)&clock_cycles, sizeof(unsigned int)); // memcpy(clock_cycles_cmd+sizeof(unsigned int), (char*)&clock_cycles, sizeof(unsigned int)); // out = out.append(clock_cycles_cmd,bytes_per_line); ////TODO: to make everything pass at the csim lvl since cc of read count always one const unsigned int dummycc=1; memcpy(clock_cycles_cmd,(char*)& dummycc, sizeof(unsigned int)); out = out.append(clock_cycles_cmd,bytes_per_line);//read out = out.append(filler_cmd,bytes_per_line);//write } out = out.append(end_of_tests_cmd,bytes_per_line); // out.append(stop_cmd,bytes_per_line); return string(out); } /***************************************************************************** * @brief Create the expected output results for the uppercase * * @param[in] input_string the input string of the uppercase * * @return out the results of the uppercase ******************************************************************************/ std::string createUppercaseGoldenOutput(std::string input_string){ std::string strGold; strGold = input_string; uppercase_conversion: for (unsigned int i = 0; i < strGold.length(); i++ ) { if (strGold[i] >= 'a' && strGold[i] <= 'z'){ strGold[i] = strGold[i] - ('a' - 'A'); } } return strGold; } /***************************************************************************** * @brief reverse a given string * * @param[in] str the string to reverse. * @return nothing, print to stdout. ******************************************************************************/ void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } /***************************************************************************** * @brief Parse the memory test output contained in astring with a given size * * @param[in] longbuf the buffer containing the output * @param[in] charOutputSize the bytesize of the buffer * @param[in] rawdatalines the number of lines in the given outbuf * @return vectpr of MemoryTestResult data strcuture ******************************************************************************/ template<unsigned int bytes_per_line=8> std::vector<MemoryTestResult> parseMemoryTestOutput(const string longbuf, size_t charOutputSize, int rawdatalines) { std::vector<MemoryTestResult> testResults_vector; int rawiterations = charOutputSize / 8; //should be equivalent to rawdatalines unsigned int mem_word_size = 512; unsigned int mem_word_byte_size = mem_word_size/8; bool is_stop_present = rawdatalines % (3+1+1) == 0; //guard to check if multiple data of 3 64bytes or with int k = 1; char myTmpOutBuff [bytes_per_line]; for (int i = 0; i < bytes_per_line; ++i) { myTmpOutBuff[i]=(char)0; } unsigned int testingNumber_out=0, fault_cntr_out=0, fault_addr_out=0; unsigned long long int max_memory_addr_out=0, clock_cycles_read=0, clock_cycles_write=0; for (int i = 1; i < rawdatalines+1; i++) { string tmp_outbuff; tmp_outbuff= longbuf.substr((i-1)*bytes_per_line,bytes_per_line); if(is_stop_present && k==7){ cout << "DEBUG the stop is present and is here" << endl; } else if( ( (i == rawdatalines-1) || (i == rawdatalines) ) && k==6){ //check it is either the last or one before the last //substr extraction and parsing //strncpy(myTmpOutBuff,tmp_outbuff.c_str()+1,bytes_per_line-1); //testingNumber_out = *reinterpret_cast<unsigned long long*>(myTmpOutBuff); memcpy(&testingNumber_out,tmp_outbuff.c_str()+1,bytes_per_line/2); #if DEBUG_LEVEL == TRACE_ALL cout << "DEBUG last command with the iterations " << testingNumber_out << endl; #endif }else if(k==5){ //strncpy(myTmpOutBuff,tmp_outbuff.c_str(),bytes_per_line); //clock_cycles_read = *reinterpret_cast<unsigned long long int*>(myTmpOutBuff); memcpy(&clock_cycles_read,tmp_outbuff.c_str(),bytes_per_line); #if DEBUG_LEVEL == TRACE_ALL cout << "DEBUG clock_cycles_read (or the fourth half data pckt) " << clock_cycles_read << endl; cout << "DEBUG clock_cycles_write (or the fourth half data pckt) " << clock_cycles_write << endl; #endif MemoryTestResult tmpResult(max_memory_addr_out,fault_cntr_out,fault_addr_out,clock_cycles_write,clock_cycles_read); testResults_vector.push_back(tmpResult); if(!( (i+1 == rawdatalines-1) || (i+1 == rawdatalines) )){ k=0; #if DEBUG_LEVEL == TRACE_ALL cout << "DEBUG reinit the counter" << endl; #endif } unsigned int written_words = max_memory_addr_out%mem_word_byte_size == 0 ? max_memory_addr_out/mem_word_byte_size : max_memory_addr_out/mem_word_byte_size + 1; double rd_bndwdth = ( (double)written_words*(double)mem_word_size / ( (double)tmpResult.clock_cycles_read * ( 6.4 ) ) ); // Gbit/T double wr_bndwdth = ( (double)written_words*(double)mem_word_size / ( (double)tmpResult.clock_cycles_write * ( 6.4 ) ) ); #if DEBUG_LEVEL == TRACE_ALL cout << "Written " << written_words << " words" << endl; cout << "DEBUG overall test results: target address " << tmpResult.target_address << " "; cout << "Fault counter: " << tmpResult.fault_cntr << " "; cout << "First fault at address: " << tmpResult.first_fault_address << " " << endl; cout << " RD BW " << rd_bndwdth << "[GBit/s] with cc equal to " << tmpResult.clock_cycles_read << " " << endl; cout << " WR BW " << wr_bndwdth << "[GBit/s] with cc equal to " << tmpResult.clock_cycles_write << " " << endl; #endif } else if(k==4){ //clock cycless //char mySecondTmpOutBuff[bytes_per_line/2]; //string additional_string; //init the buffer //for(int i=0;i<bytes_per_line;i++){myTmpOutBuff[i]=(char)0;mySecondTmpOutBuff[i%(bytes_per_line/2)]=(char)0;} // additional_string=tmp_outbuff.substr(bytes_per_line/2,bytes_per_line/2); // // tmp_outbuff = tmp_outbuff.erase(bytes_per_line/2,bytes_per_line/2); // strncpy(myTmpOutBuff,tmp_outbuff.c_str(),bytes_per_line/2); // clock_cycles_read = *reinterpret_cast<unsigned int*>(myTmpOutBuff); // // strncpy(mySecondTmpOutBuff,additional_string.c_str(),bytes_per_line/2); // clock_cycles_write = *reinterpret_cast<unsigned int*>(mySecondTmpOutBuff); //strncpy(myTmpOutBuff,tmp_outbuff.c_str(),bytes_per_line); //clock_cycles_write = *reinterpret_cast<unsigned long long int*>(myTmpOutBuff); memcpy(&clock_cycles_write,tmp_outbuff.c_str(),bytes_per_line); }else if(k==3){ // first fault address //substr extraction and parsing //strncpy(myTmpOutBuff,tmp_outbuff.c_str(),bytes_per_line); //fault_addr_out = *reinterpret_cast<unsigned long long int *>(myTmpOutBuff); memcpy(&fault_addr_out,tmp_outbuff.c_str(),bytes_per_line/2); #if DEBUG_LEVEL == TRACE_ALL cout << "DEBUG first fault address (or the third data pckt) " << fault_addr_out << endl; #endif }else if(k==2){ // fault cntr //strncpy(myTmpOutBuff,tmp_outbuff.c_str(),bytes_per_line); //fault_cntr_out = *reinterpret_cast<unsigned long long int *>(myTmpOutBuff); memcpy(&fault_cntr_out,tmp_outbuff.c_str(),bytes_per_line/2); #if DEBUG_LEVEL == TRACE_ALL cout << "DEBUG the fault counters (or the second data pack) " << fault_cntr_out << endl; #endif }else { //max addrss //substr extraction and parsing // strncpy(myTmpOutBuff,tmp_outbuff.c_str(),bytes_per_line); // max_memory_addr_out = *reinterpret_cast<unsigned long long *>(myTmpOutBuff); memcpy(&max_memory_addr_out,tmp_outbuff.c_str(),bytes_per_line); #if DEBUG_LEVEL == TRACE_ALL cout << "DEBUG max address (or the first data pack) " << max_memory_addr_out << endl; #endif } k++; tmp_outbuff.clear(); } return testResults_vector; } /***************************************************************************** * @brief print byte-per-byte a given string in hexadecimal format * * @param[in] inStr string to print * @param[in] strSize bytsize to print (can be even less, NOT more ) * ******************************************************************************/ void printStringHex(const string inStr, size_t strSize){ #if DEBUG_LEVEL == TRACE_ALL printf("Going to print a hex string :D\n"); #endif for (size_t i = 0; i < strSize; i++) { printf("%x",inStr[i]); } printf("\n"); } /***************************************************************************** * @brief print byte-per-byte a given char buff in hexadecimal format * * @param[in] inStr char buff to print * @param[in] strSize bytsize to print (can be even less, NOT more ) * ******************************************************************************/ void printCharBuffHex(const char * inStr, size_t strSize){ #if DEBUG_LEVEL == TRACE_ALL printf("Going to prit a hex char buff :D\n"); #endif for (size_t i = 0; i < strSize; i++) { printf("%x",inStr[i]); } printf("\n"); } /***************************************************************************** * @brief print the binary representation of a target pointer buffer of a given size. * Assumes little endian. * @param[in] size the bytesize to print from ptr. * @param[in] ptr the buffer pointer. * @return nothing, print to stdout. ******************************************************************************/ void printBits(size_t const size, void const * const ptr) { unsigned char *b = (unsigned char*) ptr; unsigned char byte; int i, j; for (i = size-1; i >= 0; i--) { for (j = 7; j >= 0; j--) { byte = (b[i] >> j) & 1; printf("%u", byte); } } puts(""); } static inline ssize_t __file_size(const char *fname) { int rc; struct stat s; rc = lstat(fname, &s); if (rc != 0) { fprintf(stderr, "err: Cannot find %s!\n", fname); return rc; } return s.st_size; } static inline ssize_t __file_read(const char *fname, char *buff, size_t len) { int rc; FILE *fp; if ((fname == NULL) || (buff == NULL) || (len == 0)) return -EINVAL; fp = fopen(fname, "r"); if (!fp) { fprintf(stderr, "err: Cannot open file %s: %s\n", fname, strerror(errno)); return -ENODEV; } rc = fread(buff, len, 1, fp); if (rc == -1) { fprintf(stderr, "err: Cannot read from %s: %s\n", fname, strerror(errno)); fclose(fp); return -EIO; } fclose(fp); return rc; } static inline ssize_t __file_write(const char *fname, const char *buff, size_t len) { int rc; FILE *fp; if ((fname == NULL) || (buff == NULL) || (len == 0)) return -EINVAL; fp = fopen(fname, "w+"); if (!fp) { fprintf(stderr, "err: Cannot open file %s: %s\n", fname, strerror(errno)); return -ENODEV; } rc = fwrite(buff, len, 1, fp); if (rc == -1) { fprintf(stderr, "err: Cannot write to %s: %s\n", fname, strerror(errno)); fclose(fp); return -EIO; } fclose(fp); return rc; } /*! \} */
40,625
13,439
/****************************************************************************** * Copyright 2015-2020 Xilinx, Inc. * * 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. ******************************************************************************/ /* ------------------------------------------------------------------------------- *********************************************** H E A D E R F I L E S *** ------------------------------------------------------------------------------- */ #include <iomanip> #include <iostream> #include "authkeys.h" #include "authentication.h" #include "options.h" /* ------------------------------------------------------------------------------- ***************************************************** F U N C T I O N S *** ------------------------------------------------------------------------------- */ /******************************************************************************/ Key::Key(const std::string& name0) : Loaded(false) , isSecret(false) , name(name0) { keySize = AuthenticationContext::GetRsaKeyLength(); N = new uint8_t [keySize]; N_ext = new uint8_t [keySize]; D = new uint8_t [keySize]; E = new uint8_t [WORD_SIZE_IN_BYTES]; P = new uint8_t [keySize/2]; Q = new uint8_t [keySize/2]; memset(N, 0, keySize); memset(N_ext, 0, keySize); memset(E, 0, WORD_SIZE_IN_BYTES); memset(P, 0, keySize/2); memset(Q, 0, keySize/2); memset(D, 0, keySize); } /******************************************************************************/ Key::Key(const Key& otherKey) { keySize = AuthenticationContext::GetRsaKeyLength(); N = new uint8_t [keySize]; N_ext = new uint8_t [keySize]; D = new uint8_t [keySize]; E = new uint8_t [WORD_SIZE_IN_BYTES]; P = new uint8_t [keySize/2]; Q = new uint8_t [keySize/2]; memcpy(this,&otherKey,sizeof(Key)); } /******************************************************************************/ Key::~Key() { if(N != NULL) { delete[] N; } if(N_ext != NULL) { delete[] N_ext; } if(D != NULL) { delete[] D; } if(E != NULL) { delete[] E; } if(P != NULL) { delete[] P; } if(Q != NULL) { delete[] Q; } } /******************************************************************************/ void Key::ParsePublic(const std::string& filename) { Parse(filename,false); } /******************************************************************************/ void Key::ParseSecret(const std::string& filename) { Parse(filename,true); } /******************************************************************************/ void Key::Parse(const std::string& filename, bool isSecret0) { uint8_t errCode = 0; isSecret = isSecret0; std::string basefile = StringUtils::BaseName(filename); FILE* f; f = fopen(filename.c_str(),"r"); if (f == NULL) { LOG_ERROR("Cannot open key %s", filename.c_str()); } try { int name; do { name = getc(f); } while (name >= 0 && isspace(name)); fseek(f,0,0); /* If the file starts with 'N', then it is Xilinx Format If it starts with '-', then it is OpenSSL format */ if (name == 'N') { errCode = ParseXilinxRsaKey(f); } else if (name == '-') { errCode = ParseOpenSSLKey(f); } else { LOG_ERROR("Unsupported key file - %s\n Supported key formats: Xilinx Format & OpenSSL format", basefile.c_str()); } fclose(f); if(errCode != 0) { LOG_ERROR("RSA authentication key parsing failed - %s", basefile.c_str()); } /* Calculate the modulus extension, i.e. Montgomery Reduction term RR and some sanity check for the keys passed */ { BIGNUM m; m.d = (BN_ULONG*)N; m.dmax = keySize / sizeof(BN_ULONG); m.top = keySize / sizeof(BN_ULONG); m.flags = 0; m.neg = 0; BN_CTX_Class ctxInst; BN_MONT_CTX_Class montClass(ctxInst); montClass.Set(m); montClass.GetModulusExtension(N_ext, m, keySize); } Loaded = true; } catch(...) { fclose(f); throw; } } /******************************************************************************/ uint8_t Key::ParseOpenSSLKey(FILE* f) { RSA_Class rsaInst; OpenSSL_add_all_algorithms(); uint32_t keySzRd; if (isSecret) { rsaInst.rsa = PEM_read_RSAPrivateKey(f, NULL, NULL, NULL); if(rsaInst.rsa == NULL) { return 1; } #if OPENSSL_VERSION_NUMBER > 0x10100000L keySzRd = BN_num_bytes(RSA_get0_n(rsaInst.rsa)); #else keySzRd = BN_num_bytes(rsaInst.rsa->n); #endif if (keySzRd != keySize) { LOG_ERROR("Incorrect Key Size !!!\n\t Key Size is %d bits. Expected key size is %d bits", keySzRd * 8, keySize * 8); } #if OPENSSL_VERSION_NUMBER > 0x10100000L memcpy(D, RSA_get0_d(rsaInst.rsa)->d, keySize); #else memcpy(D, rsaInst.rsa->d->d, keySize); #endif } else { rsaInst.rsa = PEM_read_RSA_PUBKEY(f, NULL, NULL, NULL); if(rsaInst.rsa == NULL) { return 1; } #if OPENSSL_VERSION_NUMBER > 0x10100000L keySzRd = BN_num_bytes(RSA_get0_n(rsaInst.rsa)); #else keySzRd = BN_num_bytes(rsaInst.rsa->n); #endif if (keySzRd != keySize) { LOG_ERROR("Incorrect Key Size !!!\n\t Key Size is %d bits. Expected key size is %d bits", keySzRd * 8, keySize * 8); } memset(D,0,keySize); } #if OPENSSL_VERSION_NUMBER > 0x10100000L memcpy(N, RSA_get0_n(rsaInst.rsa)->d, keySize); memcpy(E, RSA_get0_e(rsaInst.rsa)->d, sizeof(uint32_t)); #else memcpy(N, rsaInst.rsa->n->d, keySize); memcpy(E, rsaInst.rsa->e->d, sizeof(uint32_t)); #endif return 0; } /******************************************************************************/ uint8_t Key::ParseXilinxRsaKey(FILE* f) { int name; /* Check for N in the key file followed by '=', Once got, parse the value of N */ do { name = getc(f); } while (name >= 0 && isspace(name)); if (name != 'N') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected N, got %c", name); return 1; } do { name = getc(f); } while (name >= 0 && isspace(name)); if (name != '=') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected =, got %c", name); return 1; } LOG_TRACE("Parsing 'N' from key file"); Hex2Byte(f, N, keySize); /* Check for E in the key file followed by '=' Once got, parse the value of E */ do { name = getc(f); } while (name >= 0 && isspace(name)); if (name != 'E') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected E, got %c",name); return 1; } do { name = getc(f); } while (name >= 0 && isspace(name)); if (name != '=') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected =, got %c",name); return 1; } uint32_t temp; LOG_TRACE("Parsing 'E' from key file"); if(EOF != fscanf(f,"%X",&temp)) { E[0] = (uint8_t)(temp); E[1] = (uint8_t)(temp>>8); E[2] = (uint8_t)(temp>>16); E[3] = (uint8_t)(temp>>24); } if (isSecret) { /* Check for D in the key file followed by '=' Once got, parse the value of D */ do { name = getc(f); } while (name >= 0 && isspace(name)); if(name != 'D') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected D, got %c",name); return 1; } do { name = getc(f); } while (name >= 0 && isspace(name)); if (name != '=') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected =, got %c",name); return 1; } LOG_TRACE("Parsing 'D' from key file"); Hex2Byte(f, D, keySize); /* The rest of parsing is for sanity checking purpose Not used for signing or verfication */ /* Check for P in the key file followed by '=' Once got, parse the value of P */ do { name = getc(f); } while (name >= 0 && isspace(name)); if(name == 'P') { do { name = getc(f); } while (name >= 0 && isspace(name)); if (name != '=') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected =, got %c",name); return 1; } LOG_TRACE("Parsing 'P' from key file"); Hex2Byte(f, P, keySize/2); /* Check for Q in the key file followed by '=' Once got, parse the value of Q */ do { name = getc(f); } while (name >= 0 && isspace(name)); if(name != 'Q') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected Q, got %c",name); return 1; } do { name = getc(f); } while (name >= 0 && isspace(name)); if(name != '=') { LOG_DEBUG(DEBUG_STAMP, "Bad Key file, expected =, got %c",name); return 1; } LOG_TRACE("Parsing 'Q' from key file"); Hex2Byte(f, Q, keySize/2); /* Sanity check block, N = PxQ */ { uint8_t *Ncheck = new uint8_t [keySize]; Multiply_p_q(P, Q, Ncheck); if (memcmp(N, Ncheck, keySize)) { delete[] Ncheck; LOG_DEBUG(DEBUG_STAMP, "Inconsistency found in key file, P * Q != N"); return 1; } delete[] Ncheck; } } } else { /* If it is a public key, D=0 */ memset(D, 0, keySize); } return 0; } /******************************************************************************/ void Key::WriteRsaFile(std::ofstream& file, const RSA* rsa, bool secret, uint16_t keyLength) { uint8_t *temp = new uint8_t [keyLength]; file << "N = "; #if OPENSSL_VERSION_NUMBER > 0x10100000L memcpy(temp, RSA_get0_n(rsa)->d, keyLength); #else memcpy(temp, rsa->n->d, keyLength); #endif for (uint32_t index = keyLength; index != 0; index--) { file << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << int(temp[index-1]); } file << "\n\nE = "; #if OPENSSL_VERSION_NUMBER > 0x10100000L uint32_t* temp_e = (uint32_t*)RSA_get0_e(rsa)->d; #else uint32_t* temp_e = (uint32_t*)rsa->e->d; #endif file << std::uppercase << std::hex << std::setfill('0') << std::setw(8) << *temp_e; if (secret) { file << "\n\nD = "; #if OPENSSL_VERSION_NUMBER > 0x10100000L memcpy(temp, RSA_get0_d(rsa)->d, keyLength); #else memcpy(temp, rsa->d->d, keyLength); #endif for (uint32_t index = keyLength; index != 0; index--) { file << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << int(temp[index - 1]); } } delete[] temp; } /******************************************************************************/ void Key::GenerateRsaKeys(KeyGenerationStruct* keygen) { RSA *rsa = NULL; bool publicKeyGenerated = false; bool privateKeyGenerated = false; OpenSSL_add_all_algorithms(); FILE* file; if ((rsa = RSA_generate_key(keygen->keyLength*8, RSA_F4, NULL, NULL)) == NULL) { LOG_ERROR("Failure creating authentication Keys"); } else { if(keygen->format == GenAuthKeys::PEM) { if(keygen->ppk_file != "") { file = fopen(keygen->ppk_file.c_str(), "wb"); PEM_write_RSA_PUBKEY(file, rsa); fclose(file); LOG_INFO("PPK generation in PEM format successful"); publicKeyGenerated = true; } if(keygen->psk_file != "") { file = fopen(keygen->psk_file.c_str(), "wb"); PEM_write_RSAPrivateKey(file, rsa, NULL, NULL, 0, NULL, NULL); fclose(file); LOG_INFO("PSK generation in PEM format successful"); publicKeyGenerated = true; } } else { if(keygen->ppk_file != "") { std::ofstream file1(keygen->ppk_file.c_str()); WriteRsaFile(file1, rsa, false, keygen->keyLength); file1.close(); LOG_INFO("PPK generation in RSA format successful"); publicKeyGenerated = true; } if(keygen->psk_file != "") { std::ofstream file2(keygen->psk_file.c_str()); WriteRsaFile(file2, rsa, true, keygen->keyLength); file2.close(); LOG_INFO("PSK generation in RSA format successful"); publicKeyGenerated = true; } } } rsa=NULL; if ((rsa=RSA_generate_key(keygen->keyLength*8, RSA_F4, NULL, NULL)) == NULL) { LOG_ERROR("Failure creating authentication Keys"); } else { if(keygen->format == GenAuthKeys::PEM) { if(keygen->spk_file != "") { file = fopen(keygen->spk_file.c_str(), "wb"); PEM_write_RSA_PUBKEY(file, rsa); fclose(file); LOG_INFO("SPK generation in PEM format successful"); privateKeyGenerated = true; } if(keygen->ssk_file != "") { file = fopen(keygen->ssk_file.c_str(), "wb"); PEM_write_RSAPrivateKey(file, rsa, NULL, NULL, 0, NULL, NULL); fclose(file); LOG_INFO("SSK generation in PEM format successful"); privateKeyGenerated = true; } } else { if(keygen->spk_file != "") { std::ofstream file3(keygen->spk_file.c_str()); WriteRsaFile(file3, rsa, false, keygen->keyLength); file3.close(); LOG_INFO("SPK generation in RSA format successful"); privateKeyGenerated = true; } if(keygen->ssk_file != "") { std::ofstream file4(keygen->ssk_file.c_str()); WriteRsaFile(file4, rsa, true, keygen->keyLength); file4.close(); LOG_INFO("SSK generation in RSA format successful"); privateKeyGenerated = true; } } } if(!publicKeyGenerated && !privateKeyGenerated) { LOG_DEBUG(DEBUG_STAMP, "Key paths are not specified in the BIF file"); LOG_ERROR("Failed to generate authentication keys. Please specify the key paths in BIF file"); } } /******************************************************************************/ void Key2048::Export(void* acKey) { ACKey2048* key = (ACKey2048*)acKey; if (!Loaded) { std::string pubsec = (isSecret) ? " (Secret)" : " (Public)"; LOG_ERROR("%s - $s is not loaded", name.c_str(), pubsec.c_str()); } memset(key,0,sizeof(ACKey2048)); memcpy(key->N, N, 256); memcpy(key->N_extension, N_ext, 256); memcpy(key->E, E, 4); } /******************************************************************************/ void Key2048::Import(const void* acKey, const std::string& name0) { ACKey2048* key = (ACKey2048*)acKey; Loaded = true; isSecret = false; name = name0; memcpy(N,key->N,keySize); memcpy(N_ext,key->N_extension,keySize); memcpy(E,key->E,sizeof(uint32_t)); memset(P,0,keySize/2); memset(Q,0,keySize/2); /* Fill secret exponent with zeros */ memset(D,0,keySize); } /******************************************************************************/ void Key4096::Export(void* acKey) { ACKey4096* key = (ACKey4096*)acKey; if (!Loaded) { std::string pubsec = (isSecret) ? " (Secret)" : " (Public)"; LOG_ERROR("%s - $s is not loaded", name.c_str(), pubsec.c_str()); } memset(key, 0, sizeof(ACKey4096)); memcpy(key->N, N, keySize); memcpy(key->N_extension, N_ext, keySize); memcpy(key->E, E, 4); } /******************************************************************************/ void Key4096::Import(const void* acKey, const std::string& name0) { ACKey4096* key = (ACKey4096*)acKey; Loaded = true; isSecret = false; name = name0; memcpy(N, key->N, keySize); memcpy(N_ext, key->N_extension, keySize); memcpy(E, key->E, sizeof(uint32_t)); memset(P, 0, keySize/2); memset(Q, 0, keySize/2); /* Fill secret exponent with zeros */ memset(D, 0, keySize); } /******************************************************************************/ void Key::SetKeyName(std::string keyname) { name = keyname; } /******************************************************************************/ void Key::Multiply_p_q(uint8_t p[], uint8_t q[], uint8_t n[]) { memset(n,0,256); /* Multiply p * q, and store in n */ for(int i = 0; i < 128; i++) { for(int j = 0; j < 128; j++) { uint16_t prod = p[i] * q[j]; int k = i+j; while (prod && k < 256) { uint16_t sum = n[k] + (prod & 0xFF); n[k] = sum & 0xFF; prod >>= 8; sum >>= 8; prod = (prod + sum); k++; } } } } /******************************************************************************/ void Key::Hex2Byte(FILE* f, uint8_t* data, int count) { char *buf; buf = (char *) malloc(2000); if (buf != NULL) { char *tempbuf = buf; if (fscanf(f, "%s", tempbuf) != 1) { LOG_ERROR("Error parsing key"); } int len = strlen(tempbuf)/2; if(len != count) { LOG_ERROR("Key size is %d bytes, expected size is %d bytes", len, count); } for(int i = count-1; i >= 0; i--) { int v; if (sscanf(tempbuf, "%2X", &v) != 1) { LOG_DEBUG(DEBUG_STAMP, "Failure reading the authentication key file"); LOG_ERROR("Failure in key parsing !!!"); } if (v < 0 || v > 255) { LOG_DEBUG(DEBUG_STAMP, "Failure converting the hex characters from key file"); LOG_ERROR("Failure in key parsing !!!"); } if(i > 0) { tempbuf += 2; } data[i] = v; } } else { LOG_DEBUG(DEBUG_STAMP, "Memory Allocation error while reading keys"); LOG_ERROR("Failure in key parsing !!!"); } free(buf); }
19,921
6,630
/** * @file lldrawpoolterrain.cpp * @brief LLDrawPoolTerrain class implementation * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "lldrawpoolterrain.h" #include "llfasttimer.h" #include "llagent.h" #include "llviewercontrol.h" #include "lldrawable.h" #include "llface.h" #include "llsky.h" #include "llsurface.h" #include "llsurfacepatch.h" #include "llviewerregion.h" #include "llvlcomposition.h" #include "llviewerparcelmgr.h" // for gRenderParcelOwnership #include "llviewerparceloverlay.h" #include "llvosurfacepatch.h" #include "llviewercamera.h" #include "llviewertexturelist.h" // To get alpha gradients #include "llworld.h" #include "pipeline.h" #include "llviewershadermgr.h" #include "llrender.h" #include "llenvironment.h" #include "llsettingsvo.h" const F32 DETAIL_SCALE = 1.f/16.f; int DebugDetailMap = 0; S32 LLDrawPoolTerrain::sDetailMode = 1; F32 LLDrawPoolTerrain::sDetailScale = DETAIL_SCALE; static LLGLSLShader* sShader = NULL; static LLTrace::BlockTimerStatHandle FTM_SHADOW_TERRAIN("Terrain Shadow"); LLDrawPoolTerrain::LLDrawPoolTerrain(LLViewerTexture *texturep) : LLFacePool(POOL_TERRAIN), mTexturep(texturep) { // Hack! // <FS:PP> Attempt to speed up things a little // sDetailScale = 1.f/gSavedSettings.getF32("RenderTerrainScale"); // sDetailMode = gSavedSettings.getS32("RenderTerrainDetail"); static LLCachedControl<F32> RenderTerrainScale(gSavedSettings, "RenderTerrainScale"); static LLCachedControl<S32> RenderTerrainDetail(gSavedSettings, "RenderTerrainDetail"); sDetailScale = 1.f/RenderTerrainScale; sDetailMode = RenderTerrainDetail(); // </FS:PP> mAlphaRampImagep = LLViewerTextureManager::getFetchedTexture(IMG_ALPHA_GRAD); //gGL.getTexUnit(0)->bind(mAlphaRampImagep.get()); mAlphaRampImagep->setAddressMode(LLTexUnit::TAM_CLAMP); m2DAlphaRampImagep = LLViewerTextureManager::getFetchedTexture(IMG_ALPHA_GRAD_2D); //gGL.getTexUnit(0)->bind(m2DAlphaRampImagep.get()); m2DAlphaRampImagep->setAddressMode(LLTexUnit::TAM_CLAMP); mTexturep->setBoostLevel(LLGLTexture::BOOST_TERRAIN); //gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); } LLDrawPoolTerrain::~LLDrawPoolTerrain() { llassert( gPipeline.findPool( getType(), getTexture() ) == NULL ); } U32 LLDrawPoolTerrain::getVertexDataMask() { if (LLPipeline::sShadowRender) { return LLVertexBuffer::MAP_VERTEX; } else if (LLGLSLShader::sCurBoundShaderPtr) { return VERTEX_DATA_MASK & ~(LLVertexBuffer::MAP_TEXCOORD2 | LLVertexBuffer::MAP_TEXCOORD3); } else { return VERTEX_DATA_MASK; } } void LLDrawPoolTerrain::prerender() { mShaderLevel = LLViewerShaderMgr::instance()->getShaderLevel(LLViewerShaderMgr::SHADER_ENVIRONMENT); // <FS:Ansariel> Use faster LLCachedControls for frequently visited locations //sDetailMode = gSavedSettings.getS32("RenderTerrainDetail"); static LLCachedControl<S32> renderTerrainDetail(gSavedSettings, "RenderTerrainDetail"); sDetailMode = renderTerrainDetail(); // </FS:Ansariel> } void LLDrawPoolTerrain::beginRenderPass( S32 pass ) { LL_RECORD_BLOCK_TIME(FTM_RENDER_TERRAIN); LLFacePool::beginRenderPass(pass); sShader = LLPipeline::sUnderWaterRender ? &gTerrainWaterProgram : &gTerrainProgram; if (mShaderLevel > 1 && sShader->mShaderLevel > 0) { sShader->bind(); } } void LLDrawPoolTerrain::endRenderPass( S32 pass ) { LL_RECORD_BLOCK_TIME(FTM_RENDER_TERRAIN); //LLFacePool::endRenderPass(pass); if (mShaderLevel > 1 && sShader->mShaderLevel > 0) { sShader->unbind(); } } //static S32 LLDrawPoolTerrain::getDetailMode() { return sDetailMode; } void LLDrawPoolTerrain::boostTerrainDetailTextures() { // Hack! Get the region that this draw pool is rendering from! LLViewerRegion *regionp = mDrawFace[0]->getDrawable()->getVObj()->getRegion(); LLVLComposition *compp = regionp->getComposition(); for (S32 i = 0; i < 4; i++) { compp->mDetailTextures[i]->setBoostLevel(LLGLTexture::BOOST_TERRAIN); compp->mDetailTextures[i]->addTextureStats(1024.f*1024.f); // assume large pixel area } } void LLDrawPoolTerrain::render(S32 pass) { LL_RECORD_BLOCK_TIME(FTM_RENDER_TERRAIN); if (mDrawFace.empty()) { return; } boostTerrainDetailTextures(); LLOverrideFaceColor override(this, 1.f, 1.f, 1.f, 1.f); if (!gGLManager.mHasMultitexture) { // No multitexture, render simple land. renderSimple(); // Render without multitexture return; } // Render simplified land if video card can't do sufficient multitexturing if (!gGLManager.mHasARBEnvCombine || (gGLManager.mNumTextureUnits < 2)) { renderSimple(); // Render without multitexture return; } LLGLSPipeline gls; if (mShaderLevel > 1 && sShader->mShaderLevel > 0) { gPipeline.enableLightsDynamic(); renderFullShader(); } else { gPipeline.enableLightsStatic(); if (sDetailMode == 0) { renderSimple(); } else if (gGLManager.mNumTextureUnits < 4) { renderFull2TU(); } else { renderFull4TU(); } } // Special-case for land ownership feedback // <FS:Ansariel> Use faster LLCachedControls for frequently visited locations //if (gSavedSettings.getBOOL("ShowParcelOwners")) static LLCachedControl<bool> showParcelOwners(gSavedSettings, "ShowParcelOwners"); if (showParcelOwners) // </FS:Ansariel> { hilightParcelOwners(false); } } void LLDrawPoolTerrain::beginDeferredPass(S32 pass) { LL_RECORD_BLOCK_TIME(FTM_RENDER_TERRAIN); LLFacePool::beginRenderPass(pass); sShader = LLPipeline::sUnderWaterRender ? &gDeferredTerrainWaterProgram : &gDeferredTerrainProgram; sShader->bind(); } void LLDrawPoolTerrain::endDeferredPass(S32 pass) { LL_RECORD_BLOCK_TIME(FTM_RENDER_TERRAIN); LLFacePool::endRenderPass(pass); sShader->unbind(); } void LLDrawPoolTerrain::renderDeferred(S32 pass) { LL_RECORD_BLOCK_TIME(FTM_RENDER_TERRAIN); if (mDrawFace.empty()) { return; } boostTerrainDetailTextures(); renderFullShader(); // Special-case for land ownership feedback // <FS:Ansariel> Use faster LLCachedControls for frequently visited locations //if (gSavedSettings.getBOOL("ShowParcelOwners")) static LLCachedControl<bool> showParcelOwners(gSavedSettings, "ShowParcelOwners"); if (showParcelOwners) // </FS:Ansariel> { hilightParcelOwners(true); } } void LLDrawPoolTerrain::beginShadowPass(S32 pass) { LL_RECORD_BLOCK_TIME(FTM_SHADOW_TERRAIN); LLFacePool::beginRenderPass(pass); gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); gDeferredShadowProgram.bind(); LLEnvironment& environment = LLEnvironment::instance(); gDeferredShadowProgram.uniform1i(LLShaderMgr::SUN_UP_FACTOR, environment.getIsSunUp() ? 1 : 0); } void LLDrawPoolTerrain::endShadowPass(S32 pass) { LL_RECORD_BLOCK_TIME(FTM_SHADOW_TERRAIN); LLFacePool::endRenderPass(pass); gDeferredShadowProgram.unbind(); } void LLDrawPoolTerrain::renderShadow(S32 pass) { LL_RECORD_BLOCK_TIME(FTM_SHADOW_TERRAIN); if (mDrawFace.empty()) { return; } //LLGLEnable offset(GL_POLYGON_OFFSET); //glCullFace(GL_FRONT); drawLoop(); //glCullFace(GL_BACK); } void LLDrawPoolTerrain::drawLoop() { if (!mDrawFace.empty()) { for (std::vector<LLFace*>::iterator iter = mDrawFace.begin(); iter != mDrawFace.end(); iter++) { LLFace *facep = *iter; LLMatrix4* model_matrix = &(facep->getDrawable()->getRegion()->mRenderMatrix); if (model_matrix != gGLLastMatrix) { llassert(gGL.getMatrixMode() == LLRender::MM_MODELVIEW); gGLLastMatrix = model_matrix; gGL.loadMatrix(gGLModelView); if (model_matrix) { gGL.multMatrix((GLfloat*) model_matrix->mMatrix); } gPipeline.mMatrixOpCount++; } facep->renderIndexed(); } } } void LLDrawPoolTerrain::renderFullShader() { // Hack! Get the region that this draw pool is rendering from! LLViewerRegion *regionp = mDrawFace[0]->getDrawable()->getVObj()->getRegion(); LLVLComposition *compp = regionp->getComposition(); // [SL:KB] - Patch: Render-TextureToggle (Catznip-4.0) LLViewerTexture *detail_texture0p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[0] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture1p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[1] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture2p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[2] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture3p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[3] : LLViewerFetchedTexture::sDefaultDiffuseImagep; // [/SL:KB] // LLViewerTexture *detail_texture0p = compp->mDetailTextures[0]; // LLViewerTexture *detail_texture1p = compp->mDetailTextures[1]; // LLViewerTexture *detail_texture2p = compp->mDetailTextures[2]; // LLViewerTexture *detail_texture3p = compp->mDetailTextures[3]; LLVector3d region_origin_global = gAgent.getRegion()->getOriginGlobal(); F32 offset_x = (F32)fmod(region_origin_global.mdV[VX], 1.0/(F64)sDetailScale)*sDetailScale; F32 offset_y = (F32)fmod(region_origin_global.mdV[VY], 1.0/(F64)sDetailScale)*sDetailScale; LLVector4 tp0, tp1; tp0.setVec(sDetailScale, 0.0f, 0.0f, offset_x); tp1.setVec(0.0f, sDetailScale, 0.0f, offset_y); // // detail texture 0 // S32 detail0 = sShader->enableTexture(LLViewerShaderMgr::TERRAIN_DETAIL0); gGL.getTexUnit(detail0)->bind(detail_texture0p); gGL.getTexUnit(detail0)->setTextureAddressMode(LLTexUnit::TAM_WRAP); gGL.getTexUnit(detail0)->activate(); LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr; llassert(shader); shader->uniform4fv(LLShaderMgr::OBJECT_PLANE_S, 1, tp0.mV); shader->uniform4fv(LLShaderMgr::OBJECT_PLANE_T, 1, tp1.mV); LLSettingsWater::ptr_t pwater = LLEnvironment::instance().getCurrentWater(); ((LLSettingsVOWater*)pwater.get())->updateShader(shader); // // detail texture 1 // S32 detail1 = sShader->enableTexture(LLViewerShaderMgr::TERRAIN_DETAIL1); gGL.getTexUnit(detail1)->bind(detail_texture1p); gGL.getTexUnit(detail1)->setTextureAddressMode(LLTexUnit::TAM_WRAP); gGL.getTexUnit(detail1)->activate(); // detail texture 2 // S32 detail2 = sShader->enableTexture(LLViewerShaderMgr::TERRAIN_DETAIL2); gGL.getTexUnit(detail2)->bind(detail_texture2p); gGL.getTexUnit(detail2)->setTextureAddressMode(LLTexUnit::TAM_WRAP); gGL.getTexUnit(detail2)->activate(); // detail texture 3 // S32 detail3 = sShader->enableTexture(LLViewerShaderMgr::TERRAIN_DETAIL3); gGL.getTexUnit(detail3)->bind(detail_texture3p); gGL.getTexUnit(detail3)->setTextureAddressMode(LLTexUnit::TAM_WRAP); gGL.getTexUnit(detail3)->activate(); // // Alpha Ramp // S32 alpha_ramp = sShader->enableTexture(LLViewerShaderMgr::TERRAIN_ALPHARAMP); gGL.getTexUnit(alpha_ramp)->bind(m2DAlphaRampImagep); gGL.getTexUnit(alpha_ramp)->setTextureAddressMode(LLTexUnit::TAM_CLAMP); // GL_BLEND disabled by default drawLoop(); // Disable multitexture sShader->disableTexture(LLViewerShaderMgr::TERRAIN_ALPHARAMP); sShader->disableTexture(LLViewerShaderMgr::TERRAIN_DETAIL0); sShader->disableTexture(LLViewerShaderMgr::TERRAIN_DETAIL1); sShader->disableTexture(LLViewerShaderMgr::TERRAIN_DETAIL2); sShader->disableTexture(LLViewerShaderMgr::TERRAIN_DETAIL3); gGL.getTexUnit(alpha_ramp)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(alpha_ramp)->disable(); gGL.getTexUnit(alpha_ramp)->activate(); gGL.getTexUnit(detail3)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(detail3)->disable(); gGL.getTexUnit(detail3)->activate(); gGL.getTexUnit(detail2)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(detail2)->disable(); gGL.getTexUnit(detail2)->activate(); gGL.getTexUnit(detail1)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(detail1)->disable(); gGL.getTexUnit(detail1)->activate(); //---------------------------------------------------------------------------- // Restore Texture Unit 0 defaults gGL.getTexUnit(detail0)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(detail0)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(detail0)->activate(); } void LLDrawPoolTerrain::hilightParcelOwners(bool deferred) { if (mShaderLevel > 1) { //use fullbright shader for highlighting LLGLSLShader* old_shader = sShader; sShader->unbind(); sShader = deferred ? &gDeferredHighlightProgram : &gHighlightProgram; sShader->bind(); gGL.diffuseColor4f(1, 1, 1, 1); LLGLEnable polyOffset(GL_POLYGON_OFFSET_FILL); glPolygonOffset(-1.0f, -1.0f); renderOwnership(); sShader = old_shader; sShader->bind(); } else { gPipeline.disableLights(); renderOwnership(); } } void LLDrawPoolTerrain::renderFull4TU() { // Hack! Get the region that this draw pool is rendering from! LLViewerRegion *regionp = mDrawFace[0]->getDrawable()->getVObj()->getRegion(); LLVLComposition *compp = regionp->getComposition(); // [SL:KB] - Patch: Render-TextureToggle (Catznip-4.0) LLViewerTexture *detail_texture0p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[0] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture1p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[1] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture2p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[2] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture3p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[3] : LLViewerFetchedTexture::sDefaultDiffuseImagep; // [/SL:KB] // LLViewerTexture *detail_texture0p = compp->mDetailTextures[0]; // LLViewerTexture *detail_texture1p = compp->mDetailTextures[1]; // LLViewerTexture *detail_texture2p = compp->mDetailTextures[2]; // LLViewerTexture *detail_texture3p = compp->mDetailTextures[3]; LLVector3d region_origin_global = gAgent.getRegion()->getOriginGlobal(); F32 offset_x = (F32)fmod(region_origin_global.mdV[VX], 1.0/(F64)sDetailScale)*sDetailScale; F32 offset_y = (F32)fmod(region_origin_global.mdV[VY], 1.0/(F64)sDetailScale)*sDetailScale; LLVector4 tp0, tp1; tp0.setVec(sDetailScale, 0.0f, 0.0f, offset_x); tp1.setVec(0.0f, sDetailScale, 0.0f, offset_y); gGL.blendFunc(LLRender::BF_ONE_MINUS_SOURCE_ALPHA, LLRender::BF_SOURCE_ALPHA); //---------------------------------------------------------------------------- // Pass 1/1 // // Stage 0: detail texture 0 // gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->bind(detail_texture0p); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_COLOR); // // Stage 1: Generate alpha ramp for detail0/detail1 transition // gGL.getTexUnit(1)->bind(m2DAlphaRampImagep.get()); gGL.getTexUnit(1)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->activate(); // Care about alpha only gGL.getTexUnit(1)->setTextureColorBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_COLOR); gGL.getTexUnit(1)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_ALPHA); // // Stage 2: Interpolate detail1 with existing based on ramp // gGL.getTexUnit(2)->bind(detail_texture1p); gGL.getTexUnit(2)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(2)->activate(); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(2)->setTextureColorBlend(LLTexUnit::TBO_LERP_PREV_ALPHA, LLTexUnit::TBS_PREV_COLOR, LLTexUnit::TBS_TEX_COLOR); // // Stage 3: Modulate with primary (vertex) color for lighting // gGL.getTexUnit(3)->bind(detail_texture1p); gGL.getTexUnit(3)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(3)->activate(); // Set alpha texture and do lighting modulation gGL.getTexUnit(3)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_PREV_COLOR, LLTexUnit::TBS_VERT_COLOR); gGL.getTexUnit(0)->activate(); // GL_BLEND disabled by default drawLoop(); //---------------------------------------------------------------------------- // Second pass // Stage 0: Write detail3 into base // gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->bind(detail_texture3p); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_COLOR); // // Stage 1: Generate alpha ramp for detail2/detail3 transition // gGL.getTexUnit(1)->bind(m2DAlphaRampImagep); gGL.getTexUnit(1)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->activate(); // Set the texture matrix gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.translatef(-2.f, 0.f, 0.f); // Care about alpha only gGL.getTexUnit(1)->setTextureColorBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_COLOR); gGL.getTexUnit(1)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_ALPHA); // // Stage 2: Interpolate detail2 with existing based on ramp // gGL.getTexUnit(2)->bind(detail_texture2p); gGL.getTexUnit(2)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(2)->activate(); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(2)->setTextureColorBlend(LLTexUnit::TBO_LERP_PREV_ALPHA, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_PREV_COLOR); // // Stage 3: Generate alpha ramp for detail1/detail2 transition // gGL.getTexUnit(3)->bind(m2DAlphaRampImagep); gGL.getTexUnit(3)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(3)->activate(); // Set the texture matrix gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.translatef(-1.f, 0.f, 0.f); gGL.matrixMode(LLRender::MM_MODELVIEW); // Set alpha texture and do lighting modulation gGL.getTexUnit(3)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_PREV_COLOR, LLTexUnit::TBS_VERT_COLOR); gGL.getTexUnit(3)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_ALPHA); gGL.getTexUnit(0)->activate(); { LLGLEnable blend(GL_BLEND); drawLoop(); } LLVertexBuffer::unbind(); // Disable multitexture gGL.getTexUnit(3)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(3)->disable(); gGL.getTexUnit(3)->activate(); gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.matrixMode(LLRender::MM_MODELVIEW); gGL.getTexUnit(2)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(2)->disable(); gGL.getTexUnit(2)->activate(); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.matrixMode(LLRender::MM_MODELVIEW); gGL.getTexUnit(1)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->disable(); gGL.getTexUnit(1)->activate(); gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.matrixMode(LLRender::MM_MODELVIEW); // Restore blend state gGL.setSceneBlendType(LLRender::BT_ALPHA); //---------------------------------------------------------------------------- // Restore Texture Unit 0 defaults gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.matrixMode(LLRender::MM_MODELVIEW); gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT); } void LLDrawPoolTerrain::renderFull2TU() { // Hack! Get the region that this draw pool is rendering from! LLViewerRegion *regionp = mDrawFace[0]->getDrawable()->getVObj()->getRegion(); LLVLComposition *compp = regionp->getComposition(); // [SL:KB] - Patch: Render-TextureToggle (Catznip-4.0) LLViewerTexture *detail_texture0p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[0] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture1p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[1] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture2p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[2] : LLViewerFetchedTexture::sDefaultDiffuseImagep; LLViewerTexture *detail_texture3p = (LLPipeline::sRenderTextures) ? compp->mDetailTextures[3] : LLViewerFetchedTexture::sDefaultDiffuseImagep; // [/SL:KB] // LLViewerTexture *detail_texture0p = compp->mDetailTextures[0]; // LLViewerTexture *detail_texture1p = compp->mDetailTextures[1]; // LLViewerTexture *detail_texture2p = compp->mDetailTextures[2]; // LLViewerTexture *detail_texture3p = compp->mDetailTextures[3]; LLVector3d region_origin_global = gAgent.getRegion()->getOriginGlobal(); F32 offset_x = (F32)fmod(region_origin_global.mdV[VX], 1.0/(F64)sDetailScale)*sDetailScale; F32 offset_y = (F32)fmod(region_origin_global.mdV[VY], 1.0/(F64)sDetailScale)*sDetailScale; LLVector4 tp0, tp1; tp0.setVec(sDetailScale, 0.0f, 0.0f, offset_x); tp1.setVec(0.0f, sDetailScale, 0.0f, offset_y); gGL.blendFunc(LLRender::BF_ONE_MINUS_SOURCE_ALPHA, LLRender::BF_SOURCE_ALPHA); //---------------------------------------------------------------------------- // Pass 1/4 // // Stage 0: Render detail 0 into base // gGL.getTexUnit(0)->bind(detail_texture0p); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_VERT_COLOR); drawLoop(); //---------------------------------------------------------------------------- // Pass 2/4 // // Stage 0: Generate alpha ramp for detail0/detail1 transition // gGL.getTexUnit(0)->bind(m2DAlphaRampImagep); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); // Care about alpha only gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_COLOR); gGL.getTexUnit(0)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_ALPHA); // // Stage 1: Write detail1 // gGL.getTexUnit(1)->bind(detail_texture1p); gGL.getTexUnit(1)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->activate(); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(1)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_VERT_COLOR); gGL.getTexUnit(1)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_ALPHA); gGL.getTexUnit(0)->activate(); { LLGLEnable blend(GL_BLEND); drawLoop(); } //---------------------------------------------------------------------------- // Pass 3/4 // // Stage 0: Generate alpha ramp for detail1/detail2 transition // gGL.getTexUnit(0)->bind(m2DAlphaRampImagep); // Set the texture matrix gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.translatef(-1.f, 0.f, 0.f); gGL.matrixMode(LLRender::MM_MODELVIEW); // Care about alpha only gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_COLOR); gGL.getTexUnit(0)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_ALPHA); // // Stage 1: Write detail2 // gGL.getTexUnit(1)->bind(detail_texture2p); gGL.getTexUnit(1)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->activate(); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(1)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_VERT_COLOR); gGL.getTexUnit(1)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_ALPHA); { LLGLEnable blend(GL_BLEND); drawLoop(); } //---------------------------------------------------------------------------- // Pass 4/4 // // Stage 0: Generate alpha ramp for detail2/detail3 transition // gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->bind(m2DAlphaRampImagep); // Set the texture matrix gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.translatef(-2.f, 0.f, 0.f); gGL.matrixMode(LLRender::MM_MODELVIEW); // Care about alpha only gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_COLOR); gGL.getTexUnit(0)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_TEX_ALPHA); // Stage 1: Write detail3 gGL.getTexUnit(1)->bind(detail_texture3p); gGL.getTexUnit(1)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->activate(); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); gGL.getTexUnit(1)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_VERT_COLOR); gGL.getTexUnit(1)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_ALPHA); gGL.getTexUnit(0)->activate(); { LLGLEnable blend(GL_BLEND); drawLoop(); } // Restore blend state gGL.setSceneBlendType(LLRender::BT_ALPHA); // Disable multitexture gGL.getTexUnit(1)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->disable(); gGL.getTexUnit(1)->activate(); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.matrixMode(LLRender::MM_MODELVIEW); //---------------------------------------------------------------------------- // Restore Texture Unit 0 defaults gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.matrixMode(LLRender::MM_MODELVIEW); gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT); } void LLDrawPoolTerrain::renderSimple() { LLVector4 tp0, tp1; //---------------------------------------------------------------------------- // Pass 1/1 // Stage 0: Base terrain texture pass mTexturep->addTextureStats(1024.f*1024.f); gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(0)->bind(mTexturep); LLVector3 origin_agent = mDrawFace[0]->getDrawable()->getVObj()->getRegion()->getOriginAgent(); F32 tscale = 1.f/256.f; tp0.setVec(tscale, 0.f, 0.0f, -1.f*(origin_agent.mV[0]/256.f)); tp1.setVec(0.f, tscale, 0.0f, -1.f*(origin_agent.mV[1]/256.f)); if (LLGLSLShader::sNoFixedFunction) { sShader->uniform4fv(LLShaderMgr::OBJECT_PLANE_S, 1, tp0.mV); sShader->uniform4fv(LLShaderMgr::OBJECT_PLANE_T, 1, tp1.mV); } else { glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0.mV); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1.mV); } gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_VERT_COLOR); drawLoop(); //---------------------------------------------------------------------------- // Restore Texture Unit 0 defaults gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); if (!LLGLSLShader::sNoFixedFunction) { glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); } gGL.matrixMode(LLRender::MM_TEXTURE); gGL.loadIdentity(); gGL.matrixMode(LLRender::MM_MODELVIEW); gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT); } //============================================================================ void LLDrawPoolTerrain::renderOwnership() { LLGLSPipelineAlpha gls_pipeline_alpha; llassert(!mDrawFace.empty()); // Each terrain pool is associated with a single region. // We need to peek back into the viewer's data to find out // which ownership overlay texture to use. LLFace *facep = mDrawFace[0]; LLDrawable *drawablep = facep->getDrawable(); const LLViewerObject *objectp = drawablep->getVObj(); const LLVOSurfacePatch *vo_surface_patchp = (LLVOSurfacePatch *)objectp; LLSurfacePatch *surface_patchp = vo_surface_patchp->getPatch(); LLSurface *surfacep = surface_patchp->getSurface(); LLViewerRegion *regionp = surfacep->getRegion(); LLViewerParcelOverlay *overlayp = regionp->getParcelOverlay(); LLViewerTexture *texturep = overlayp->getTexture(); gGL.getTexUnit(0)->bind(texturep); // *NOTE: Because the region is 256 meters wide, but has 257 pixels, the // texture coordinates for pixel 256x256 is not 1,1. This makes the // ownership map not line up with the selection. We address this with // a texture matrix multiply. gGL.matrixMode(LLRender::MM_TEXTURE); gGL.pushMatrix(); const F32 TEXTURE_FUDGE = 257.f / 256.f; gGL.scalef( TEXTURE_FUDGE, TEXTURE_FUDGE, 1.f ); for (std::vector<LLFace*>::iterator iter = mDrawFace.begin(); iter != mDrawFace.end(); iter++) { LLFace *facep = *iter; facep->renderIndexed(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_TEXCOORD0); } gGL.matrixMode(LLRender::MM_TEXTURE); gGL.popMatrix(); gGL.matrixMode(LLRender::MM_MODELVIEW); } void LLDrawPoolTerrain::dirtyTextures(const std::set<LLViewerFetchedTexture*>& textures) { LLViewerFetchedTexture* tex = LLViewerTextureManager::staticCastToFetchedTexture(mTexturep) ; if (tex && textures.find(tex) != textures.end()) { for (std::vector<LLFace*>::iterator iter = mReferences.begin(); iter != mReferences.end(); iter++) { LLFace *facep = *iter; gPipeline.markTextured(facep->getDrawable()); } } } LLViewerTexture *LLDrawPoolTerrain::getTexture() { return mTexturep; } LLViewerTexture *LLDrawPoolTerrain::getDebugTexture() { return mTexturep; } LLColor3 LLDrawPoolTerrain::getDebugColor() const { return LLColor3(0.f, 0.f, 1.f); }
31,543
13,263
/*************************************************************************** * Software License Agreement (BSD License) * * Copyright (C) 2012 by Markus Bader <markus.bader@tuwien.ac.at> * * * * 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 name of the copyright holder 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. * ***************************************************************************/ #include <iostream> #include <stdlib.h> #include <signal.h> #include "shmfw/variable.h" #include "shmfw/vector.h" #include "shmfw/log.h" #include <boost/program_options.hpp> #include <boost/thread.hpp> #include <ncurses.h> bool loop_program = true; struct Prarmeters { bool clear; std::string shm_memory_name; unsigned int shm_memory_size; std::string variable_name; std::string log_file; int process_cout_level; int source; int file_level; int cout_level; bool timeout_msg; bool pull; bool buffer; bool timestamp; int timeout; }; Prarmeters readArgs ( int argc, char **argv ) { namespace po = boost::program_options; Prarmeters params; po::options_description desc ( "Allowed Parameters" ); desc.add_options() ( "help", "get this help message" ) ( "clear", "clears the shared memory" ) ( "msg_off,o", "switches the timeout message off" ) ( "buffer", "shows the buffer id" ) ( "timestamp_off", "switches the timestamp off" ) ( "pull,p", "pulls for log messages (no trigger needed)" ) ( "timeout,t", po::value<int> ( &params.timeout )->default_value ( 2000 ), "timeout for timeout message in ms" ) ( "source,s", po::value<int> ( &params.source )->default_value ( -1 ), "source filter (-1 off)" ) ( "process_cout_level", po::value<int> ( &params.process_cout_level )->default_value ( ShmFw::Message::NA ), "level of message to be printed by the meassage creating process" ) ( "cout_level", po::value<int> ( &params.cout_level )->default_value ( ShmFw::Message::NA ), "level of message to be printed by this process" ) ( "file_level", po::value<int> ( &params.file_level )->default_value ( ShmFw::Message::NA ), "level of message to be stored" ) ( "file,f", po::value<std::string> ( &params.log_file )->default_value ( "/tmp/log" ), "log file prefix, if empty it will print of cout" ) ( "shm_log,l", po::value<std::string> ( &params.variable_name )->default_value ( "log" ), "shared variable name of the logger" ) ( "shm_memory_name", po::value<std::string> ( &params.shm_memory_name )->default_value ( ShmFw::DEFAULT_LOG_SEGMENT_NAME() ), "shared memory segment name" ) ( "shm_memory_size", po::value<unsigned int> ( &params.shm_memory_size )->default_value ( ShmFw::DEFAULT_LOG_SEGMENT_SIZE() ), "shared memory segment size" ); po::variables_map vm; try { po::store ( po::parse_command_line ( argc, argv, desc ), vm ); } catch ( const std::exception &ex ) { std::cout << desc << std::endl;; exit ( 1 ); } po::notify ( vm ); if ( vm.count ( "help" ) ) { std::cout << desc << std::endl; exit ( 1 ); } params.clear = ( vm.count ( "clear" ) > 0 ); params.timeout_msg = ! ( vm.count ( "msg_off" ) > 0 ); params.pull = ( vm.count ( "pull" ) > 0 ); params.buffer = ( vm.count ( "buffer" ) > 0 ); params.timestamp = !( vm.count ( "timestamp_off" ) > 0 ); return params; } void printMsgs ( std::vector<ShmFw::Message> &msgs, std::ofstream &file, const Prarmeters &params ) { for ( unsigned int i = 0; i < msgs.size(); i++ ) { ShmFw::Message &msg = msgs[i]; if ( !params.log_file.empty() ) { file << std::setw ( 4 ) << i << ": " << msg << std::endl; } //source log level/type filter if ( msg.getType() >= params.cout_level ) { if ( params.buffer ) std::cout << std::setw ( 4 ) << i << ": "; if ( params.timestamp ) std::cout << boost::posix_time::to_simple_string ( msg.getTime() ).substr(12,26) << ": "; if ( msg.getType() != ShmFw::Message::NA ) std::cout << ": " << std::setw ( 8 ) << msg.typeStr() << ": "; std::cout << msg.getMsg(); std::cout << std::endl; } } } void dequeLog ( ShmFw::Log &log, const Prarmeters &params ) { std::vector<ShmFw::Message> msgs; std::ofstream file; boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); std::string datedFileName = params.log_file + std::string ( "_" ) + boost::posix_time::to_iso_string ( now ) + std::string ( ".txt" ); if ( !params.log_file.empty() ) { file.open ( datedFileName.c_str(), std::ios::out | std::ios::binary ); } while ( loop_program ) { bool wait_ones = true; while ( ( log.timed_wait ( params.timeout ) == false ) && loop_program && wait_ones ) { if ( params.timeout_msg ) std::cout << "waited " << params.timeout << " ms" << std::endl; if ( params.pull ) wait_ones = false; } msgs.clear(); log.lock(); #if BOOST_VERSION / 100 % 1000 <= 55 for ( ShmFw::Log::Iterator it = log->begin(); it != log->end(); it++ ) { //source filter if ( (params.source < 0) || (params.source == ( *it ).getSource())) { msgs.push_back ( *it ); log.pop_front(); } } #else #endif log.unlock(); printMsgs ( msgs, file, params ); } if ( !params.log_file.empty() ) file.close(); } void terminate ( int param ) { std::cout << "Closing program!" << std::endl; loop_program = false; } int main ( int argc, char *argv[] ) { signal ( SIGINT, terminate ); signal ( SIGKILL, terminate ); Prarmeters params = readArgs ( argc, argv ); if ( params.clear ) { ShmFw::Handler::removeSegment ( params.shm_memory_name ); std::cout << "Shared Memory " << params.shm_memory_name << " cleared" << std::endl; exit ( 1 ); } ShmFw::HandlerPtr shmHdl = ShmFw::Handler::create ( params.shm_memory_name, params.shm_memory_size ); ShmFw::Log log ( shmHdl, params.variable_name ); log.process_cout_level ( params.process_cout_level ); log.unlock(); dequeLog ( log, params ); log.unlock(); exit ( 0 ); }
8,242
2,721
#include <glfw/include/glfw.h> #include <windowsystem.h> #include <webgl.h> #include "canvas/src/stb_image.h" #include <exout> #if defined(TARGET_OS_MAC) || defined(__linux__) #define MAIN_THREAD_POLLING 1 #endif namespace glfw { thread_local NATIVEwindow *currentWindow = nullptr; std::mutex windowHandleMutex; NATIVEwindow *sharedWindow = nullptr; InjectionHandler mainThreadInjectionHandler; std::mutex injectionHandlerMapMutex; int lastX = -1, lastY = -1; // XXX track this per-window uint64_t lastClickTime = 0; #ifdef MAIN_THREAD_POLLING std::thread::id mainThreadId; bool hasMainThreadId = false; #endif WindowState::WindowState() {} WindowState::~WindowState() {} void RunEventInWindowThread(uv_async_t *async) { Nan::HandleScope scope; EventHandler *eventHandler = (EventHandler *)async->data; std::deque<std::function<void(std::function<void(int argc, Local<Value> *argv)>)>> localFns; Local<Function> handlerFn; { std::lock_guard<std::mutex> lock(eventHandler->mutex); localFns = std::move(eventHandler->fns); eventHandler->fns.clear(); handlerFn = Nan::New(eventHandler->handlerFn); } for (auto iter = localFns.begin(); iter != localFns.end(); iter++) { Nan::HandleScope scope; (*iter)([&](int argc, Local<Value> *argv) -> void { Local<Object> asyncObject = Nan::New<Object>(); AsyncResource asyncResource(Isolate::GetCurrent(), asyncObject, "mlEvents"); asyncResource.MakeCallback(handlerFn, argc, argv); }); } } EventHandler::EventHandler(uv_loop_t *loop, Local<Function> handlerFn) : async(new uv_async_t()), handlerFn(handlerFn) { uv_async_init(loop, async.get(), RunEventInWindowThread); async->data = this; } EventHandler::~EventHandler() { uv_close((uv_handle_t *)async.release(), [](uv_handle_t *handle) { delete handle; }); } InjectionHandler::InjectionHandler() {} void QueueEvent(NATIVEwindow *window, std::function<void(std::function<void(int, Local<Value> *)>)> fn) { WindowState *windowState = (WindowState *)glfwGetWindowUserPointer(window); if (windowState->handler) { EventHandler *eventHandler = windowState->handler.get(); { std::lock_guard<std::mutex> lock(eventHandler->mutex); eventHandler->fns.push_back(fn); } uv_async_send(eventHandler->async.get()); } } bool glfwInitialized = false; void initializeGlfw() { glewExperimental = GL_TRUE; if (glfwInit() == GLFW_TRUE) { atexit([]() { glfwTerminate(); }); glfwDefaultWindowHints(); // we use OpenGL 2.1, GLSL 1.20. Comment this for now as this is for GLSL 1.50 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, 1); glfwWindowHint(GLFW_VISIBLE, 1); glfwWindowHint(GLFW_DECORATED, 1); glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_DEPTH_BITS, 24); glfwWindowHint(GLFW_REFRESH_RATE, 0); glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR, GLFW_RELEASE_BEHAVIOR_NONE); glfwSetErrorCallback([](int err, const char *errString) { fprintf(stderr, "GLFW error: %d: %s", err, errString); }); } else { exerr << "Failed to initialize GLFW" << std::endl; abort(); } } void handleInjections() { std::lock_guard<std::mutex> lock(injectionHandlerMapMutex); for (auto iter = mainThreadInjectionHandler.fns.begin(); iter != mainThreadInjectionHandler.fns.end(); iter++) { std::function<void(InjectionHandler *)> &fn = *iter; fn(&mainThreadInjectionHandler); } mainThreadInjectionHandler.fns.clear(); } void QueueInjection(std::function<void(InjectionHandler *injectionHandler)> fn) { if (!glfwInitialized) { #ifndef MAIN_THREAD_POLLING std::thread([&]() -> void { initializeGlfw(); for (;;) { glfwWaitEvents(); handleInjections(); } }).detach(); #else { std::lock_guard<std::mutex> lock(injectionHandlerMapMutex); mainThreadInjectionHandler.fns.push_back([](InjectionHandler *injectionHandler) -> void { initializeGlfw(); }); } #endif glfwInitialized = true; } { std::lock_guard<std::mutex> lock(injectionHandlerMapMutex); mainThreadInjectionHandler.fns.push_back(fn); } #ifndef MAIN_THREAD_POLLING glfwPostEmptyEvent(); #else if (std::this_thread::get_id() == mainThreadId) { handleInjections(); } #endif } GLFWmonitor* _activeMonitor; GLFWmonitor* getMonitor() { if (_activeMonitor) { return _activeMonitor; } else { GLFWmonitor *monitor = glfwGetPrimaryMonitor(); return monitor; } } NAN_METHOD(GetMonitors) { int monitor_count, mode_count, xpos, ypos, width, height; int i, j; GLFWmonitor **monitors = glfwGetMonitors(&monitor_count); GLFWmonitor *primary = glfwGetPrimaryMonitor(); const GLFWvidmode *mode, *modes; Local<Array> js_monitors = Nan::New<Array>(monitor_count); Local<Object> js_monitor, js_mode; Local<Array> js_modes; for(i=0; i<monitor_count; i++){ js_monitor = Nan::New<Object>(); js_monitor->Set(JS_STR("is_primary"), JS_BOOL(monitors[i] == primary)); js_monitor->Set(JS_STR("index"), JS_INT(i)); js_monitor->Set(JS_STR("name"), JS_STR(glfwGetMonitorName(monitors[i]))); glfwGetMonitorPos(monitors[i], &xpos, &ypos); js_monitor->Set(JS_STR("pos_x"), JS_INT(xpos)); js_monitor->Set(JS_STR("pos_y"), JS_INT(ypos)); glfwGetMonitorPhysicalSize(monitors[i], &width, &height); js_monitor->Set(JS_STR("width_mm"), JS_INT(width)); js_monitor->Set(JS_STR("height_mm"), JS_INT(height)); mode = glfwGetVideoMode(monitors[i]); js_monitor->Set(JS_STR("width"), JS_INT(mode->width)); js_monitor->Set(JS_STR("height"), JS_INT(mode->height)); js_monitor->Set(JS_STR("rate"), JS_INT(mode->refreshRate)); modes = glfwGetVideoModes(monitors[i], &mode_count); js_modes = Nan::New<Array>(mode_count); for(j=0; j<mode_count; j++){ js_mode = Nan::New<Object>(); js_mode->Set(JS_STR("width"), JS_INT(modes[j].width)); js_mode->Set(JS_STR("height"), JS_INT(modes[j].height)); js_mode->Set(JS_STR("rate"), JS_INT(modes[j].refreshRate)); // NOTE: Are color bits necessary? js_modes->Set(JS_INT(j), js_mode); } js_monitor->Set(JS_STR("modes"), js_modes); js_monitors->Set(JS_INT(i), js_monitor); } info.GetReturnValue().Set(js_monitors); } NAN_METHOD(SetMonitor) { int index = TO_INT32(info[0]); int monitor_count; GLFWmonitor **monitors = glfwGetMonitors(&monitor_count); _activeMonitor = monitors[index]; } void GetScreenSize(int *width, int *height) { uv_sem_t sem; uv_sem_init(&sem, 0); QueueInjection([&](InjectionHandler *injectionHandler) -> void { GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *videoMode = glfwGetVideoMode(monitor); *width = videoMode->width; *height = videoMode->height; uv_sem_post(&sem); }); uv_sem_wait(&sem); uv_sem_destroy(&sem); } NAN_METHOD(GetScreenSize) { int width, height; GetScreenSize(&width, &height); Local<Array> result = Nan::New<Array>(2); result->Set(0, JS_INT(width)); result->Set(1, JS_INT(height)); info.GetReturnValue().Set(result); } // Window callbacks handling void APIENTRY windowPosCB(NATIVEwindow *window, int xpos, int ypos) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("move")); evt->Set(JS_STR("x"),JS_INT(xpos)); evt->Set(JS_STR("y"),JS_INT(ypos)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("move"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY windowSizeCB(NATIVEwindow *window, int w, int h) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("windowResize")); evt->Set(JS_STR("width"),JS_INT(w)); evt->Set(JS_STR("height"),JS_INT(h)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("windowResize"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY windowFramebufferSizeCB(NATIVEwindow *window, int w, int h) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("framebufferResize")); evt->Set(JS_STR("width"),JS_INT(w)); evt->Set(JS_STR("height"),JS_INT(h)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("framebufferResize"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY windowDropCB(NATIVEwindow *window, int count, const char **paths) { std::vector<char *> localPaths(count); for (int i = 0; i < count; i++) { const char *path = paths[i]; size_t size = strlen(path) + 1; char *localPath = new char[size]; memcpy(localPath, path, size); localPaths[i] = localPath; } QueueEvent(window, [localPaths{std::move(localPaths)}](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Array> pathsArray = Nan::New<Array>(localPaths.size()); for (int i = 0; i < localPaths.size(); i++) { pathsArray->Set(i, JS_STR(localPaths[i])); } Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("paths"), pathsArray); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("drop"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); for (int i = 0; i < localPaths.size(); i++) { delete[] localPaths[i]; } }); } void APIENTRY windowCloseCB(NATIVEwindow *window) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("quit"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY windowRefreshCB(NATIVEwindow *window) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("refresh")); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("refresh"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY windowFocusCB(NATIVEwindow *window, int focused) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("focus")); evt->Set(JS_STR("focused"),JS_BOOL((bool)focused)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("focus"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY windowMaximizeCB(NATIVEwindow *window, int maximized) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("maximize")); evt->Set(JS_STR("maximized"),JS_BOOL((bool)maximized)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("maximize"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY windowIconifyCB(NATIVEwindow *window, int iconified) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("minimize")); evt->Set(JS_STR("minimized"),JS_BOOL((bool)iconified)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("minimize"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } static int jsKeyCode[]={ /*GLFW_KEY_ESCAPE*/ 27, /*GLFW_KEY_ENTER*/ 13, /*GLFW_KEY_TAB*/ 9, /*GLFW_KEY_BACKSPACE*/ 8, /*GLFW_KEY_INSERT*/ 45, /*GLFW_KEY_DELETE*/ 46, /*GLFW_KEY_RIGHT*/ 39, /*GLFW_KEY_LEFT*/ 37, /*GLFW_KEY_DOWN*/ 40, /*GLFW_KEY_UP*/ 38, /*GLFW_KEY_PAGE_UP*/ 33, /*GLFW_KEY_PAGE_DOWN*/ 34, /*GLFW_KEY_HOME*/ 36, /*GLFW_KEY_END*/ 35, /*GLFW_KEY_CAPS_LOCK*/ 20, /*GLFW_KEY_SCROLL_LOCK*/ 145, /*GLFW_KEY_NUM_LOCK*/ 144, /*GLFW_KEY_PRINT_SCREEN*/ 144, /* TODO */ /*GLFW_KEY_PAUSE*/ 19, /*GLFW_KEY_F1*/ 112, /*GLFW_KEY_F2*/ 113, /*GLFW_KEY_F3*/ 114, /*GLFW_KEY_F4*/ 115, /*GLFW_KEY_F5*/ 116, /*GLFW_KEY_F6*/ 117, /*GLFW_KEY_F7*/ 118, /*GLFW_KEY_F8*/ 119, /*GLFW_KEY_F9*/ 120, /*GLFW_KEY_F10*/ 121, /*GLFW_KEY_F11*/ 122, /*GLFW_KEY_F12*/ 123, /*GLFW_KEY_F13*/ 123, /* unknown */ /*GLFW_KEY_F14*/ 123, /* unknown */ /*GLFW_KEY_F15*/ 123, /* unknown */ /*GLFW_KEY_F16*/ 123, /* unknown */ /*GLFW_KEY_F17*/ 123, /* unknown */ /*GLFW_KEY_F18*/ 123, /* unknown */ /*GLFW_KEY_F19*/ 123, /* unknown */ /*GLFW_KEY_F20*/ 123, /* unknown */ /*GLFW_KEY_F21*/ 123, /* unknown */ /*GLFW_KEY_F22*/ 123, /* unknown */ /*GLFW_KEY_F23*/ 123, /* unknown */ /*GLFW_KEY_F24*/ 123, /* unknown */ /*GLFW_KEY_F25*/ 123, /* unknown */ /*GLFW_KEY_KP_0*/ 96, /*GLFW_KEY_KP_1*/ 97, /*GLFW_KEY_KP_2*/ 98, /*GLFW_KEY_KP_3*/ 99, /*GLFW_KEY_KP_4*/ 100, /*GLFW_KEY_KP_5*/ 101, /*GLFW_KEY_KP_6*/ 102, /*GLFW_KEY_KP_7*/ 103, /*GLFW_KEY_KP_8*/ 104, /*GLFW_KEY_KP_9*/ 105, /*GLFW_KEY_KP_DECIMAL*/ 110, /*GLFW_KEY_KP_DIVIDE*/ 111, /*GLFW_KEY_KP_MULTIPLY*/ 106, /*GLFW_KEY_KP_SUBTRACT*/ 109, /*GLFW_KEY_KP_ADD*/ 107, /*GLFW_KEY_KP_ENTER*/ 13, /*GLFW_KEY_KP_EQUAL*/ 187, /*GLFW_KEY_LEFT_SHIFT*/ 16, /*GLFW_KEY_LEFT_CONTROL*/ 17, /*GLFW_KEY_LEFT_ALT*/ 18, /*GLFW_KEY_LEFT_SUPER*/ 91, /*GLFW_KEY_RIGHT_SHIFT*/ 16, /*GLFW_KEY_RIGHT_CONTROL*/17, /*GLFW_KEY_RIGHT_ALT*/ 18, /*GLFW_KEY_RIGHT_SUPER*/ 93, /*GLFW_KEY_MENU*/ 18 }; const char *actionNames = "keyup\0 keydown\0keypress"; void APIENTRY keyCB(NATIVEwindow *window, int key, int scancode, int action, int mods) { if (key >= 0) { // media keys are -1 bool isPrintable = true; switch (key) { case GLFW_KEY_ESCAPE: case GLFW_KEY_ENTER: case GLFW_KEY_TAB: case GLFW_KEY_BACKSPACE: case GLFW_KEY_INSERT: case GLFW_KEY_DELETE: case GLFW_KEY_RIGHT: case GLFW_KEY_LEFT: case GLFW_KEY_DOWN: case GLFW_KEY_UP: case GLFW_KEY_PAGE_UP: case GLFW_KEY_PAGE_DOWN: case GLFW_KEY_HOME: case GLFW_KEY_END: case GLFW_KEY_CAPS_LOCK: case GLFW_KEY_SCROLL_LOCK: case GLFW_KEY_NUM_LOCK: case GLFW_KEY_PRINT_SCREEN: case GLFW_KEY_PAUSE: case GLFW_KEY_F1: case GLFW_KEY_F2: case GLFW_KEY_F3: case GLFW_KEY_F4: case GLFW_KEY_F5: case GLFW_KEY_F6: case GLFW_KEY_F7: case GLFW_KEY_F8: case GLFW_KEY_F9: case GLFW_KEY_F10: case GLFW_KEY_F11: case GLFW_KEY_F12: case GLFW_KEY_F13: case GLFW_KEY_F14: case GLFW_KEY_F15: case GLFW_KEY_F16: case GLFW_KEY_F17: case GLFW_KEY_F18: case GLFW_KEY_F19: case GLFW_KEY_F20: case GLFW_KEY_F21: case GLFW_KEY_F22: case GLFW_KEY_F23: case GLFW_KEY_F24: case GLFW_KEY_F25: case GLFW_KEY_LEFT_SHIFT: case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_LEFT_ALT: case GLFW_KEY_LEFT_SUPER: case GLFW_KEY_RIGHT_SHIFT: case GLFW_KEY_RIGHT_CONTROL: case GLFW_KEY_RIGHT_ALT: case GLFW_KEY_RIGHT_SUPER: case GLFW_KEY_MENU: isPrintable = false; } if (!isPrintable && action == GLFW_REPEAT) { action = GLFW_PRESS; } int charCode = key; if (action == GLFW_RELEASE || action == GLFW_PRESS) { switch (key) { case GLFW_KEY_SLASH: key = 191; break; // / case GLFW_KEY_GRAVE_ACCENT: key = 192; break; // ` case GLFW_KEY_LEFT_BRACKET: key = 219; break; // [ case GLFW_KEY_BACKSLASH: key = 220; break; /* \ */ case GLFW_KEY_RIGHT_BRACKET: key = 221; break; // ] case GLFW_KEY_APOSTROPHE: key = 222; break; // ' case GLFW_KEY_PERIOD: key = 190; break; // ' case GLFW_KEY_COMMA: key = 188; break; // ' case GLFW_KEY_SEMICOLON: key = 186; break; // ; case GLFW_KEY_EQUAL: key = 187; break; // = case GLFW_KEY_MINUS: key = 189; break; // - } } switch (key) { case GLFW_KEY_ESCAPE: key = 27; break; case GLFW_KEY_ENTER: key = 13; break; case GLFW_KEY_TAB: key = 9; break; case GLFW_KEY_BACKSPACE: key = 8; break; case GLFW_KEY_INSERT: key = 45; break; case GLFW_KEY_DELETE: key = 46; break; case GLFW_KEY_RIGHT: key = 39; break; case GLFW_KEY_LEFT: key = 37; break; case GLFW_KEY_DOWN: key = 40; break; case GLFW_KEY_UP: key = 38; break; case GLFW_KEY_PAGE_UP: key = 33; break; case GLFW_KEY_PAGE_DOWN: key = 34; break; case GLFW_KEY_HOME: key = 36; break; case GLFW_KEY_END: key = 35; break; case GLFW_KEY_CAPS_LOCK: key = 20; break; case GLFW_KEY_SCROLL_LOCK: key = 145; break; case GLFW_KEY_NUM_LOCK: key = 144; break; case GLFW_KEY_PRINT_SCREEN: key = 144; break; /* TODO */ case GLFW_KEY_PAUSE: key = 19; break; case GLFW_KEY_F1: key = 112; break; case GLFW_KEY_F2: key = 113; break; case GLFW_KEY_F3: key = 114; break; case GLFW_KEY_F4: key = 115; break; case GLFW_KEY_F5: key = 116; break; case GLFW_KEY_F6: key = 117; break; case GLFW_KEY_F7: key = 118; break; case GLFW_KEY_F8: key = 119; break; case GLFW_KEY_F9: key = 120; break; case GLFW_KEY_F10: key = 121; break; case GLFW_KEY_F11: key = 122; break; case GLFW_KEY_F12: key = 123; break; case GLFW_KEY_F13: key = 123; break; /* unknown */ case GLFW_KEY_F14: key = 123; break; /* unknown */ case GLFW_KEY_F15: key = 123; break; /* unknown */ case GLFW_KEY_F16: key = 123; break; /* unknown */ case GLFW_KEY_F17: key = 123; break; /* unknown */ case GLFW_KEY_F18: key = 123; break; /* unknown */ case GLFW_KEY_F19: key = 123; break; /* unknown */ case GLFW_KEY_F20: key = 123; break; /* unknown */ case GLFW_KEY_F21: key = 123; break; /* unknown */ case GLFW_KEY_F22: key = 123; break; /* unknown */ case GLFW_KEY_F23: key = 123; break; /* unknown */ case GLFW_KEY_F24: key = 123; break; /* unknown */ case GLFW_KEY_F25: key = 123; break; /* unknown */ case GLFW_KEY_KP_0: key = 96; break; case GLFW_KEY_KP_1: key = 97; break; case GLFW_KEY_KP_2: key = 98; break; case GLFW_KEY_KP_3: key = 99; break; case GLFW_KEY_KP_4: key = 100; break; case GLFW_KEY_KP_5: key = 101; break; case GLFW_KEY_KP_6: key = 102; break; case GLFW_KEY_KP_7: key = 103; break; case GLFW_KEY_KP_8: key = 104; break; case GLFW_KEY_KP_9: key = 105; break; case GLFW_KEY_KP_DECIMAL: key = 110; break; case GLFW_KEY_KP_DIVIDE: key = 111; break; case GLFW_KEY_KP_MULTIPLY: key = 106; break; case GLFW_KEY_KP_SUBTRACT: key = 109; break; case GLFW_KEY_KP_ADD: key = 107; break; case GLFW_KEY_KP_ENTER: key = 13; break; case GLFW_KEY_KP_EQUAL: key = 187; break; case GLFW_KEY_LEFT_SHIFT: key = 16; break; case GLFW_KEY_LEFT_CONTROL: key = 17; break; case GLFW_KEY_LEFT_ALT: key = 18; break; case GLFW_KEY_LEFT_SUPER: key = 91; break; case GLFW_KEY_RIGHT_SHIFT: key = 16; break; case GLFW_KEY_RIGHT_CONTROL: key = 17; break; case GLFW_KEY_RIGHT_ALT: key = 18; break; case GLFW_KEY_RIGHT_SUPER: key = 93; break; case GLFW_KEY_MENU: key = 18; break; } if ( action == 2 && // keypress key >= 65 && // A key <= 90 // Z ) { key += 32; } int which = key; QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"), JS_STR(&actionNames[action << 3])); evt->Set(JS_STR("ctrlKey"), JS_BOOL(mods & GLFW_MOD_CONTROL)); evt->Set(JS_STR("shiftKey"), JS_BOOL(mods & GLFW_MOD_SHIFT)); evt->Set(JS_STR("altKey"), JS_BOOL(mods & GLFW_MOD_ALT)); evt->Set(JS_STR("metaKey"), JS_BOOL(mods & GLFW_MOD_SUPER)); evt->Set(JS_STR("which"), JS_INT(which)); evt->Set(JS_STR("keyCode"), JS_INT(key)); evt->Set(JS_STR("charCode"), JS_INT(charCode)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR(&actionNames[action << 3]), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); if (action == GLFW_PRESS && isPrintable) { keyCB(window, charCode, scancode, GLFW_REPEAT, mods); } } } void APIENTRY cursorPosCB(NATIVEwindow* window, double x, double y) { int w, h; glfwGetWindowSize(window, &w, &h); if(x<0 || x>=w) return; if(y<0 || y>=h) return; int xi = static_cast<int>(x); int yi = static_cast<int>(y); int movementX, movementY; int mode = glfwGetInputMode(window, GLFW_CURSOR); if (mode == GLFW_CURSOR_DISABLED) { movementX = xi - (w / 2); movementY = yi - (h / 2); glfwSetCursorPos(window, w / 2, h / 2); } else { if (lastX != -1 && lastY != -1) { movementX = xi - lastX; movementY = yi - lastY; } else { movementX = 0; movementY = 0; } } lastX = xi; lastY = yi; QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("mousemove")); evt->Set(JS_STR("clientX"),JS_NUM(x)); evt->Set(JS_STR("clientY"),JS_NUM(y)); evt->Set(JS_STR("pageX"),JS_NUM(x)); evt->Set(JS_STR("pageY"),JS_NUM(y)); evt->Set(JS_STR("offsetX"),JS_NUM(x)); evt->Set(JS_STR("offsetY"),JS_NUM(y)); evt->Set(JS_STR("screenX"),JS_NUM(x)); evt->Set(JS_STR("screenY"),JS_NUM(y)); evt->Set(JS_STR("movementX"),JS_NUM(movementX)); evt->Set(JS_STR("movementY"),JS_NUM(movementY)); evt->Set(JS_STR("ctrlKey"),JS_BOOL(glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)); evt->Set(JS_STR("shiftKey"),JS_BOOL(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS)); evt->Set(JS_STR("altKey"),JS_BOOL(glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS)); evt->Set(JS_STR("metaKey"),JS_BOOL(glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("mousemove"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY cursorEnterCB(NATIVEwindow* window, int entered) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("mouseenter")); evt->Set(JS_STR("entered"),JS_INT(entered)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("mouseenter"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } void APIENTRY mouseButtonCB(NATIVEwindow *window, int button, int action, int mods) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); int localButton = button; if (localButton == 2) { localButton = 1; } else if (localButton == 1) { localButton = 2; } { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR(action ? "mousedown" : "mouseup")); evt->Set(JS_STR("button"),JS_INT(localButton)); evt->Set(JS_STR("which"),JS_INT(localButton + 1)); evt->Set(JS_STR("clientX"),JS_NUM(xpos)); evt->Set(JS_STR("clientY"),JS_NUM(ypos)); evt->Set(JS_STR("pageX"),JS_NUM(xpos)); evt->Set(JS_STR("pageY"),JS_NUM(ypos)); evt->Set(JS_STR("offsetX"),JS_NUM(xpos)); evt->Set(JS_STR("offsetY"),JS_NUM(ypos)); evt->Set(JS_STR("screenX"),JS_NUM(xpos)); evt->Set(JS_STR("screenY"),JS_NUM(ypos)); evt->Set(JS_STR("shiftKey"),JS_BOOL(mods & GLFW_MOD_SHIFT)); evt->Set(JS_STR("ctrlKey"),JS_BOOL(mods & GLFW_MOD_CONTROL)); evt->Set(JS_STR("altKey"),JS_BOOL(mods & GLFW_MOD_ALT)); evt->Set(JS_STR("metaKey"),JS_BOOL(mods & GLFW_MOD_SUPER)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR(action ? "mousedown" : "mouseup"), // event name evt }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); } if (!action) { Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("click")); evt->Set(JS_STR("button"),JS_INT(localButton)); evt->Set(JS_STR("which"),JS_INT(localButton + 1)); evt->Set(JS_STR("clientX"),JS_NUM(xpos)); evt->Set(JS_STR("clientY"),JS_NUM(ypos)); evt->Set(JS_STR("pageX"),JS_NUM(xpos)); evt->Set(JS_STR("pageY"),JS_NUM(ypos)); evt->Set(JS_STR("offsetX"),JS_NUM(xpos)); evt->Set(JS_STR("offsetY"),JS_NUM(ypos)); evt->Set(JS_STR("screenX"),JS_NUM(xpos)); evt->Set(JS_STR("screenY"),JS_NUM(ypos)); evt->Set(JS_STR("shiftKey"),JS_BOOL(mods & GLFW_MOD_SHIFT)); evt->Set(JS_STR("ctrlKey"),JS_BOOL(mods & GLFW_MOD_CONTROL)); evt->Set(JS_STR("altKey"),JS_BOOL(mods & GLFW_MOD_ALT)); evt->Set(JS_STR("metaKey"),JS_BOOL(mods & GLFW_MOD_SUPER)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("click"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); uint64_t now = glfwGetTimerValue(); uint64_t timeDiffTicks = now - lastClickTime; uint64_t frequency = glfwGetTimerFrequency(); double timeDiffSeconds = (double)timeDiffTicks / (double)frequency; if (timeDiffSeconds < 0.2) { evt->Set(JS_STR("type"),JS_STR("dblclick")); Local<Value> argv[] = { JS_STR("dblclick"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); } lastClickTime = now; } }); } void APIENTRY scrollCB(NATIVEwindow *window, double xoffset, double yoffset) { QueueEvent(window, [=](std::function<void(int, Local<Value> *)> eventHandlerFn) -> void { double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); Local<Object> evt = Nan::New<Object>(); evt->Set(JS_STR("type"),JS_STR("wheel")); evt->Set(JS_STR("clientX"),JS_NUM(xpos)); evt->Set(JS_STR("clientY"),JS_NUM(ypos)); evt->Set(JS_STR("deltaX"),JS_NUM(-xoffset*120)); evt->Set(JS_STR("deltaY"),JS_NUM(-yoffset*120)); evt->Set(JS_STR("deltaZ"),JS_INT(0)); evt->Set(JS_STR("deltaMode"),JS_INT(0)); // evt->Set(JS_STR("windowHandle"), pointerToArray(window)); Local<Value> argv[] = { JS_STR("wheel"), // event name evt, }; eventHandlerFn(sizeof(argv)/sizeof(argv[0]), argv); }); } NAN_METHOD(BlitTopFrameBuffer) { GLuint fbo1 = TO_UINT32(info[0]); GLuint fbo2 = TO_UINT32(info[1]); int sw = TO_UINT32(info[2]); int sh = TO_UINT32(info[3]); int dw = TO_UINT32(info[4]); int dh = TO_UINT32(info[5]); bool color = TO_BOOL(info[6]); bool depth = TO_BOOL(info[7]); bool stencil = TO_BOOL(info[8]); glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo1); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo2); glBlitFramebuffer( 0, 0, sw, sh, 0, 0, dw, dh, (color ? GL_COLOR_BUFFER_BIT : 0) | (depth ? GL_DEPTH_BUFFER_BIT : 0) | (stencil ? GL_STENCIL_BUFFER_BIT : 0), (depth || stencil) ? GL_NEAREST : GL_LINEAR ); } NAN_METHOD(BlitChildFrameBuffer) { Local<Object> glObj = Local<Object>::Cast(info[0]); GLuint srcTex = TO_UINT32(info[1]); GLuint srcDepthTex = TO_UINT32(info[2]); bool isMultisampleSrc = Local<Boolean>::Cast(info[3])->Value(); GLuint tex = TO_UINT32(info[4]); GLuint depthTex = TO_UINT32(info[5]); bool isMultisampleDst = Local<Boolean>::Cast(info[6])->Value(); int sw = TO_UINT32(info[7]); int sh = TO_UINT32(info[8]); int dw = TO_UINT32(info[9]); int dh = TO_UINT32(info[10]); GLuint readFbo; glGenFramebuffers(1, &readFbo); glBindFramebuffer(GL_READ_FRAMEBUFFER, readFbo); glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, isMultisampleSrc ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, srcTex, 0); if (srcDepthTex != 0) { glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, isMultisampleSrc ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, srcDepthTex, 0); } GLuint drawFbo = 0; if (tex != 0) { glGenFramebuffers(1, &drawFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFbo); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, isMultisampleDst ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, tex, 0); if (depthTex != 0) { glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, isMultisampleDst ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D, depthTex, 0); } } else { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } glBlitFramebuffer( 0, 0, sw, sh, 0, 0, dw, dh, GL_COLOR_BUFFER_BIT | (srcDepthTex ? (GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT) : 0), srcDepthTex ? GL_NEAREST : GL_LINEAR ); glDeleteFramebuffers(1, &readFbo); if (drawFbo != 0) { glDeleteFramebuffers(1, &drawFbo); } WebGLRenderingContext *gl = ObjectWrap::Unwrap<WebGLRenderingContext>(glObj); if (gl->HasFramebufferBinding(GL_READ_FRAMEBUFFER)) { glBindFramebuffer(GL_READ_FRAMEBUFFER, gl->GetFramebufferBinding(GL_READ_FRAMEBUFFER)); } else { glBindFramebuffer(GL_READ_FRAMEBUFFER, gl->defaultFramebuffer); } if (gl->HasFramebufferBinding(GL_DRAW_FRAMEBUFFER)) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gl->GetFramebufferBinding(GL_DRAW_FRAMEBUFFER)); } else { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gl->defaultFramebuffer); } } NATIVEwindow *GetCurrentWindowContext() { return currentWindow; } void SetCurrentWindowContext(NATIVEwindow *window) { if (currentWindow != window) { glfwMakeContextCurrent(window); currentWindow = window; } } void ReadPixels(WebGLRenderingContext *gl, unsigned int fbo, int x, int y, int width, int height, unsigned int format, unsigned int type, unsigned char *data) { glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data); if (gl->HasFramebufferBinding(GL_READ_FRAMEBUFFER)) { glBindFramebuffer(GL_READ_FRAMEBUFFER, gl->GetFramebufferBinding(GL_READ_FRAMEBUFFER)); } else { glBindFramebuffer(GL_READ_FRAMEBUFFER, gl->defaultFramebuffer); } } NAN_METHOD(HasCurrentWindowContext) { info.GetReturnValue().Set(JS_BOOL(currentWindow != nullptr)); } NAN_METHOD(GetCurrentWindowContext) { if (currentWindow != nullptr) { info.GetReturnValue().Set(pointerToArray(currentWindow)); } else { info.GetReturnValue().Set(Nan::Null()); } } NAN_METHOD(SetCurrentWindowContext) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); SetCurrentWindowContext(window); } bool SetNativeWindowIcon(NATIVEwindow* window, const char* filename) { GLFWimage icon; int components; icon.pixels = stbi_load(filename, &icon.width, &icon.height, &components, STBI_rgb_alpha); if (icon.pixels != nullptr) { glfwSetWindowIcon(window, 1, &icon); stbi_image_free(icon.pixels); return true; } return false; } NATIVEwindow *CreateNativeWindow(unsigned int width, unsigned int height, bool visible) { glfwWindowHint(GLFW_VISIBLE, visible); { std::lock_guard<std::mutex> lock(windowHandleMutex); if (!sharedWindow) { sharedWindow = glfwCreateWindow(1, 1, "Exokit", nullptr, nullptr); if (sharedWindow) { glfwSetWindowUserPointer(sharedWindow, new WindowState()); } else { exerr << "Can't create GLFW window" << std::endl; abort(); return nullptr; } } } NATIVEwindow *window = glfwCreateWindow(width, height, "Exokit", nullptr, sharedWindow); if (window) { glfwSetWindowUserPointer(window, new WindowState()); SetNativeWindowIcon(window, "assets/icon.png"); return window; } else { exerr << "Can't create GLFW window" << std::endl; abort(); return nullptr; } } void DestroyNativeWindow(NATIVEwindow *window) { WindowState *windowState = (WindowState *)glfwGetWindowUserPointer(window); delete windowState; glfwDestroyWindow(window); } NAN_METHOD(SetWindowTitle) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); Nan::Utf8String str(Local<String>::Cast(info[1])); glfwSetWindowTitle(window, *str); } void GetWindowSize(NATIVEwindow *window, int *width, int *height) { glfwGetWindowSize(window, width, height); } NAN_METHOD(GetWindowSize) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); int w, h; GetWindowSize(window, &w, &h); Local<Object> result = Nan::New<Object>(); result->Set(JS_STR("width"),JS_INT(w)); result->Set(JS_STR("height"),JS_INT(h)); info.GetReturnValue().Set(result); } NAN_METHOD(SetWindowSize) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); glfwSetWindowSize(window, TO_UINT32(info[1]), TO_UINT32(info[2])); } NAN_METHOD(SetWindowPos) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); glfwSetWindowPos(window, TO_UINT32(info[1]), TO_UINT32(info[2])); } NAN_METHOD(GetWindowPos) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); int xpos, ypos; glfwGetWindowPos(window, &xpos, &ypos); Local<Object> result = Nan::New<Object>(); result->Set(JS_STR("xpos"),JS_INT(xpos)); result->Set(JS_STR("ypos"),JS_INT(ypos)); info.GetReturnValue().Set(result); } void GetFramebufferSize(NATIVEwindow *window, int *width, int *height) { glfwGetFramebufferSize(window, width, height); } NAN_METHOD(GetFramebufferSize) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); int width, height; GetFramebufferSize(window, &width, &height); Local<Object> result = Nan::New<Object>(); result->Set(JS_STR("width"),JS_INT(width)); result->Set(JS_STR("height"),JS_INT(height)); info.GetReturnValue().Set(result); } double GetDevicePixelRatio() { int width, height; uv_sem_t sem; uv_sem_init(&sem, 0); QueueInjection([&](InjectionHandler *injectionHandler) -> void { NATIVEwindow *window = CreateNativeWindow(100, 100, false); glfwGetFramebufferSize(window, &width, &height); DestroyNativeWindow(window); uv_sem_post(&sem); }); uv_sem_wait(&sem); uv_sem_destroy(&sem); return static_cast<double>(width)/100.0; } NAN_METHOD(GetDevicePixelRatio) { double devicePixelRatio = GetDevicePixelRatio(); info.GetReturnValue().Set(JS_NUM(devicePixelRatio)); } NATIVEwindow *GetGLContext(NATIVEwindow *window) { return window; } NAN_METHOD(IconifyWindow) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); glfwIconifyWindow(window); } NAN_METHOD(RestoreWindow) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); glfwRestoreWindow(window); } NAN_METHOD(SetVisibility) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); bool visible = TO_BOOL(info[1]); QueueInjection([window, visible](InjectionHandler *injectionHandler) -> void { if (visible) { glfwShowWindow(window); } else { glfwHideWindow(window); } }); } NAN_METHOD(SetWindowFocus) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); glfwFocusWindow(window); } NAN_METHOD(IsVisible) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); bool visible = glfwGetWindowAttrib(window, GLFW_VISIBLE); info.GetReturnValue().Set(JS_BOOL(visible)); } const GLFWvidmode *getBestVidMode(NATIVEwindow *window, GLFWmonitor *monitor) { int numVidModes; const GLFWvidmode *vidModes = glfwGetVideoModes(monitor, &numVidModes); const GLFWvidmode *bestVidMode = nullptr; for (int i = 0; i < numVidModes; i++) { const GLFWvidmode *vidMode = &vidModes[i]; if (bestVidMode == nullptr || vidMode->width > bestVidMode->width) { bestVidMode = vidMode; } } return bestVidMode; } NAN_METHOD(SetFullscreen) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); bool enabled = TO_BOOL(info[1]); QueueInjection([window, enabled](InjectionHandler *injectionHandler) -> void { GLFWmonitor *monitor = getMonitor(); if (enabled) { const GLFWvidmode *vidMode = getBestVidMode(window, monitor); if (vidMode != nullptr) { glfwSetWindowMonitor(window, monitor, 0, 0, vidMode->width, vidMode->height, 0); } } else { const GLFWvidmode *vidMode = getBestVidMode(window, monitor); glfwSetWindowMonitor(window, nullptr, vidMode->width/2 - 1280/2, vidMode->height/2 - 1024/2, 1280, 1024, 0); } }); } NAN_METHOD(InitWindow3D) { NATIVEwindow *windowHandle = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); WebGLRenderingContext *gl = ObjectWrap::Unwrap<WebGLRenderingContext>(Local<Object>::Cast(info[1])); SetCurrentWindowContext(windowHandle); GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); #ifdef GL_VERTEX_PROGRAM_POINT_SIZE glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #endif #ifdef GL_PROGRAM_POINT_SIZE glEnable(GL_PROGRAM_POINT_SIZE); #endif Local<Array> result = Nan::New<Array>(2); result->Set(0, pointerToArray(windowHandle)); result->Set(1, JS_INT(vao)); info.GetReturnValue().Set(result); } NATIVEwindow *CreateWindowHandle(unsigned int width, unsigned int height, bool initialVisible) { NATIVEwindow *windowHandle; uv_sem_t sem; uv_sem_init(&sem, 0); QueueInjection([&](InjectionHandler *injectionHandler) -> void { windowHandle = CreateNativeWindow(width, height, initialVisible); SetCurrentWindowContext(windowHandle); GLenum err = glewInit(); if (!err) { // swap interval glfwSwapInterval(0); // input mode // glfwSetInputMode(windowHandle, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // window callbacks glfwSetWindowPosCallback(windowHandle, windowPosCB); glfwSetWindowSizeCallback(windowHandle, windowSizeCB); glfwSetWindowCloseCallback(windowHandle, windowCloseCB); glfwSetWindowRefreshCallback(windowHandle, windowRefreshCB); glfwSetWindowFocusCallback(windowHandle, windowFocusCB); glfwSetWindowMaximizeCallback(windowHandle, windowMaximizeCB); glfwSetWindowIconifyCallback(windowHandle, windowIconifyCB); glfwSetFramebufferSizeCallback(windowHandle, windowFramebufferSizeCB); glfwSetDropCallback(windowHandle, windowDropCB); // input callbacks glfwSetKeyCallback(windowHandle, keyCB); glfwSetMouseButtonCallback(windowHandle, mouseButtonCB); glfwSetCursorPosCallback(windowHandle, cursorPosCB); glfwSetCursorEnterCallback(windowHandle, cursorEnterCB); glfwSetScrollCallback(windowHandle, scrollCB); // size setting glfwSetWindowSizeLimits(windowHandle, 1, 1, GLFW_DONT_CARE, GLFW_DONT_CARE); } else { /* Problem: glewInit failed, something is seriously wrong. */ exerr << "Can't init GLEW (glew error " << (const char *)glewGetErrorString(err) << ")" << std::endl; DestroyNativeWindow(windowHandle); windowHandle = nullptr; } SetCurrentWindowContext(nullptr); uv_sem_post(&sem); }); uv_sem_wait(&sem); uv_sem_destroy(&sem); return windowHandle; } NAN_METHOD(CreateWindowHandle) { unsigned int width = info[0]->IsNumber() ? TO_UINT32(info[0]) : 1; unsigned int height = info[1]->IsNumber() ? TO_UINT32(info[1]) : 1; bool initialVisible = TO_BOOL(info[2]); NATIVEwindow *windowHandle = CreateWindowHandle(width, height, initialVisible); if (windowHandle) { info.GetReturnValue().Set(pointerToArray(windowHandle)); } else { info.GetReturnValue().Set(Nan::Null()); } } NAN_METHOD(DestroyWindowHandle) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); uv_sem_t sem; uv_sem_init(&sem, 0); QueueInjection([&](InjectionHandler *injectionHandler) -> void { DestroyNativeWindow(window); uv_sem_post(&sem); }); uv_sem_wait(&sem); uv_sem_destroy(&sem); } NAN_METHOD(SetEventHandler) { if (info[0]->IsArray() && info[1]->IsFunction()) { Local<Array> windowHandle = Local<Array>::Cast(info[0]); Local<Function> handlerFn = Local<Function>::Cast(info[1]); NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(windowHandle); WindowState *windowState = (WindowState *)glfwGetWindowUserPointer(window); uv_loop_t *loop = windowsystembase::GetEventLoop(); EventHandler *handler = new EventHandler(loop, handlerFn); windowState->handler.reset(handler); } else { Nan::ThrowError("SetEventHandler: invalid arguments"); } } NAN_METHOD(SwapBuffers) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); glfwSwapBuffers(window); } NAN_METHOD(GetRefreshRate) { int refreshRate; GLFWmonitor *monitor = getMonitor(); if (monitor) { const GLFWvidmode *mode = glfwGetVideoMode(monitor); refreshRate = mode->refreshRate; } else { refreshRate = 60; } info.GetReturnValue().Set(refreshRate); } NAN_METHOD(SetCursorMode) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); bool enabled = TO_BOOL(info[1]); QueueInjection([window, enabled](InjectionHandler *injectionHandler) -> void { if (enabled) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } else { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); int w, h; glfwGetWindowSize(window, &w, &h); int centerX = w/2; int centerY = h/2; glfwSetCursorPos(window, centerX, centerY); /* lastX = centerX; lastY = centerY; */ } }); } NAN_METHOD(SetCursorPosition) { NATIVEwindow *window = (NATIVEwindow *)arrayToPointer(Local<Array>::Cast(info[0])); int x = TO_INT32(info[1]); int y = TO_INT32(info[2]); glfwSetCursorPos(window, x, y); } NAN_METHOD(GetClipboard) { NATIVEwindow *window = GetCurrentWindowContext(); const char *clipboardContents = glfwGetClipboardString(window); if (clipboardContents != nullptr) { info.GetReturnValue().Set(JS_STR(clipboardContents)); } else { info.GetReturnValue().Set(Nan::Null()); } } NAN_METHOD(SetClipboard) { if (info[0]->IsString()) { NATIVEwindow *window = GetCurrentWindowContext(); Nan::Utf8String utf8_value(info[0]); glfwSetClipboardString(window, *utf8_value); } else { Nan::ThrowTypeError("Invalid arguments"); } } #ifdef MAIN_THREAD_POLLING NAN_METHOD(PollEvents) { glfwPollEvents(); handleInjections(); } #endif } /////////////////////////////////////////////////////////////////////////////// // // bindings // /////////////////////////////////////////////////////////////////////////////// #define JS_GLFW_CONSTANT(name) target->Set(JS_STR( #name ), JS_INT(GLFW_ ## name)) #define JS_GLFW_SET_METHOD(name) Nan::SetMethod(target, #name , glfw::name); /* Local<Object> makeGlfw() { glfwInit(); glewInit(); atexit([]() { glfwTerminate(); }); Isolate *isolate = Isolate::GetCurrent(); v8::EscapableHandleScope scope(isolate); Local<Object> target = Object::New(isolate); // GLFW initialization, termination and version querying JS_GLFW_SET_METHOD(GetVersion); JS_GLFW_SET_METHOD(GetVersionString); // Time JS_GLFW_SET_METHOD(GetTime); JS_GLFW_SET_METHOD(SetTime); // Monitor handling JS_GLFW_SET_METHOD(GetMonitors); // Window handling //JS_GLFW_SET_METHOD(CreateWindow); Nan::SetMethod(target, "CreateWindow", glfw::glfw_CreateWindow); Nan::SetMethod(target, "GetRenderTarget", glfw::GetRenderTarget); Nan::SetMethod(target, "BindFrameBuffer", glfw::BindFrameBuffer); Nan::SetMethod(target, "BlitFrameBuffer", glfw::BlitFrameBuffer); JS_GLFW_SET_METHOD(WindowHint); JS_GLFW_SET_METHOD(DefaultWindowHints); JS_GLFW_SET_METHOD(DestroyWindow); JS_GLFW_SET_METHOD(SetWindowShouldClose); JS_GLFW_SET_METHOD(WindowShouldClose); JS_GLFW_SET_METHOD(SetWindowTitle); JS_GLFW_SET_METHOD(GetWindowSize); JS_GLFW_SET_METHOD(SetWindowSize); JS_GLFW_SET_METHOD(SetWindowPos); JS_GLFW_SET_METHOD(GetWindowPos); JS_GLFW_SET_METHOD(GetFramebufferSize); JS_GLFW_SET_METHOD(IconifyWindow); JS_GLFW_SET_METHOD(RestoreWindow); JS_GLFW_SET_METHOD(ShowWindow); JS_GLFW_SET_METHOD(HideWindow); JS_GLFW_SET_METHOD(GetWindowAttrib); JS_GLFW_SET_METHOD(SetInputMode); JS_GLFW_SET_METHOD(PollEvents); JS_GLFW_SET_METHOD(WaitEvents); // Input handling JS_GLFW_SET_METHOD(GetKey); JS_GLFW_SET_METHOD(GetMouseButton); JS_GLFW_SET_METHOD(GetCursorPos); JS_GLFW_SET_METHOD(SetCursorPos); // Context handling JS_GLFW_SET_METHOD(MakeContextCurrent); JS_GLFW_SET_METHOD(GetCurrentContext); JS_GLFW_SET_METHOD(SwapBuffers); JS_GLFW_SET_METHOD(SwapInterval); JS_GLFW_SET_METHOD(ExtensionSupported); // Joystick JS_GLFW_SET_METHOD(JoystickPresent); JS_GLFW_SET_METHOD(GetJoystickAxes); JS_GLFW_SET_METHOD(GetJoystickButtons); JS_GLFW_SET_METHOD(GetJoystickName); // GLFW version JS_GLFW_CONSTANT(VERSION_MAJOR); JS_GLFW_CONSTANT(VERSION_MINOR); JS_GLFW_CONSTANT(VERSION_REVISION); // Input handling definitions // Key and button state/action definitions JS_GLFW_CONSTANT(RELEASE); JS_GLFW_CONSTANT(PRESS); JS_GLFW_CONSTANT(REPEAT); // These key codes are inspired by the *USB HID Usage Tables v1.12* (p. 53-60), // but re-arranged to map to 7-bit ASCII for printable keys (function keys are // put in the 256+ range). // // The naming of the key codes follow these rules: // - The US keyboard layout is used // - Names of printable alpha-numeric characters are used (e.g. "A", "R", // "3", etc.) // - For non-alphanumeric characters, Unicode:ish names are used (e.g. // "COMMA", "LEFT_SQUARE_BRACKET", etc.). Note that some names do not // correspond to the Unicode standard (usually for brevity) // - Keys that lack a clear US mapping are named "WORLD_x" // - For non-printable keys, custom names are used (e.g. "F4", // "BACKSPACE", etc.) // The unknown key JS_GLFW_CONSTANT(KEY_UNKNOWN); // Printable keys JS_GLFW_CONSTANT(KEY_SPACE); JS_GLFW_CONSTANT(KEY_APOSTROPHE); JS_GLFW_CONSTANT(KEY_COMMA); JS_GLFW_CONSTANT(KEY_MINUS); JS_GLFW_CONSTANT(KEY_PERIOD); JS_GLFW_CONSTANT(KEY_SLASH); JS_GLFW_CONSTANT(KEY_0); JS_GLFW_CONSTANT(KEY_1); JS_GLFW_CONSTANT(KEY_2); JS_GLFW_CONSTANT(KEY_3); JS_GLFW_CONSTANT(KEY_4); JS_GLFW_CONSTANT(KEY_5); JS_GLFW_CONSTANT(KEY_6); JS_GLFW_CONSTANT(KEY_7); JS_GLFW_CONSTANT(KEY_8); JS_GLFW_CONSTANT(KEY_9); JS_GLFW_CONSTANT(KEY_SEMICOLON); JS_GLFW_CONSTANT(KEY_EQUAL); JS_GLFW_CONSTANT(KEY_A); JS_GLFW_CONSTANT(KEY_B); JS_GLFW_CONSTANT(KEY_C); JS_GLFW_CONSTANT(KEY_D); JS_GLFW_CONSTANT(KEY_E); JS_GLFW_CONSTANT(KEY_F); JS_GLFW_CONSTANT(KEY_G); JS_GLFW_CONSTANT(KEY_H); JS_GLFW_CONSTANT(KEY_I); JS_GLFW_CONSTANT(KEY_J); JS_GLFW_CONSTANT(KEY_K); JS_GLFW_CONSTANT(KEY_L); JS_GLFW_CONSTANT(KEY_M); JS_GLFW_CONSTANT(KEY_N); JS_GLFW_CONSTANT(KEY_O); JS_GLFW_CONSTANT(KEY_P); JS_GLFW_CONSTANT(KEY_Q); JS_GLFW_CONSTANT(KEY_R); JS_GLFW_CONSTANT(KEY_S); JS_GLFW_CONSTANT(KEY_T); JS_GLFW_CONSTANT(KEY_U); JS_GLFW_CONSTANT(KEY_V); JS_GLFW_CONSTANT(KEY_W); JS_GLFW_CONSTANT(KEY_X); JS_GLFW_CONSTANT(KEY_Y); JS_GLFW_CONSTANT(KEY_Z); JS_GLFW_CONSTANT(KEY_LEFT_BRACKET); JS_GLFW_CONSTANT(KEY_BACKSLASH); JS_GLFW_CONSTANT(KEY_RIGHT_BRACKET); JS_GLFW_CONSTANT(KEY_GRAVE_ACCENT); JS_GLFW_CONSTANT(KEY_WORLD_1); JS_GLFW_CONSTANT(KEY_WORLD_2); // Function keys JS_GLFW_CONSTANT(KEY_ESCAPE); JS_GLFW_CONSTANT(KEY_ENTER); JS_GLFW_CONSTANT(KEY_TAB); JS_GLFW_CONSTANT(KEY_BACKSPACE); JS_GLFW_CONSTANT(KEY_INSERT); JS_GLFW_CONSTANT(KEY_DELETE); JS_GLFW_CONSTANT(KEY_RIGHT); JS_GLFW_CONSTANT(KEY_LEFT); JS_GLFW_CONSTANT(KEY_DOWN); JS_GLFW_CONSTANT(KEY_UP); JS_GLFW_CONSTANT(KEY_PAGE_UP); JS_GLFW_CONSTANT(KEY_PAGE_DOWN); JS_GLFW_CONSTANT(KEY_HOME); JS_GLFW_CONSTANT(KEY_END); JS_GLFW_CONSTANT(KEY_CAPS_LOCK); JS_GLFW_CONSTANT(KEY_SCROLL_LOCK); JS_GLFW_CONSTANT(KEY_NUM_LOCK); JS_GLFW_CONSTANT(KEY_PRINT_SCREEN); JS_GLFW_CONSTANT(KEY_PAUSE); JS_GLFW_CONSTANT(KEY_F1); JS_GLFW_CONSTANT(KEY_F2); JS_GLFW_CONSTANT(KEY_F3); JS_GLFW_CONSTANT(KEY_F4); JS_GLFW_CONSTANT(KEY_F5); JS_GLFW_CONSTANT(KEY_F6); JS_GLFW_CONSTANT(KEY_F7); JS_GLFW_CONSTANT(KEY_F8); JS_GLFW_CONSTANT(KEY_F9); JS_GLFW_CONSTANT(KEY_F10); JS_GLFW_CONSTANT(KEY_F11); JS_GLFW_CONSTANT(KEY_F12); JS_GLFW_CONSTANT(KEY_F13); JS_GLFW_CONSTANT(KEY_F14); JS_GLFW_CONSTANT(KEY_F15); JS_GLFW_CONSTANT(KEY_F16); JS_GLFW_CONSTANT(KEY_F17); JS_GLFW_CONSTANT(KEY_F18); JS_GLFW_CONSTANT(KEY_F19); JS_GLFW_CONSTANT(KEY_F20); JS_GLFW_CONSTANT(KEY_F21); JS_GLFW_CONSTANT(KEY_F22); JS_GLFW_CONSTANT(KEY_F23); JS_GLFW_CONSTANT(KEY_F24); JS_GLFW_CONSTANT(KEY_F25); JS_GLFW_CONSTANT(KEY_KP_0); JS_GLFW_CONSTANT(KEY_KP_1); JS_GLFW_CONSTANT(KEY_KP_2); JS_GLFW_CONSTANT(KEY_KP_3); JS_GLFW_CONSTANT(KEY_KP_4); JS_GLFW_CONSTANT(KEY_KP_5); JS_GLFW_CONSTANT(KEY_KP_6); JS_GLFW_CONSTANT(KEY_KP_7); JS_GLFW_CONSTANT(KEY_KP_8); JS_GLFW_CONSTANT(KEY_KP_9); JS_GLFW_CONSTANT(KEY_KP_DECIMAL); JS_GLFW_CONSTANT(KEY_KP_DIVIDE); JS_GLFW_CONSTANT(KEY_KP_MULTIPLY); JS_GLFW_CONSTANT(KEY_KP_SUBTRACT); JS_GLFW_CONSTANT(KEY_KP_ADD); JS_GLFW_CONSTANT(KEY_KP_ENTER); JS_GLFW_CONSTANT(KEY_KP_EQUAL); JS_GLFW_CONSTANT(KEY_LEFT_SHIFT); JS_GLFW_CONSTANT(KEY_LEFT_CONTROL); JS_GLFW_CONSTANT(KEY_LEFT_ALT); JS_GLFW_CONSTANT(KEY_LEFT_SUPER); JS_GLFW_CONSTANT(KEY_RIGHT_SHIFT); JS_GLFW_CONSTANT(KEY_RIGHT_CONTROL); JS_GLFW_CONSTANT(KEY_RIGHT_ALT); JS_GLFW_CONSTANT(KEY_RIGHT_SUPER); JS_GLFW_CONSTANT(KEY_MENU); JS_GLFW_CONSTANT(KEY_LAST); // Modifier key flags // If this bit is set one or more Shift keys were held down. JS_GLFW_CONSTANT(MOD_SHIFT); // If this bit is set one or more Control keys were held down. JS_GLFW_CONSTANT(MOD_CONTROL); // If this bit is set one or more Alt keys were held down. JS_GLFW_CONSTANT(MOD_ALT); // If this bit is set one or more Super keys were held down. JS_GLFW_CONSTANT(MOD_SUPER); // Mouse buttons JS_GLFW_CONSTANT(MOUSE_BUTTON_1); JS_GLFW_CONSTANT(MOUSE_BUTTON_2); JS_GLFW_CONSTANT(MOUSE_BUTTON_3); JS_GLFW_CONSTANT(MOUSE_BUTTON_4); JS_GLFW_CONSTANT(MOUSE_BUTTON_5); JS_GLFW_CONSTANT(MOUSE_BUTTON_6); JS_GLFW_CONSTANT(MOUSE_BUTTON_7); JS_GLFW_CONSTANT(MOUSE_BUTTON_8); JS_GLFW_CONSTANT(MOUSE_BUTTON_LAST); JS_GLFW_CONSTANT(MOUSE_BUTTON_LEFT); JS_GLFW_CONSTANT(MOUSE_BUTTON_RIGHT); JS_GLFW_CONSTANT(MOUSE_BUTTON_MIDDLE); // Joysticks JS_GLFW_CONSTANT(JOYSTICK_1); JS_GLFW_CONSTANT(JOYSTICK_2); JS_GLFW_CONSTANT(JOYSTICK_3); JS_GLFW_CONSTANT(JOYSTICK_4); JS_GLFW_CONSTANT(JOYSTICK_5); JS_GLFW_CONSTANT(JOYSTICK_6); JS_GLFW_CONSTANT(JOYSTICK_7); JS_GLFW_CONSTANT(JOYSTICK_8); JS_GLFW_CONSTANT(JOYSTICK_9); JS_GLFW_CONSTANT(JOYSTICK_10); JS_GLFW_CONSTANT(JOYSTICK_11); JS_GLFW_CONSTANT(JOYSTICK_12); JS_GLFW_CONSTANT(JOYSTICK_13); JS_GLFW_CONSTANT(JOYSTICK_14); JS_GLFW_CONSTANT(JOYSTICK_15); JS_GLFW_CONSTANT(JOYSTICK_16); JS_GLFW_CONSTANT(JOYSTICK_LAST); // errors Error codes // GLFW has not been initialized. JS_GLFW_CONSTANT(NOT_INITIALIZED); // No context is current for this thread. JS_GLFW_CONSTANT(NO_CURRENT_CONTEXT); // One of the enum parameters for the function was given an invalid enum. JS_GLFW_CONSTANT(INVALID_ENUM); // One of the parameters for the function was given an invalid value. JS_GLFW_CONSTANT(INVALID_VALUE); // A memory allocation failed. JS_GLFW_CONSTANT(OUT_OF_MEMORY); // GLFW could not find support for the requested client API on the system. JS_GLFW_CONSTANT(API_UNAVAILABLE); // The requested client API version is not available. JS_GLFW_CONSTANT(VERSION_UNAVAILABLE); // A platform-specific error occurred that does not match any of the more specific categories. JS_GLFW_CONSTANT(PLATFORM_ERROR); // The clipboard did not contain data in the requested format. JS_GLFW_CONSTANT(FORMAT_UNAVAILABLE); JS_GLFW_CONSTANT(FOCUSED); JS_GLFW_CONSTANT(ICONIFIED); JS_GLFW_CONSTANT(RESIZABLE); JS_GLFW_CONSTANT(VISIBLE); JS_GLFW_CONSTANT(DECORATED); JS_GLFW_CONSTANT(RED_BITS); JS_GLFW_CONSTANT(GREEN_BITS); JS_GLFW_CONSTANT(BLUE_BITS); JS_GLFW_CONSTANT(ALPHA_BITS); JS_GLFW_CONSTANT(DEPTH_BITS); JS_GLFW_CONSTANT(STENCIL_BITS); JS_GLFW_CONSTANT(ACCUM_RED_BITS); JS_GLFW_CONSTANT(ACCUM_GREEN_BITS); JS_GLFW_CONSTANT(ACCUM_BLUE_BITS); JS_GLFW_CONSTANT(ACCUM_ALPHA_BITS); JS_GLFW_CONSTANT(AUX_BUFFERS); JS_GLFW_CONSTANT(STEREO); JS_GLFW_CONSTANT(SAMPLES); JS_GLFW_CONSTANT(SRGB_CAPABLE); JS_GLFW_CONSTANT(REFRESH_RATE); JS_GLFW_CONSTANT(DOUBLEBUFFER); JS_GLFW_CONSTANT(TRUE); JS_GLFW_CONSTANT(FALSE); JS_GLFW_CONSTANT(CLIENT_API); JS_GLFW_CONSTANT(CONTEXT_VERSION_MAJOR); JS_GLFW_CONSTANT(CONTEXT_VERSION_MINOR); JS_GLFW_CONSTANT(CONTEXT_REVISION); JS_GLFW_CONSTANT(CONTEXT_ROBUSTNESS); JS_GLFW_CONSTANT(OPENGL_FORWARD_COMPAT); JS_GLFW_CONSTANT(OPENGL_DEBUG_CONTEXT); JS_GLFW_CONSTANT(OPENGL_PROFILE); JS_GLFW_CONSTANT(OPENGL_API); JS_GLFW_CONSTANT(OPENGL_ES_API); JS_GLFW_CONSTANT(NO_ROBUSTNESS); JS_GLFW_CONSTANT(NO_RESET_NOTIFICATION); JS_GLFW_CONSTANT(LOSE_CONTEXT_ON_RESET); JS_GLFW_CONSTANT(OPENGL_ANY_PROFILE); JS_GLFW_CONSTANT(OPENGL_CORE_PROFILE); JS_GLFW_CONSTANT(OPENGL_COMPAT_PROFILE); JS_GLFW_CONSTANT(CURSOR); JS_GLFW_CONSTANT(STICKY_KEYS); JS_GLFW_CONSTANT(STICKY_MOUSE_BUTTONS); JS_GLFW_CONSTANT(CURSOR_NORMAL); JS_GLFW_CONSTANT(CURSOR_HIDDEN); JS_GLFW_CONSTANT(CURSOR_DISABLED); JS_GLFW_CONSTANT(CONNECTED); JS_GLFW_CONSTANT(DISCONNECTED); // test scene JS_GLFW_SET_METHOD(testScene); JS_GLFW_SET_METHOD(testJoystick); return scope.Escape(target); } */ Local<Object> makeWindow() { #ifdef MAIN_THREAD_POLLING if (!glfw::hasMainThreadId) { glfw::mainThreadId = std::this_thread::get_id(); glfw::hasMainThreadId = true; } #endif Isolate *isolate = Isolate::GetCurrent(); v8::EscapableHandleScope scope(isolate); Local<Object> target = Object::New(isolate); windowsystembase::Decorate(target); Nan::SetMethod(target, "initWindow3D", glfw::InitWindow3D); Nan::SetMethod(target, "createWindowHandle", glfw::CreateWindowHandle); Nan::SetMethod(target, "destroyWindowHandle", glfw::DestroyWindowHandle); Nan::SetMethod(target, "setVisibility", glfw::SetVisibility); Nan::SetMethod(target, "isVisible", glfw::IsVisible); Nan::SetMethod(target, "setFullscreen", glfw::SetFullscreen); Nan::SetMethod(target, "getMonitors", glfw::GetMonitors); Nan::SetMethod(target, "setMonitor", glfw::SetMonitor); Nan::SetMethod(target, "getScreenSize", glfw::GetScreenSize); Nan::SetMethod(target, "setWindowTitle", glfw::SetWindowTitle); Nan::SetMethod(target, "getWindowSize", glfw::GetWindowSize); Nan::SetMethod(target, "setWindowSize", glfw::SetWindowSize); Nan::SetMethod(target, "setWindowPos", glfw::SetWindowPos); Nan::SetMethod(target, "getWindowPos", glfw::GetWindowPos); Nan::SetMethod(target, "setWindowFocus", glfw::SetWindowFocus); Nan::SetMethod(target, "getFramebufferSize", glfw::GetFramebufferSize); Nan::SetMethod(target, "getDevicePixelRatio", glfw::GetDevicePixelRatio); Nan::SetMethod(target, "iconifyWindow", glfw::IconifyWindow); Nan::SetMethod(target, "restoreWindow", glfw::RestoreWindow); Nan::SetMethod(target, "setEventHandler", glfw::SetEventHandler); Nan::SetMethod(target, "swapBuffers", glfw::SwapBuffers); Nan::SetMethod(target, "getRefreshRate", glfw::GetRefreshRate); Nan::SetMethod(target, "setCursorMode", glfw::SetCursorMode); Nan::SetMethod(target, "setCursorPosition", glfw::SetCursorPosition); Nan::SetMethod(target, "getClipboard", glfw::GetClipboard); Nan::SetMethod(target, "setClipboard", glfw::SetClipboard); Nan::SetMethod(target, "blitTopFrameBuffer", glfw::BlitTopFrameBuffer); Nan::SetMethod(target, "blitChildFrameBuffer", glfw::BlitChildFrameBuffer); Nan::SetMethod(target, "hasCurrentWindowContext", glfw::HasCurrentWindowContext); Nan::SetMethod(target, "getCurrentWindowContext", glfw::GetCurrentWindowContext); Nan::SetMethod(target, "setCurrentWindowContext", glfw::SetCurrentWindowContext); #ifdef MAIN_THREAD_POLLING Nan::SetMethod(target, "pollEvents", glfw::PollEvents); #endif return scope.Escape(target); }
59,237
24,539
/**************************************************************************************** * @author: kzvd4729 created: Jun/28/2019 19:22 * solution_verdict: Accepted language: GNU C++14 * run_time: 31 ms memory_used: 0 KB * problem: https://codeforces.com/contest/1183/problem/B ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int q;cin>>q; while(q--) { int n,k;cin>>n>>k;int mn=1e9,mx=0; for(int i=1;i<=n;i++) { int x;cin>>x; mn=min(mn,x);mx=max(mx,x); } if(mx-mn>k+k)cout<<-1<<"\n"; else cout<<mn+k<<"\n"; } return 0; }
955
314
//package toolbox #include "Maths.h" /* static void printMatrix(glm::mat4& m, string name) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { cout << name << "[" << i << "," << j << "] = " << m[j][i] << " "; } cout << endl; } cout << endl; } */ glm::mat4 createTransformationMatrix(glm::vec3& translation, GLfloat rx, GLfloat ry, GLfloat rz, GLfloat scale) { glm::mat4 unit = glm::mat4(1.0f); // identity matrix glm::mat4 t = glm::translate(unit, glm::vec3(translation[0], translation[1], translation[2])); //printMatrix(t, "t"); glm::mat4 rotx = glm::rotate(unit, glm::radians(rx), glm::vec3(1.0f, 0.0f, 0.0f)); //printMatrix(rotx, "rotx"); glm::mat4 roty = glm::rotate(unit, glm::radians(ry), glm::vec3(0.0f, 1.0f, 0.0f)); //printMatrix(roty, "roty"); glm::mat4 rotz = glm::rotate(unit, glm::radians(rz), glm::vec3(0.0f, 0.0f, 1.0f)); //printMatrix(rotz, "rotz"); glm::mat4 r = rotx * roty * rotz; //printMatrix(r, "r"); glm::mat4 s = glm::scale(unit, glm::vec3(scale)); //printMatrix(s, "s"); glm::mat4 m = s * r * t; //printMatrix(m, "m"); return m; }
1,120
539
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * 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 Server Side 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. */ #include "mongo/platform/basic.h" #include <boost/optional.hpp> #include <string> #include "mongo/db/auth/action_type.h" #include "mongo/db/auth/authorization_session.h" #include "mongo/db/auth/privilege.h" #include "mongo/db/catalog_raii.h" #include "mongo/db/commands.h" #include "mongo/db/field_parser.h" #include "mongo/db/jsobj.h" #include "mongo/db/namespace_string.h" #include "mongo/db/range_arithmetic.h" #include "mongo/db/s/chunk_move_write_concern_options.h" #include "mongo/db/s/collection_sharding_runtime.h" #include "mongo/db/s/migration_util.h" #include "mongo/db/s/shard_filtering_metadata_refresh.h" #include "mongo/db/s/sharding_runtime_d_params_gen.h" #include "mongo/db/s/sharding_state.h" #include "mongo/db/service_context.h" #include "mongo/logv2/log.h" #include "mongo/s/request_types/migration_secondary_throttle_options.h" #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand namespace mongo { namespace { enum class CleanupResult { kDone, kContinue, kError }; /** * Waits for all possibly orphaned ranges on 'nss' to be cleaned up. * * @return CleanupResult::kDone if no orphaned ranges remain * @return CleanupResult::kError and 'errMsg' if an error occurred * * If the collection is not sharded, returns CleanupResult::kDone. */ CleanupResult cleanupOrphanedData(OperationContext* opCtx, const NamespaceString& ns, const BSONObj& startingFromKeyConst, std::string* errMsg) { boost::optional<ChunkRange> range; boost::optional<UUID> collectionUuid; { AutoGetCollection autoColl(opCtx, ns, MODE_IX); if (!autoColl.getCollection()) { LOGV2(4416000, "cleanupOrphaned skipping waiting for orphaned data cleanup because " "{namespace} does not exist", "cleanupOrphaned skipping waiting for orphaned data cleanup because " "collection does not exist", "namespace"_attr = ns.ns()); return CleanupResult::kDone; } collectionUuid.emplace(autoColl.getCollection()->uuid()); auto* const csr = CollectionShardingRuntime::get(opCtx, ns); const auto optCollDescr = csr->getCurrentMetadataIfKnown(); if (!optCollDescr || !optCollDescr->isSharded()) { LOGV2(4416001, "cleanupOrphaned skipping waiting for orphaned data cleanup because " "{namespace} is not sharded", "cleanupOrphaned skipping waiting for orphaned data cleanup because " "collection is not sharded", "namespace"_attr = ns.ns()); return CleanupResult::kDone; } range.emplace(optCollDescr->getMinKey(), optCollDescr->getMaxKey()); // Though the 'startingFromKey' parameter is not used as the min key of the range to // wait for, we still validate that 'startingFromKey' in the same way as the original // cleanupOrphaned logic did if 'startingFromKey' is present. BSONObj keyPattern = optCollDescr->getKeyPattern(); if (!startingFromKeyConst.isEmpty() && !optCollDescr->isValidKey(startingFromKeyConst)) { LOGV2_ERROR_OPTIONS( 4416002, {logv2::UserAssertAfterLog(ErrorCodes::OrphanedRangeCleanUpFailed)}, "Could not cleanup orphaned data because start key does not match shard key " "pattern", "startKey"_attr = redact(startingFromKeyConst), "shardKeyPattern"_attr = keyPattern); } } // We actually want to wait until there are no range deletion tasks for this namespace/UUID, // but we don't have a good way to wait for that event, so instead we wait for there to be // no tasks being processed in memory for this namespace/UUID. // However, it's possible this node has recently stepped up, and the stepup recovery task to // resubmit range deletion tasks for processing has not yet completed. In that case, // waitForClean will return though there are still tasks in config.rangeDeletions, so we // sleep for a short time and then try waitForClean again. while (auto numRemainingDeletionTasks = migrationutil::checkForConflictingDeletions(opCtx, *range, *collectionUuid)) { uassert(ErrorCodes::ResumableRangeDeleterDisabled, "Failing cleanupOrphaned because the disableResumableRangeDeleter server parameter " "is set to true and this shard contains range deletion tasks for the collection.", !disableResumableRangeDeleter.load()); LOGV2(4416003, "cleanupOrphaned going to wait for range deletion tasks to complete", "namespace"_attr = ns.ns(), "collectionUUID"_attr = *collectionUuid, "numRemainingDeletionTasks"_attr = numRemainingDeletionTasks); auto status = CollectionShardingRuntime::waitForClean( opCtx, ns, *collectionUuid, *range, Date_t::max()); if (!status.isOK()) { *errMsg = status.reason(); return CleanupResult::kError; } opCtx->sleepFor(Milliseconds(1000)); } return CleanupResult::kDone; } /** * Called on a particular namespace, and if the collection is sharded will wait for the number of * range deletion tasks on the collection on this shard to reach zero. * * Since the sharding state may change after this call returns, there is no guarantee that orphans * won't re-appear as a result of migrations that commit after this call returns. * * Safe to call with the balancer on. */ class CleanupOrphanedCommand : public ErrmsgCommandDeprecated { public: CleanupOrphanedCommand() : ErrmsgCommandDeprecated("cleanupOrphaned") {} AllowedOnSecondary secondaryAllowed(ServiceContext*) const override { return AllowedOnSecondary::kNever; } bool adminOnly() const override { return true; } Status checkAuthForCommand(Client* client, const std::string& dbname, const BSONObj& cmdObj) const override { if (!AuthorizationSession::get(client)->isAuthorizedForActionsOnResource( ResourcePattern::forClusterResource(), ActionType::cleanupOrphaned)) { return Status(ErrorCodes::Unauthorized, "Not authorized for cleanupOrphaned command."); } return Status::OK(); } bool supportsWriteConcern(const BSONObj& cmd) const override { return true; } // Input static BSONField<std::string> nsField; static BSONField<BSONObj> startingFromKeyField; bool errmsgRun(OperationContext* opCtx, std::string const& db, const BSONObj& cmdObj, std::string& errmsg, BSONObjBuilder& result) override { std::string ns; if (!FieldParser::extract(cmdObj, nsField, &ns, &errmsg)) { return false; } const NamespaceString nss(ns); uassert(ErrorCodes::InvalidNamespace, str::stream() << "Invalid namespace: " << nss.ns(), nss.isValid()); BSONObj startingFromKey; if (!FieldParser::extract(cmdObj, startingFromKeyField, &startingFromKey, &errmsg)) { return false; } ShardingState* const shardingState = ShardingState::get(opCtx); if (!shardingState->enabled()) { errmsg = str::stream() << "server is not part of a sharded cluster or " << "the sharding metadata is not yet initialized."; return false; } onShardVersionMismatch(opCtx, nss, boost::none); CleanupResult cleanupResult = cleanupOrphanedData(opCtx, nss, startingFromKey, &errmsg); if (cleanupResult == CleanupResult::kError) { return false; } dassert(cleanupResult == CleanupResult::kDone); return true; } } cleanupOrphanedCmd; BSONField<std::string> CleanupOrphanedCommand::nsField("cleanupOrphaned"); BSONField<BSONObj> CleanupOrphanedCommand::startingFromKeyField("startingFromKey"); } // namespace } // namespace mongo
9,870
2,848
/* * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2008 Apple Inc. All rights 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 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include "third_party/blink/renderer/modules/plugins/dom_mime_type_array.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/page/plugin_data.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { DOMMimeTypeArray::DOMMimeTypeArray(LocalFrame* frame) : ExecutionContextLifecycleObserver(frame ? frame->DomWindow() : nullptr), PluginsChangedObserver(frame ? frame->GetPage() : nullptr) { UpdatePluginData(); } void DOMMimeTypeArray::Trace(Visitor* visitor) const { visitor->Trace(dom_mime_types_); ScriptWrappable::Trace(visitor); ExecutionContextLifecycleObserver::Trace(visitor); } unsigned DOMMimeTypeArray::length() const { return dom_mime_types_.size(); } DOMMimeType* DOMMimeTypeArray::item(unsigned index) { if (index >= dom_mime_types_.size()) return nullptr; if (!dom_mime_types_[index]) { dom_mime_types_[index] = MakeGarbageCollected<DOMMimeType>( GetFrame(), *GetPluginData()->Mimes()[index]); } return dom_mime_types_[index]; } DOMMimeType* DOMMimeTypeArray::namedItem(const AtomicString& property_name) { PluginData* data = GetPluginData(); if (!data) return nullptr; for (const Member<MimeClassInfo>& mime : data->Mimes()) { if (mime->Type() == property_name) { unsigned index = static_cast<unsigned>(&mime - &data->Mimes()[0]); return item(index); } } return nullptr; } void DOMMimeTypeArray::NamedPropertyEnumerator(Vector<String>& property_names, ExceptionState&) const { PluginData* data = GetPluginData(); if (!data) return; property_names.ReserveInitialCapacity(data->Mimes().size()); for (const MimeClassInfo* mime_info : data->Mimes()) { property_names.UncheckedAppend(mime_info->Type()); } } bool DOMMimeTypeArray::NamedPropertyQuery(const AtomicString& property_name, ExceptionState&) const { PluginData* data = GetPluginData(); if (!data) return false; return data->SupportsMimeType(property_name); } PluginData* DOMMimeTypeArray::GetPluginData() const { if (!GetFrame()) return nullptr; return GetFrame()->GetPluginData(); } void DOMMimeTypeArray::UpdatePluginData() { PluginData* data = GetPluginData(); if (!data) { dom_mime_types_.clear(); return; } HeapVector<Member<DOMMimeType>> old_dom_mime_types( std::move(dom_mime_types_)); dom_mime_types_.clear(); dom_mime_types_.resize(data->Mimes().size()); for (Member<DOMMimeType>& mime : old_dom_mime_types) { if (mime) { for (const Member<MimeClassInfo>& mime_info : data->Mimes()) { if (mime->type() == mime_info->Type()) { unsigned index = static_cast<unsigned>(&mime_info - &data->Mimes()[0]); dom_mime_types_[index] = mime; } } } } } void DOMMimeTypeArray::ContextDestroyed() { dom_mime_types_.clear(); } void DOMMimeTypeArray::PluginsChanged() { UpdatePluginData(); } } // namespace blink
4,161
1,400
// RUN: %clangxx -fsycl -fsyntax-only -Xclang -verify %s -Xclang -verify-ignore-unexpected=note,warning // expected-no-diagnostics //==--------------- id_ctad.cpp - SYCL id CTAD test ----------------------==// // // 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 <CL/sycl.hpp> using namespace std; int main() { cl::sycl::id one_dim_id(64); cl::sycl::id two_dim_id(64, 1); cl::sycl::id three_dim_id(64, 1, 2); static_assert(std::is_same<decltype(one_dim_id), cl::sycl::id<1>>::value); static_assert(std::is_same<decltype(two_dim_id), cl::sycl::id<2>>::value); static_assert(std::is_same<decltype(three_dim_id), cl::sycl::id<3>>::value); }
895
340
#include <JCDT_Lib/internal/ast/AstImportDeclaration.h> #include <JCDT_Lib/internal/ast/AstAnnotationDeclaration.h> #include <JCDT_Lib/internal/ast/AstPackageDeclaration.h> #ifndef AstCompilationUnit_def_INCLUDED #define AstCompilationUnit_def_INCLUDED #include "JCDT_Lib/internal/ast/CompilationUnitDeclaration.h" #include <JCDT_Lib/internal/lex/LexStream.h> #include <JCDT_Lib/internal/lookup/ASTVisitor.h> #include <JCDT_Lib/internal/ast/AstStoragePool.h> namespace Jikes { // Open namespace Jikes block void CompilationUnitDeclaration::Unparse(Ostream& os, LexStream* lex_stream) { unsigned i; if (debug_unparse) os << "/*CompilationUnitDeclaration:#" << id << "*/"; os << "// " << lex_stream -> FileName() << endl; if (package_declaration_opt) package_declaration_opt -> Unparse(os, lex_stream); for (i = 0; i < NumImportDeclarations(); i++) ImportDeclaration(i) -> Unparse(os, lex_stream); for (i = 0; i < NumTypeDeclarations(); i++) GetTypeDeclaration(i) -> Unparse(os, lex_stream); if (debug_unparse) os << "/*:CompilationUnitDeclaration#" << id << "*/"; } bool CompilationUnitDeclaration::IsEmpty() { if (package_declaration_opt) return false; if (NumImportDeclarations()) return false; if (NumTypeDeclarations()) return false; return true; } CompilationUnitDeclaration::CompilationUnitDeclaration(AstStoragePool* p) : Ast(COMPILATION), import_declarations(nullptr), type_declarations(nullptr) , ast_pool(p), package_declaration_opt(nullptr), state(HEAD_PARSE) {} void CompilationUnitDeclaration::FreeAst() { delete ast_pool; ast_pool = nullptr; } Ast* CompilationUnitDeclaration::Clone(AstStoragePool* ast_pool) { unsigned i; CompilationUnitDeclaration* clone = ast_pool->GenCompilationUnit(); clone->other_tag = other_tag; if (package_declaration_opt) clone->package_declaration_opt = (AstPackageDeclaration*) package_declaration_opt->Clone(ast_pool); clone->AllocateImportDeclarations(NumImportDeclarations()); for (i = 0; i < NumImportDeclarations(); i++) clone->AddImportDeclaration((AstImportDeclaration*) ImportDeclaration(i)->Clone(ast_pool)); clone->AllocateTypeDeclarations(NumTypeDeclarations()); for (i = 0; i < NumTypeDeclarations(); i++) clone->AddTypeDeclaration((TypeDeclaration*)GetTypeDeclaration(i) -> Clone(ast_pool)); return clone; } void CompilationUnitDeclaration::traverse(ASTVisitor* visitor,AstNodeScope* scope) { if (visitor->visit(this, this)) { unsigned i; if (package_declaration_opt) package_declaration_opt->traverse(visitor, this); unsigned num = NumImportDeclarations(); for (i = 0; i < num; i++) (*import_declarations)[i]->traverse(visitor, this); num = NumTypeDeclarations(); for (i = 0; i < num; i++) (*type_declarations)[i]->traverse(visitor, this); } visitor->endVisit(this, this); } void CompilationUnitDeclaration::Print(Ostream& os,LexStream& lex_stream) { unsigned i; os << endl << "AST structure for " << lex_stream.FileName() << ':' << endl << endl << '#' << id << " (CompilationUnit): #" << (package_declaration_opt ? package_declaration_opt -> id : 0) << " ("; for (i = 0; i < NumImportDeclarations(); i++) os << " #" << ImportDeclaration(i) -> id; os << " ) ("; for (i = 0; i < NumTypeDeclarations(); i++) os << " #" << GetTypeDeclaration(i) -> id; os << ')' << endl; if (package_declaration_opt) package_declaration_opt -> Print(os, lex_stream); for (i = 0; i < NumImportDeclarations(); i++) ImportDeclaration(i) -> Print(os, lex_stream); for (i = 0; i < NumTypeDeclarations(); i++) GetTypeDeclaration(i) -> Print(os, lex_stream); } Token* CompilationUnitDeclaration::LeftToken() { if (package_declaration_opt) return package_declaration_opt->package_token; if (NumImportDeclarations()) return ImportDeclaration(0)->import_token; if (NumTypeDeclarations()) return GetTypeDeclaration(0)->LeftToken(); return 0; } // Special top-level form void CompilationUnitDeclaration::Unparse(LexStream* lex_stream, const char* const directory) { auto in_file_name = lex_stream->FileName(); // const char* suffix = ".unparse"; const char* suffix = ""; char* out_file_name = strcat3(directory, in_file_name, suffix); // Create the directory if necessary SystemMkdirhierForFile(out_file_name); ofstream os_base(out_file_name); if (!os_base) { Ostream() << "Cannot open output file " << out_file_name << endl; ::abort(); } Ostream os(&os_base); Unparse(os, lex_stream); delete[] out_file_name; } Token* CompilationUnitDeclaration::RightToken() { if (NumTypeDeclarations()) return GetTypeDeclaration(NumTypeDeclarations() - 1)->RightToken(); if (NumImportDeclarations()) return ImportDeclaration(NumImportDeclarations() - 1) -> semicolon_token; if (package_declaration_opt) return package_declaration_opt->semicolon_token; return 0; } } // Close namespace Jikes block #endif // AstCompilationUnit_def_INCLUDED
5,183
1,861
#define STATIC_CHECK(expr) { char unamed[(expr) ? 1 : 0]; } template <class To, class From> To safe_reinterpret_cast(From from) { STATIC_CHECK(sizeof(From) <= sizeof(To)); return reinterpret_cast<To>(from); } int main() { int intValue = 5; char c = safe_reinterpret_cast<char>(intValue); return 0; }
323
128
// FEM_2D_Plane_Stress.cpp (Main) #include "pch.h" #include "FEM_Input.h" #include "FEM_GNUPlot.h" #include <Eigen/Dense> #include <Eigen/Sparse> #include <string> #include <vector> #include <iostream> #include <fstream> //Element data type struct Element { void CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector<Eigen::Triplet<float> >& triplets); Eigen::Matrix<float, 3, 6> B; int nodesIds[3]; }; //Boundary constraint data type struct Constraint { enum Type { UX = 1 << 0, UY = 1 << 1, UXY = UX | UY }; int node; Type type; }; //Globals int nodesCount; Eigen::VectorXf nodesX; Eigen::VectorXf nodesY; Eigen::VectorXf loads; std::vector< Element > elements; std::vector< Constraint > constraints; //Function for calculating the element stiffness matrix. void Element::CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector<Eigen::Triplet<float> >& triplets) { Eigen::Vector3f x, y; x << nodesX[nodesIds[0]], nodesX[nodesIds[1]], nodesX[nodesIds[2]]; y << nodesY[nodesIds[0]], nodesY[nodesIds[1]], nodesY[nodesIds[2]]; Eigen::Matrix3f C; C << Eigen::Vector3f(1.0f, 1.0f, 1.0f), x, y; //Calculating coefficients for shape functions (a1, a2, a3). //These are relevant for interpolation. Eigen::Matrix3f IC = C.inverse(); //Assemble B matrix for (int i = 0; i < 3; i++) { B(0, 2 * i + 0) = IC(1, i); B(0, 2 * i + 1) = 0.0f; B(1, 2 * i + 0) = 0.0f; B(1, 2 * i + 1) = IC(2, i); B(2, 2 * i + 0) = IC(2, i); B(2, 2 * i + 1) = IC(1, i); } //Calculate element stiffness (det(C)/2 = area of triangle). Eigen::Matrix<float, 6, 6> K = B.transpose() * D * B * C.determinant() / 2.0f; //Store values of element stiffness matrix with corresponding indices in global stiffness matrix in triplets. for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Eigen::Triplet<float> trplt11(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 0, K(2 * i + 0, 2 * j + 0)); Eigen::Triplet<float> trplt12(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 1, K(2 * i + 0, 2 * j + 1)); Eigen::Triplet<float> trplt21(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 0, K(2 * i + 1, 2 * j + 0)); Eigen::Triplet<float> trplt22(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 1, K(2 * i + 1, 2 * j + 1)); triplets.push_back(trplt11); triplets.push_back(trplt12); triplets.push_back(trplt21); triplets.push_back(trplt22); } } } //Function for setting constraints. void SetConstraints(Eigen::SparseMatrix<float>::InnerIterator& it, int index) { if (it.row() == index || it.col() == index) { it.valueRef() = it.row() == it.col() ? 1.0f : 0.0f; } } //Function for applying constraints in stiffness matrix. void ApplyConstraints(Eigen::SparseMatrix<float>& K, const std::vector<Constraint>& constraints) { std::vector<int> indicesToConstraint; for (std::vector<Constraint>::const_iterator it = constraints.begin(); it != constraints.end(); ++it) { if (it->type & Constraint::UX) { indicesToConstraint.push_back(2 * it->node + 0); } if (it->type & Constraint::UY) { indicesToConstraint.push_back(2 * it->node + 1); } } for (int k = 0; k < K.outerSize(); ++k) { for (Eigen::SparseMatrix<float>::InnerIterator it(K, k); it; ++it) { for (std::vector<int>::iterator idit = indicesToConstraint.begin(); idit != indicesToConstraint.end(); ++idit) { SetConstraints(it, *idit); } } } } int main(void) { std::cout << "---------------------- 2D FEM SOLVER ---------------------" << std::endl; std::cout << "FEM software for solving elastic 2D plain stress problems." << std::endl; std::cout << "Created by Joshua Simon. Date: 25.02.2019." << std::endl; std::cout << std::endl; //1. Paths and filenames string mesh_data_file; //This filename is read from user input. string solver_input_file = "Solver_Input.txt"; string displacement_plot_data = "GNUPlot_Input_displacement.txt"; string stress_plot_data = "GNUPlot_Input_contour.txt"; //User input of mesh data file std::cout << "Enter the filename of the GiD mesh data file. If the data file is " << std::endl; std::cout << "not in same folder as this application, than enter the whole path " << std::endl; std::cout << "of the mesh data file with filename. Use \\\\ for \\ in address. " << std::endl; std::cout << std::endl << "Filename >> "; std::cin >> mesh_data_file; std::cout << std::endl << std::endl; //2. Pre Processing: //Read GiD mesh Data and write solver input. std::cout << "Pre Processor: Define boundary conditions and loads." << std::endl << std::endl; generateSolverInput(mesh_data_file, solver_input_file); std::cout << "Pre Processor: Solver input generated!" << std::endl << std::endl; std::ifstream infile(solver_input_file); std::ofstream outfile("Solution_Data.txt"); //This file contains solution data. std::ofstream outfile_gnuplot(displacement_plot_data); //This file contains plot data. std::ofstream outfile_gnuplot_contur(stress_plot_data); //This file contains plot data. //3. Solution: std::cout << "Solver: Creating mathematical model..." << std::endl; //Read material specifications float poissonRatio, youngModulus; infile >> poissonRatio >> youngModulus; //Assemble elasticity matrix D Eigen::Matrix3f D; D << 1.0f, poissonRatio, 0.0f, poissonRatio, 1.0, 0.0f, 0.0f, 0.0f, (1.0f - poissonRatio) / 2.0f; D *= youngModulus / (1.0f - pow(poissonRatio, 2.0f)); //Read number of nodes and their coordinates infile >> nodesCount; nodesX.resize(nodesCount); nodesY.resize(nodesCount); for (int i = 0; i < nodesCount; ++i) { infile >> nodesX[i] >> nodesY[i]; } //Read number of elements and their nodes int elementCount; infile >> elementCount; for (int i = 0; i < elementCount; ++i) { Element element; infile >> element.nodesIds[0] >> element.nodesIds[1] >> element.nodesIds[2]; elements.push_back(element); } //Read number of constraints and their node settings int constraintCount; infile >> constraintCount; for (int i = 0; i < constraintCount; ++i) { Constraint constraint; int type; infile >> constraint.node >> type; constraint.type = static_cast<Constraint::Type>(type); constraints.push_back(constraint); } loads.resize(2 * nodesCount); loads.setZero(); //Read number of nodal loads and nodal forces int loadsCount; infile >> loadsCount; for (int i = 0; i < loadsCount; ++i) { int node; float x, y; infile >> node >> x >> y; loads[2 * node + 0] = x; loads[2 * node + 1] = y; } //Calculate stiffness matrix for each element std::vector<Eigen::Triplet<float> > triplets; for (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it) { it->CalculateStiffnessMatrix(D, triplets); } //Assemble global stiffness matirx Eigen::SparseMatrix<float> globalK(2 * nodesCount, 2 * nodesCount); globalK.setFromTriplets(triplets.begin(), triplets.end()); //Apply Constraints ApplyConstraints(globalK, constraints); std::cout << "Solver: Mathematical model created!" << std::endl; //Solving std::cout << "Solver: Solving in progress..." << std::endl; Eigen::SimplicialLDLT<Eigen::SparseMatrix<float> > solver(globalK); Eigen::VectorXf displacements = solver.solve(loads); std::cout << "Solver: Solving done!" << std::endl << std::endl; //Writing output and display on console //std::cout << "Loads vector:" << std::endl << loads << std::endl << std::endl; //Loads //std::cout << "Displacements vector:" << std::endl << displacements << std::endl; //Displaysments outfile << displacements << std::endl; //std::cout << "Stresses:" << std::endl; //Von Mises Stress int m = 0; float sigma_max = 0.0; float *sigma_mises = new float[elementCount]; for (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it) { Eigen::Matrix<float, 6, 1> delta; delta << displacements.segment<2>(2 * it->nodesIds[0]), displacements.segment<2>(2 * it->nodesIds[1]), displacements.segment<2>(2 * it->nodesIds[2]); Eigen::Vector3f sigma = D * it->B * delta; sigma_mises[m] = sqrt(sigma[0] * sigma[0] - sigma[0] * sigma[1] + sigma[1] * sigma[1] + 3.0f * sigma[2] * sigma[2]); //Search for maximum stress if (sigma_mises[m] > sigma_max) { sigma_max = sigma_mises[m]; } //std::cout << sigma_mises[m] << std::endl; //Von Mises Stress outfile << sigma_mises[m] << std::endl; m++; } //4. Post Processing: //4.1 Writing GNUPlot output file for ploting mesh and mesh + displacements for (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it) { //Prints x,y,dis-x,dis-y for every node of element in one line for (int i = 0; i < 3; i++) { outfile_gnuplot << nodesX(it->nodesIds[i]) << " " << nodesY(it->nodesIds[i]) \ << " " << displacements(it->nodesIds[i] * 2) << " " << displacements(it->nodesIds[i] * 2 + 1) << std::endl; } //First node of element has to appear twice for plotting purpose outfile_gnuplot << nodesX(it->nodesIds[0]) << " " << nodesY(it->nodesIds[0]) \ << " " << displacements(it->nodesIds[0] * 2) << " " << displacements(it->nodesIds[0] * 2 + 1) << std::endl; //Empty line to sperate between elements outfile_gnuplot << std::endl; } //4.2 Writing GNUPlot output file for stress contour plot outfile_gnuplot_contur << "unset xtics" << std::endl; outfile_gnuplot_contur << "unset ytics" << std::endl; outfile_gnuplot_contur << "set cbrange [0:1]" << std::endl << std::endl; outfile_gnuplot_contur << "plot[-15:15][-15:15] \\" << std::endl; //Write color information for every element int mm = 0; for (std::vector<Element>::iterator it = elements.begin(); it != (elements.end()-1); ++it) { outfile_gnuplot_contur << "\"-\" title \"\" with filledcurve lt palette cb " \ << sigma_mises[mm] / sigma_max << " \\" << std::endl; outfile_gnuplot_contur << "fillstyle transparent solid 1.000000 ,\\" << std::endl; mm++; } //Write color information for last element outfile_gnuplot_contur << "\"-\" title \"\" with filledcurve lt palette cb " \ << sigma_mises[elementCount-1] / sigma_max << " \\" << std::endl; outfile_gnuplot_contur << "fillstyle transparent solid 1.000000 ;" << std::endl; for (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it) { //Elements and their nodes: //Prints x,y for every node of element in one line for (int i = 0; i < 3; i++) { outfile_gnuplot_contur << nodesX(it->nodesIds[i]) << " " << nodesY(it->nodesIds[i]) << std::endl; } //First node of element has to appear twice for plotting purpose outfile_gnuplot_contur << nodesX(it->nodesIds[0]) << " " << nodesY(it->nodesIds[0]) << std::endl; //'e' to sperate between elements outfile_gnuplot_contur << "e" << std::endl; } std::cout << "Post Processor: Plotting solution..." << std::endl << std::endl; //4.3 Plot results plot(displacement_plot_data); delete[] sigma_mises; return 0; }
11,278
4,547
#include "runtime.h" #include <math.h> int Call_int_ref_double_double_double_double_int_(double x1, double x2, double x3, double x4, int y, void* __context) { #define fpart(x) (x - floor(x)) double xgap = fpart(x1 + 0.5); return int(xgap * 10.0) == 1 && y && x2 == 2.0 && x3 == 3.0 && x4 == 4.0; #undef fpart }
315
149
#include "GPUBasedProperty.h"
30
13
#include <Scheduler.h> #include <System.h> #include <IDT.h> #include <Logging.h> #include <APIC.h> #include <Fs/Filesystem.h> #include <Device.h> #define KEY_QUEUE_SIZE 256 namespace Keyboard{ uint8_t keyQueue[KEY_QUEUE_SIZE]; unsigned short keyQueueEnd = 0; unsigned short keyQueueStart = 0; unsigned short keyCount = 0; bool ReadKey(uint8_t* key){ if(keyCount <= 0) return false; *key = keyQueue[keyQueueStart]; keyQueueStart++; if(keyQueueStart >= KEY_QUEUE_SIZE) { keyQueueStart = 0; } keyCount--; return true; } class KeyboardDevice : public Device{ public: DirectoryEntry dirent; KeyboardDevice(char* name) : Device(name, DeviceTypeLegacyHID){ flags = FS_NODE_CHARDEVICE; strcpy(dirent.name, name); dirent.flags = flags; dirent.node = this; SetDeviceName("PS/2 Keyboard Device"); } ssize_t Read(size_t offset, size_t size, uint8_t *buffer){ if(size > keyCount) size = keyCount; if(!size) return 0; unsigned short i = 0; for(; i < size; i++){ if(!ReadKey(buffer++)) // Insert key and increment break; } return i; } }; KeyboardDevice kbDev("keyboard0"); // Interrupt handler void Handler(void*, RegisterContext* r) { // Read from the keyboard's data buffer uint8_t key = inportb(0x60); if(keyCount >= KEY_QUEUE_SIZE) return; // Drop key // Add key to queue keyQueue[keyQueueEnd] = key; keyQueueEnd++; if(keyQueueEnd >= KEY_QUEUE_SIZE) { keyQueueEnd = 0; } keyCount++; } // Register interrupt handler void Install() { IDT::RegisterInterruptHandler(IRQ0 + 1, Handler); APIC::IO::MapLegacyIRQ(1); outportb(0xF0, 1); // Set scan code 1 } }
1,971
674
/*! @file Defines `boost::hana::detail::variadic::foldr1`. @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_DETAIL_VARIADIC_FOLDR1_HPP #define BOOST_HANA_DETAIL_VARIADIC_FOLDR1_HPP #include <boost/hana/core/datatype.hpp> #include <boost/hana/detail/type_fwd.hpp> namespace boost { namespace hana { namespace detail { namespace variadic { template <unsigned int narg> struct foldr1_impl; template <> struct foldr1_impl<1> { template <template <typename ...> class F, typename X1> using apply_t = X1; template <typename F, typename X1> static constexpr auto apply(F, X1 x1) { return x1; } }; template <> struct foldr1_impl<2> { template <template <typename ...> class F, typename X1, typename X2> using apply_t = typename F<X1, X2>::type; template <typename F, typename X1, typename X2> static constexpr auto apply(F f, X1 x1, X2 x2) { return f(x1, x2); } }; template <> struct foldr1_impl<3> { template <template <typename ...> class F, typename X1, typename X2, typename X3> using apply_t = typename F<X1, typename F<X2, X3>::type>::type; template <typename F, typename X1, typename X2, typename X3> static constexpr auto apply(F f, X1 x1, X2 x2, X3 x3) { return f(x1, f(x2, x3)); } }; // Given a number of arguments left to process, returns the number with // which the next call to `foldr1_impl` should be specialized. constexpr unsigned int foldr1_next(unsigned int n) { return n > 4 ? 4 : n; } template <> struct foldr1_impl<4> { template <template <typename ...> class F, typename X1, typename X2, typename X3, typename ...Xs> using apply_t = typename F<X1, typename F<X2, typename F<X3, typename foldr1_impl<foldr1_next(sizeof...(Xs))>:: template apply_t<F, Xs...> >::type>::type>::type; template <typename F, typename X1, typename X2, typename X3, typename ...Xs> static constexpr auto apply(F f, X1 x1, X2 x2, X3 x3, Xs ...xs) { return f(x1, f(x2, f(x3, foldr1_impl<foldr1_next(sizeof...(Xs))>::apply(f, xs...)))); } }; template <typename ...Xs, typename F> constexpr auto foldr1_helper(F f, ...) { return foldr1_impl<foldr1_next(sizeof...(Xs))>::apply(f, type<Xs>...); } template <typename ...Xs, typename F> constexpr auto foldr1_helper(F, Metafunction*) { return type< typename foldr1_impl<foldr1_next(sizeof...(Xs))>:: template apply_t<F::template apply, Xs...> >; } template <typename ...Xs, typename F> constexpr auto foldr1(F f) { return foldr1_helper<Xs...>(f, (datatype_t<F>*)0); } template <typename F, typename ...Xs> constexpr auto foldr1(F f, Xs ...xs) { return foldr1_impl<foldr1_next(sizeof...(Xs))>::apply(f, xs...); } #if 0 template <typename F, typename X0> constexpr auto foldr1_impl(F, X0 x0) { return x0; } template <typename F, typename X0, typename X1> constexpr auto foldr1_impl(F f, X0 x0, X1 x1) { return f(x0, x1); } template <typename F, typename X0, typename X1, typename X2> constexpr auto foldr1_impl(F f, X0 x0, X1 x1, X2 x2) { return f(x0, f(x1, x2)); } template <typename F, typename X0, typename X1, typename X2, typename X3> constexpr auto foldr1_impl(F f, X0 x0, X1 x1, X2 x2, X3 x3) { return f(x0, f(x1, f(x2, x3))); } template <typename F, typename X0, typename X1, typename X2, typename X3, typename ...Xs> constexpr auto foldr1_impl(F f, X0 x0, X1 x1, X2 x2, X3 x3, Xs ...xs) { return f(x0, f(x1, f(x2, f(x3, foldr1_impl(f, xs...))))); } BOOST_HANA_CONSTEXPR_LAMBDA auto foldr1 = [](auto f, auto x, auto ...xs) { return foldr1_impl(f, x, xs...); }; #endif }}}} // end namespace boost::hana::detail::variadic #endif // !BOOST_HANA_DETAIL_VARIADIC_FOLDR1_HPP
4,136
1,590
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include "atlas/mesh/actions/ExtendNodesGlobal.h" #include "atlas/array.h" #include "atlas/field/Field.h" #include "atlas/grid/Grid.h" #include "atlas/grid/Iterator.h" #include "atlas/mesh/Mesh.h" #include "atlas/mesh/Nodes.h" #include "atlas/runtime/Exception.h" #include "atlas/util/CoordinateEnums.h" #include "atlas/util/Earth.h" namespace atlas { namespace mesh { namespace actions { ExtendNodesGlobal::ExtendNodesGlobal(const std::string& gridname): gridname_(gridname) {} void ExtendNodesGlobal::operator()(const Grid& grid, Mesh& mesh) const { if (grid.domain().global()) { return; // don't add virtual points to global domains } Grid O16("O16"); // virtual points std::vector<PointXY> extended_pts; extended_pts.reserve(grid.size()); // loop over the point and keep the ones that *don't* fall in the domain for (const PointLonLat& lonlat : O16.lonlat()) { PointXY xy = grid.projection().xy(lonlat); if (not grid.domain().contains(xy)) { extended_pts.push_back(xy); } } mesh::Nodes& nodes = mesh.nodes(); const idx_t nb_real_pts = nodes.size(); const idx_t nb_extension_pts = extended_pts.size(); idx_t new_size = nodes.size() + extended_pts.size(); nodes.resize(new_size); // resizes the fields const idx_t nb_total_pts = nodes.size(); ATLAS_ASSERT(nb_total_pts == nb_real_pts + nb_extension_pts); nodes.metadata().set<idx_t>("NbRealPts", nb_real_pts); nodes.metadata().set<idx_t>("NbVirtualPts", nb_extension_pts); array::ArrayView<double, 2> xyz = array::make_view<double, 2>(nodes.field("xyz")); array::ArrayView<double, 2> xy = array::make_view<double, 2>(nodes.xy()); array::ArrayView<double, 2> lonlat = array::make_view<double, 2>(nodes.lonlat()); array::ArrayView<gidx_t, 1> gidx = array::make_view<gidx_t, 1>(nodes.global_index()); for (idx_t i = 0; i < nb_extension_pts; ++i) { const idx_t n = nb_real_pts + i; const PointLonLat pLL = grid.projection().lonlat(extended_pts[i]); PointXYZ pXYZ; util::Earth::convertSphericalToCartesian(pLL, pXYZ); xyz(n, XX) = pXYZ.x(); xyz(n, YY) = pXYZ.y(); xyz(n, ZZ) = pXYZ.z(); xy(n, XX) = extended_pts[i].x(); xy(n, YY) = extended_pts[i].y(); lonlat(n, LON) = pLL.lon(); lonlat(n, LAT) = pLL.lat(); gidx(n) = n + 1; } } } // namespace actions } // namespace mesh } // namespace atlas
2,945
1,082
#include "tensorflow/cc/examples/mcts.h" #include <boost/coroutine2/coroutine.hpp> #include <boost/fiber/all.hpp> #include <chrono> #include <list> #include <thread> #include "tensorflow/cc/saved_model/loader.h" #include "tensorflow/cc/saved_model/tag_constants.h" #include "tensorflow/core/platform/test.h" namespace snake { TEST(Mcts, SinglePredictionTest) { Snake p1({ Point{0, 3}, Point{0, 2}, Point{0, 1}, Point{0, 0}, }); Snake p2({ Point{1, 5}, Point{1, 4}, Point{1, 3}, Point{1, 2}, }); SnakeBoard16 state(p1, p2, [](const SnakeBoard16&) { return Point{15, 15}; }); SnakeMctsAdapter adapter(state); adapter.print(); Mcts mcts(random_rollout); auto d = mcts.Search(adapter); EXPECT_EQ(d, Direction::DOWN); } TEST(Mcts, MctsTest) { Snake p1({ Point{0, 3}, Point{0, 2}, Point{0, 1}, Point{0, 0}, }); Snake p2({ Point{1, 5}, Point{1, 4}, Point{1, 3}, Point{1, 2}, }); SnakeBoard16 state(p1, p2, [](const SnakeBoard16&) { return Point{15, 15}; }); state.print(); SnakeMctsAdapter adapter(state); Mcts mcts(random_rollout); auto d = mcts.Search(adapter); EXPECT_EQ(d, Direction::DOWN); adapter.execute(d); d = mcts.Search(adapter); EXPECT_EQ(d, Direction::LEFT); adapter.execute(d); // adapter.print(); } TEST(Mcts, MctsMultipleMoves) { SnakeBoard16 state; SnakeMctsAdapter adapter(state); while (!adapter.is_terminal()) { Mcts mcts(random_rollout); auto d = mcts.Search(adapter); adapter.execute(d); d = mcts.Search(adapter); adapter.execute(d); adapter.print(); } adapter.print(); } TEST(Mcts, TestMctsStrategy) { RunGame(GreedyStrategy, Mcts::Strategy); } TEST(Mcts, SavedModel) { using namespace tensorflow; // Load SavedModelBundle model_bundle; SessionOptions session_options = SessionOptions(); // (*session_options.config.mutable_device_count())["GPU"] = 0; session_options.config.set_log_device_placement(true); RunOptions run_options = RunOptions(); TF_CHECK_OK(LoadSavedModel(session_options, run_options, "/home/geli/tmp/saved_model", {kSavedModelTagServe}, &model_bundle)); // LOG(ERROR) << model_bundle.meta_graph_def.DebugString(); for (const auto& s : model_bundle.GetSignatures()) { LOG(ERROR) << s.first; LOG(ERROR) << s.second.DebugString(); } Tensor input(DT_FLOAT, TensorShape{{4096, 16, 16, 3}}); for (int i = 0; i < input.NumElements(); ++i) { input.flat<float>()(i) = 0; } std::vector<Tensor> output; TF_CHECK_OK(model_bundle.session->Run({{"serving_default_board:0", input}}, {"StatefulPartitionedCall:0"}, {}, &output)); ASSERT_EQ(output.size(), 1); auto begin = std::chrono::steady_clock::now(); for (int i = 0; i < 100; ++i) { std::vector<Tensor> output; TF_CHECK_OK(model_bundle.session->Run({{"serving_default_board:0", input}}, {"StatefulPartitionedCall:0"}, {}, &output)); ASSERT_EQ(output.size(), 1); LOG(ERROR) << output[0].shape().DebugString(); LOG(ERROR) << output[0].DebugString(8); } std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::steady_clock::now() - begin) .count() << "[µs]" << std::endl; // model_bundle.session->Run() // bundle.session->Run({}, {"filename_tensor:0"}, {}, &path_outputs)); // Tensor // Status runStatus = model_bundle.GetSession()->Run( // {{"serving_default_input_tensor:0", input_tensor}}, outputLayer, {}, // &outputs); // Inference // outputLayer = {"StatefulPartitionedCall:0", "StatefulPartitionedCall:4", // "StatefulPartitionedCall:1", "StatefulPartitionedCall:5", // "StatefulPartitionedCall:3"}; // Status runStatus = model_bundle.GetSession()->Run( // {{"serving_default_input_tensor:0", input_tensor}}, outputLayer, {}, // &outputs); } TEST(Coroutine, Test) { boost::coroutines2::coroutine<int>::pull_type source( [](boost::coroutines2::coroutine<int>::push_type& sink) { int first = 1, second = 1; sink(first); sink(second); for (int i = 0; i < 8; ++i) { int third = first + second; first = second; second = third; sink(third); } }); for (auto i : source) { std::cout << i << " "; } std::cout << "\nDone" << std::endl; } template <typename INPUT, typename OUTPUT> struct Batching { struct Work { INPUT input; boost::fibers::promise<OUTPUT> r; }; using ChannelType = boost::fibers::unbuffered_channel<Work>; struct Closer { void operator()(ChannelType* c) { c->close(); } }; using Base = std::unique_ptr<ChannelType, Closer>; struct Foo : public Base { using Base::Base; OUTPUT BatchProcess(INPUT input) const { Work w; w.input = input; auto f = w.r.get_future(); Base::get()->push(std::move(w)); return f.get(); } }; Foo new_channel() { channels_.emplace_back(); return Foo{&channels_.back(), Closer()}; } typename boost::coroutines2::coroutine<Work>::pull_type get_batch() { return typename boost::coroutines2::coroutine<Work>::pull_type( [this](typename boost::coroutines2::coroutine<Work>::push_type& sink) { for (auto it = channels_.begin(); it != channels_.end();) { Work w; if (it->pop(w) != boost::fibers::channel_op_status::success) { it = channels_.erase(it); continue; } else { ++it; } sink(std::move(w)); } }); } private: std::list<ChannelType> channels_; }; TEST(Fiber, Test) { Batching<int, int> c; auto batch_compute = [&c]() { while (true) { auto batch = c.get_batch(); std::vector<boost::fibers::promise<int>> results; int result = 0; int batch_size = 0; for (auto&& w : batch) { ++batch_size; result += w.input; results.push_back(std::move(w.r)); } if (batch_size == 0) { break; } for (auto& r : results) { r.set_value(result); } } }; auto leaf_comp = [](const Batching<int, int>::Foo& f, int i) { for (int j = 0; j < i; ++j) { auto r = f.BatchProcess(j); std::cout << i << ": f(" << j << ")=" << r << std::endl; } }; boost::fibers::fiber l1{[leaf_comp, f = std::move(c.new_channel()), i = 3]() { leaf_comp(f, i); }}; boost::fibers::fiber l2{[leaf_comp, f = std::move(c.new_channel()), i = 4]() { leaf_comp(f, i); }}; boost::fibers::fiber l3{[leaf_comp, f = std::move(c.new_channel()), i = 5]() { leaf_comp(f, i); }}; boost::fibers::fiber bc{batch_compute}; l1.join(); std::cout << "l1 joined" << std::endl; l2.join(); std::cout << "l2 joined" << std::endl; l3.join(); std::cout << "l3 joined" << std::endl; bc.join(); } } // namespace snake
7,251
2,668
/* * Copyright (c) 2020 Razeware LLC * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * This project and source code may use libraries or frameworks that are * released under various Open-Source licenses. Use of those libraries and * frameworks are governed by their own individual licenses. * * 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 "./include/user_processing_jni.h" class UserInfoHandler { private: std::string _usernameString; char *_passwordChar; //Use char * so we can secure wipe memory public: UserInfoHandler(); ~UserInfoHandler(); } void UserInfoHandler::UserInfoHandler() { _passwordChar = ""; _usernameString = "Anonymous"; } void UserInfoHandler::~UserInfoHandler() { const int c = 0; size_t n = strlen(_passwordChar) volatile char *p = (volatile char *)_passwordChar; //tell compiler the value can change while (n--) { *p++ = (char)c; } } static UserInfoHandler s_userInfoHandler; #ifdef __cplusplus extern "C" { #endif JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env = nullptr; jint result = -1; if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { return result; } assert(env != nullptr); result = JNI_VERSION_1_6; return result; } JNIEXPORT void JNICALL Java_com_raywenderlich_android_petsave_PetSaveApplication_doRegisterProcessing (JNIEnv *env, jobject obj) { if (s_userInfoHandler) { s_userInfoHandler->setupUser(); } } #ifdef __cplusplus } #endif
3,011
969
#include <cassert> #include <cstdio> #include <fstream> #include <libff/algebra/curves/mnt753/mnt4753/mnt4753_pp.hpp> #include <libff/algebra/curves/mnt753/mnt6753/mnt6753_pp.hpp> #include <libff/algebra/scalar_multiplication/multiexp.hpp> #include <libff/common/profiling.hpp> #include <libff/common/rng.hpp> #include <libff/common/utils.hpp> #include <libsnark/knowledge_commitment/kc_multiexp.hpp> #include <libsnark/knowledge_commitment/knowledge_commitment.hpp> #include <libsnark/reductions/r1cs_to_qap/r1cs_to_qap.hpp> #include <libsnark/serialization.hpp> #include <omp.h> #include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp> #include <libfqfft/evaluation_domain/domains/basic_radix2_domain.hpp> #include "prover_reference_include/prover_reference_functions.hpp" using namespace libff; using namespace libsnark; const multi_exp_method method = multi_exp_method_BDLO12; template <typename G, typename Fr> G multiexp(typename std::vector<Fr>::const_iterator scalar_start, typename std::vector<G>::const_iterator g_start, size_t length) { #ifdef MULTICORE const size_t chunks = omp_get_max_threads(); // to override, set OMP_NUM_THREADS env var or call // omp_set_num_threads() #else const size_t chunks = 1; #endif return libff::multi_exp_with_mixed_addition<G, Fr, method>( g_start, g_start + length, scalar_start, scalar_start + length, chunks); } class mnt4753_libsnark::groth16_input { public: std::shared_ptr<std::vector<Fr<mnt4753_pp>>> w; std::shared_ptr<std::vector<Fr<mnt4753_pp>>> ca, cb, cc; Fr<mnt4753_pp> r; groth16_input(const char *path, size_t d, size_t m) { w = std::make_shared<std::vector<libff::Fr<mnt4753_pp>>>( std::vector<libff::Fr<mnt4753_pp>>()); ca = std::make_shared<std::vector<libff::Fr<mnt4753_pp>>>( std::vector<libff::Fr<mnt4753_pp>>()); cb = std::make_shared<std::vector<libff::Fr<mnt4753_pp>>>( std::vector<libff::Fr<mnt4753_pp>>()); cc = std::make_shared<std::vector<libff::Fr<mnt4753_pp>>>( std::vector<libff::Fr<mnt4753_pp>>()); FILE *inputs = fopen(path, "r"); for (size_t i = 0; i < m + 1; ++i) { w->emplace_back(read_fr<mnt4753_pp>(inputs)); } for (size_t i = 0; i < d + 1; ++i) { ca->emplace_back(read_fr<mnt4753_pp>(inputs)); } for (size_t i = 0; i < d + 1; ++i) { cb->emplace_back(read_fr<mnt4753_pp>(inputs)); } for (size_t i = 0; i < d + 1; ++i) { cc->emplace_back(read_fr<mnt4753_pp>(inputs)); } r = read_fr<mnt4753_pp>(inputs); fclose(inputs); } }; class mnt4753_libsnark::groth16_params { public: size_t d; size_t m; std::shared_ptr<std::vector<libff::G1<mnt4753_pp>>> A, B1, L, H; std::shared_ptr<std::vector<libff::G2<mnt4753_pp>>> B2; groth16_params(const char *path) { FILE *params = fopen(path, "r"); d = read_size_t(params); m = read_size_t(params); A = std::make_shared<std::vector<libff::G1<mnt4753_pp>>>( std::vector<libff::G1<mnt4753_pp>>()); B1 = std::make_shared<std::vector<libff::G1<mnt4753_pp>>>( std::vector<libff::G1<mnt4753_pp>>()); L = std::make_shared<std::vector<libff::G1<mnt4753_pp>>>( std::vector<libff::G1<mnt4753_pp>>()); H = std::make_shared<std::vector<libff::G1<mnt4753_pp>>>( std::vector<libff::G1<mnt4753_pp>>()); B2 = std::make_shared<std::vector<libff::G2<mnt4753_pp>>>( std::vector<libff::G2<mnt4753_pp>>()); for (size_t i = 0; i <= m; ++i) { A->emplace_back(read_g1<mnt4753_pp>(params)); } for (size_t i = 0; i <= m; ++i) { B1->emplace_back(read_g1<mnt4753_pp>(params)); } for (size_t i = 0; i <= m; ++i) { B2->emplace_back(read_g2<mnt4753_pp>(params)); } for (size_t i = 0; i < m - 1; ++i) { L->emplace_back(read_g1<mnt4753_pp>(params)); } for (size_t i = 0; i < d; ++i) { H->emplace_back(read_g1<mnt4753_pp>(params)); } fclose(params); } }; struct mnt4753_libsnark::evaluation_domain { std::shared_ptr<libfqfft::evaluation_domain<Fr<mnt4753_pp>>> data; }; struct mnt4753_libsnark::field { Fr<mnt4753_pp> data; }; struct mnt4753_libsnark::G1 { libff::G1<mnt4753_pp> data; }; struct mnt4753_libsnark::G2 { libff::G2<mnt4753_pp> data; }; struct mnt4753_libsnark::vector_Fr { std::shared_ptr<std::vector<Fr<mnt4753_pp>>> data; size_t offset; }; struct mnt4753_libsnark::vector_G1 { std::shared_ptr<std::vector<libff::G1<mnt4753_pp>>> data; }; struct mnt4753_libsnark::vector_G2 { std::shared_ptr<std::vector<libff::G2<mnt4753_pp>>> data; }; void mnt4753_libsnark::init_public_params() { mnt4753_pp::init_public_params(); } void mnt4753_libsnark::print_G1(mnt4753_libsnark::G1 *a) { a->data.print(); } void mnt4753_libsnark::print_G2(mnt4753_libsnark::G2 *a) { a->data.print(); } mnt4753_libsnark::evaluation_domain * mnt4753_libsnark::get_evaluation_domain(size_t d) { return new evaluation_domain{ .data = libfqfft::get_evaluation_domain<Fr<mnt4753_pp>>(d)}; } mnt4753_libsnark::G1 *mnt4753_libsnark::G1_add(mnt4753_libsnark::G1 *a, mnt4753_libsnark::G1 *b) { return new mnt4753_libsnark::G1{.data = a->data + b->data}; } mnt4753_libsnark::G1 *mnt4753_libsnark::G1_scale(field *a, G1 *b) { return new G1{.data = a->data * b->data}; } void mnt4753_libsnark::vector_Fr_muleq(mnt4753_libsnark::vector_Fr *a, mnt4753_libsnark::vector_Fr *b, size_t size) { size_t a_off = a->offset, b_off = b->offset; #ifdef MULTICORE #pragma omp parallel for #endif for (size_t i = 0; i < size; i++) { a->data->at(i + a_off) = a->data->at(i + a_off) * b->data->at(i + b_off); } } void mnt4753_libsnark::vector_Fr_subeq(mnt4753_libsnark::vector_Fr *a, mnt4753_libsnark::vector_Fr *b, size_t size) { size_t a_off = a->offset, b_off = b->offset; #ifdef MULTICORE #pragma omp parallel for #endif for (size_t i = 0; i < size; i++) { a->data->at(i + a_off) = a->data->at(i + a_off) - b->data->at(i + b_off); } } mnt4753_libsnark::vector_Fr * mnt4753_libsnark::vector_Fr_offset(mnt4753_libsnark::vector_Fr *a, size_t offset) { return new vector_Fr{.data = a->data, .offset = offset}; } void mnt4753_libsnark::vector_Fr_copy_into(mnt4753_libsnark::vector_Fr *src, mnt4753_libsnark::vector_Fr *dst, size_t length) { std::cerr << "length is " << length << ", offset is " << src->offset << ", size of src is " << src->data->size() << ", size of dst is " << dst->data->size() << std::endl; #ifdef MULTICORE #pragma omp parallel for #endif for (size_t i = 0; i < length; i++) { // std::cerr << "doing iteration " << i << std::endl; dst->data->at(i) = src->data->at(i); } // std::copy(src->data->begin(), src->data->end(), dst->data->begin() ); } mnt4753_libsnark::vector_Fr *mnt4753_libsnark::vector_Fr_zeros(size_t length) { std::vector<Fr<mnt4753_pp>> data(length, Fr<mnt4753_pp>::zero()); return new mnt4753_libsnark::vector_Fr{ .data = std::make_shared<std::vector<Fr<mnt4753_pp>>>(data)}; } void mnt4753_libsnark::domain_iFFT(mnt4753_libsnark::evaluation_domain *domain, mnt4753_libsnark::vector_Fr *a) { std::vector<Fr<mnt4753_pp>> &data = *a->data; domain->data->iFFT(data); } void mnt4753_libsnark::domain_cosetFFT( mnt4753_libsnark::evaluation_domain *domain, mnt4753_libsnark::vector_Fr *a) { domain->data->cosetFFT(*a->data, Fr<mnt4753_pp>::multiplicative_generator); } void mnt4753_libsnark::domain_icosetFFT( mnt4753_libsnark::evaluation_domain *domain, mnt4753_libsnark::vector_Fr *a) { domain->data->icosetFFT(*a->data, Fr<mnt4753_pp>::multiplicative_generator); } void mnt4753_libsnark::domain_divide_by_Z_on_coset( mnt4753_libsnark::evaluation_domain *domain, mnt4753_libsnark::vector_Fr *a) { domain->data->divide_by_Z_on_coset(*a->data); } size_t mnt4753_libsnark::domain_get_m(mnt4753_libsnark::evaluation_domain *domain) { return domain->data->m; } mnt4753_libsnark::G1 * mnt4753_libsnark::multiexp_G1(mnt4753_libsnark::vector_Fr *scalar_start, mnt4753_libsnark::vector_G1 *g_start, size_t length) { return new mnt4753_libsnark::G1{ multiexp<libff::G1<mnt4753_pp>, Fr<mnt4753_pp>>( scalar_start->data->begin() + scalar_start->offset, g_start->data->begin(), length)}; } mnt4753_libsnark::G2 * mnt4753_libsnark::multiexp_G2(mnt4753_libsnark::vector_Fr *scalar_start, mnt4753_libsnark::vector_G2 *g_start, size_t length) { return new mnt4753_libsnark::G2{ multiexp<libff::G2<mnt4753_pp>, Fr<mnt4753_pp>>( scalar_start->data->begin() + scalar_start->offset, g_start->data->begin(), length)}; } mnt4753_libsnark::groth16_input * mnt4753_libsnark::read_input(const char *path, mnt4753_libsnark::groth16_params *params) { return new mnt4753_libsnark::groth16_input(path, params->d, params->m); } mnt4753_libsnark::vector_Fr * mnt4753_libsnark::input_w(mnt4753_libsnark::groth16_input *input) { return new mnt4753_libsnark::vector_Fr{.data = input->w, .offset = 0}; } mnt4753_libsnark::vector_Fr * mnt4753_libsnark::input_ca(mnt4753_libsnark::groth16_input *input) { return new mnt4753_libsnark::vector_Fr{.data = input->ca, .offset = 0}; } mnt4753_libsnark::vector_Fr *mnt4753_libsnark::input_cb(groth16_input *input) { return new mnt4753_libsnark::vector_Fr{.data = input->cb, .offset = 0}; } mnt4753_libsnark::vector_Fr *mnt4753_libsnark::input_cc(groth16_input *input) { return new vector_Fr{.data = input->cc, .offset = 0}; } mnt4753_libsnark::field *mnt4753_libsnark::input_r(groth16_input *input) { return new mnt4753_libsnark::field{.data = input->r}; } mnt4753_libsnark::groth16_params * mnt4753_libsnark::read_params(const char *path) { return new mnt4753_libsnark::groth16_params(path); } size_t mnt4753_libsnark::params_d(mnt4753_libsnark::groth16_params *params) { return params->d; } size_t mnt4753_libsnark::params_m(mnt4753_libsnark::groth16_params *params) { return params->m; } mnt4753_libsnark::vector_G1 * mnt4753_libsnark::params_A(mnt4753_libsnark::groth16_params *params) { return new mnt4753_libsnark::vector_G1{.data = params->A}; } mnt4753_libsnark::vector_G1 * mnt4753_libsnark::params_B1(mnt4753_libsnark::groth16_params *params) { return new mnt4753_libsnark::vector_G1{.data = params->B1}; } mnt4753_libsnark::vector_G1 * mnt4753_libsnark::params_L(mnt4753_libsnark::groth16_params *params) { return new mnt4753_libsnark::vector_G1{.data = params->L}; } mnt4753_libsnark::vector_G1 * mnt4753_libsnark::params_H(mnt4753_libsnark::groth16_params *params) { return new mnt4753_libsnark::vector_G1{.data = params->H}; } mnt4753_libsnark::vector_G2 * mnt4753_libsnark::params_B2(mnt4753_libsnark::groth16_params *params) { return new mnt4753_libsnark::vector_G2{.data = params->B2}; } void mnt4753_libsnark::delete_G1(mnt4753_libsnark::G1 *a) { delete a; } void mnt4753_libsnark::delete_G2(mnt4753_libsnark::G1 *a) { delete a; } void mnt4753_libsnark::delete_vector_Fr(mnt4753_libsnark::vector_Fr *a) { delete a; } void mnt4753_libsnark::delete_vector_G1(mnt4753_libsnark::vector_G1 *a) { delete a; } void mnt4753_libsnark::delete_vector_G2(mnt4753_libsnark::vector_G2 *a) { delete a; } void mnt4753_libsnark::delete_groth16_input( mnt4753_libsnark::groth16_input *a) { delete a; } void mnt4753_libsnark::delete_groth16_params( mnt4753_libsnark::groth16_params *a) { delete a; } void mnt4753_libsnark::delete_evaluation_domain( mnt4753_libsnark::evaluation_domain *a) { delete a; } void mnt4753_libsnark::groth16_output_write(mnt4753_libsnark::G1 *A, mnt4753_libsnark::G2 *B, mnt4753_libsnark::G1 *C, const char *output_path) { FILE *out = fopen(output_path, "w"); write_g1<mnt4753_pp>(out, A->data); write_g2<mnt4753_pp>(out, B->data); write_g1<mnt4753_pp>(out, C->data); fclose(out); } class mnt6753_libsnark::groth16_input { public: std::shared_ptr<std::vector<Fr<mnt6753_pp>>> w; std::shared_ptr<std::vector<Fr<mnt6753_pp>>> ca, cb, cc; Fr<mnt6753_pp> r; groth16_input(const char *path, size_t d, size_t m) { w = std::make_shared<std::vector<libff::Fr<mnt6753_pp>>>( std::vector<libff::Fr<mnt6753_pp>>()); ca = std::make_shared<std::vector<libff::Fr<mnt6753_pp>>>( std::vector<libff::Fr<mnt6753_pp>>()); cb = std::make_shared<std::vector<libff::Fr<mnt6753_pp>>>( std::vector<libff::Fr<mnt6753_pp>>()); cc = std::make_shared<std::vector<libff::Fr<mnt6753_pp>>>( std::vector<libff::Fr<mnt6753_pp>>()); FILE *inputs = fopen(path, "r"); for (size_t i = 0; i < m + 1; ++i) { w->emplace_back(read_fr<mnt6753_pp>(inputs)); } for (size_t i = 0; i < d + 1; ++i) { ca->emplace_back(read_fr<mnt6753_pp>(inputs)); } for (size_t i = 0; i < d + 1; ++i) { cb->emplace_back(read_fr<mnt6753_pp>(inputs)); } for (size_t i = 0; i < d + 1; ++i) { cc->emplace_back(read_fr<mnt6753_pp>(inputs)); } r = read_fr<mnt6753_pp>(inputs); fclose(inputs); } }; class mnt6753_libsnark::groth16_params { public: size_t d; size_t m; std::shared_ptr<std::vector<libff::G1<mnt6753_pp>>> A, B1, L, H; std::shared_ptr<std::vector<libff::G2<mnt6753_pp>>> B2; groth16_params(const char *path) { FILE *params = fopen(path, "r"); d = read_size_t(params); m = read_size_t(params); A = std::make_shared<std::vector<libff::G1<mnt6753_pp>>>( std::vector<libff::G1<mnt6753_pp>>()); B1 = std::make_shared<std::vector<libff::G1<mnt6753_pp>>>( std::vector<libff::G1<mnt6753_pp>>()); L = std::make_shared<std::vector<libff::G1<mnt6753_pp>>>( std::vector<libff::G1<mnt6753_pp>>()); H = std::make_shared<std::vector<libff::G1<mnt6753_pp>>>( std::vector<libff::G1<mnt6753_pp>>()); B2 = std::make_shared<std::vector<libff::G2<mnt6753_pp>>>( std::vector<libff::G2<mnt6753_pp>>()); for (size_t i = 0; i <= m; ++i) { A->emplace_back(read_g1<mnt6753_pp>(params)); } for (size_t i = 0; i <= m; ++i) { B1->emplace_back(read_g1<mnt6753_pp>(params)); } for (size_t i = 0; i <= m; ++i) { B2->emplace_back(read_g2<mnt6753_pp>(params)); } for (size_t i = 0; i < m - 1; ++i) { L->emplace_back(read_g1<mnt6753_pp>(params)); } for (size_t i = 0; i < d; ++i) { H->emplace_back(read_g1<mnt6753_pp>(params)); } fclose(params); } }; struct mnt6753_libsnark::evaluation_domain { std::shared_ptr<libfqfft::evaluation_domain<Fr<mnt6753_pp>>> data; }; struct mnt6753_libsnark::field { Fr<mnt6753_pp> data; }; struct mnt6753_libsnark::G1 { libff::G1<mnt6753_pp> data; }; struct mnt6753_libsnark::G2 { libff::G2<mnt6753_pp> data; }; struct mnt6753_libsnark::vector_Fr { std::shared_ptr<std::vector<Fr<mnt6753_pp>>> data; size_t offset; }; struct mnt6753_libsnark::vector_G1 { std::shared_ptr<std::vector<libff::G1<mnt6753_pp>>> data; }; struct mnt6753_libsnark::vector_G2 { std::shared_ptr<std::vector<libff::G2<mnt6753_pp>>> data; }; void mnt6753_libsnark::init_public_params() { mnt6753_pp::init_public_params(); } void mnt6753_libsnark::print_G1(mnt6753_libsnark::G1 *a) { a->data.print(); } void mnt6753_libsnark::print_G2(mnt6753_libsnark::G2 *a) { a->data.print(); } mnt6753_libsnark::evaluation_domain * mnt6753_libsnark::get_evaluation_domain(size_t d) { return new evaluation_domain{ .data = libfqfft::get_evaluation_domain<Fr<mnt6753_pp>>(d)}; } mnt6753_libsnark::G1 *mnt6753_libsnark::G1_add(mnt6753_libsnark::G1 *a, mnt6753_libsnark::G1 *b) { return new mnt6753_libsnark::G1{.data = a->data + b->data}; } mnt6753_libsnark::G1 *mnt6753_libsnark::G1_scale(field *a, G1 *b) { return new G1{.data = a->data * b->data}; } void mnt6753_libsnark::vector_Fr_muleq(mnt6753_libsnark::vector_Fr *a, mnt6753_libsnark::vector_Fr *b, size_t size) { size_t a_off = a->offset, b_off = b->offset; #ifdef MULTICORE #pragma omp parallel for #endif for (size_t i = 0; i < size; i++) { a->data->at(i + a_off) = a->data->at(i + a_off) * b->data->at(i + b_off); } } void mnt6753_libsnark::vector_Fr_subeq(mnt6753_libsnark::vector_Fr *a, mnt6753_libsnark::vector_Fr *b, size_t size) { size_t a_off = a->offset, b_off = b->offset; #ifdef MULTICORE #pragma omp parallel for #endif for (size_t i = 0; i < size; i++) { a->data->at(i + a_off) = a->data->at(i + a_off) - b->data->at(i + b_off); } } mnt6753_libsnark::vector_Fr * mnt6753_libsnark::vector_Fr_offset(mnt6753_libsnark::vector_Fr *a, size_t offset) { return new vector_Fr{.data = a->data, .offset = offset}; } void mnt6753_libsnark::vector_Fr_copy_into(mnt6753_libsnark::vector_Fr *src, mnt6753_libsnark::vector_Fr *dst, size_t length) { std::copy(src->data->begin() + src->offset, src->data->begin() + src->offset + length, dst->data->begin()); } mnt6753_libsnark::vector_Fr *mnt6753_libsnark::vector_Fr_zeros(size_t length) { return new mnt6753_libsnark::vector_Fr{ .data = std::make_shared<std::vector<Fr<mnt6753_pp>>>( length, Fr<mnt6753_pp>::zero())}; } void mnt6753_libsnark::domain_iFFT(mnt6753_libsnark::evaluation_domain *domain, mnt6753_libsnark::vector_Fr *a) { std::vector<Fr<mnt6753_pp>> &data = *a->data; domain->data->iFFT(data); } void mnt6753_libsnark::domain_cosetFFT( mnt6753_libsnark::evaluation_domain *domain, mnt6753_libsnark::vector_Fr *a) { domain->data->cosetFFT(*a->data, Fr<mnt6753_pp>::multiplicative_generator); } void mnt6753_libsnark::domain_icosetFFT( mnt6753_libsnark::evaluation_domain *domain, mnt6753_libsnark::vector_Fr *a) { domain->data->icosetFFT(*a->data, Fr<mnt6753_pp>::multiplicative_generator); } void mnt6753_libsnark::domain_divide_by_Z_on_coset( mnt6753_libsnark::evaluation_domain *domain, mnt6753_libsnark::vector_Fr *a) { domain->data->divide_by_Z_on_coset(*a->data); } size_t mnt6753_libsnark::domain_get_m(mnt6753_libsnark::evaluation_domain *domain) { return domain->data->m; } mnt6753_libsnark::G1 * mnt6753_libsnark::multiexp_G1(mnt6753_libsnark::vector_Fr *scalar_start, mnt6753_libsnark::vector_G1 *g_start, size_t length) { return new mnt6753_libsnark::G1{ multiexp<libff::G1<mnt6753_pp>, Fr<mnt6753_pp>>( scalar_start->data->begin() + scalar_start->offset, g_start->data->begin(), length)}; } mnt6753_libsnark::G2 * mnt6753_libsnark::multiexp_G2(mnt6753_libsnark::vector_Fr *scalar_start, mnt6753_libsnark::vector_G2 *g_start, size_t length) { return new mnt6753_libsnark::G2{ multiexp<libff::G2<mnt6753_pp>, Fr<mnt6753_pp>>( scalar_start->data->begin() + scalar_start->offset, g_start->data->begin(), length)}; } mnt6753_libsnark::groth16_input * mnt6753_libsnark::read_input(const char *path, mnt6753_libsnark::groth16_params *params) { return new mnt6753_libsnark::groth16_input(path, params->d, params->m); } mnt6753_libsnark::vector_Fr * mnt6753_libsnark::input_w(mnt6753_libsnark::groth16_input *input) { return new mnt6753_libsnark::vector_Fr{.data = input->w, .offset = 0}; } mnt6753_libsnark::vector_Fr * mnt6753_libsnark::input_ca(mnt6753_libsnark::groth16_input *input) { return new mnt6753_libsnark::vector_Fr{.data = input->ca, .offset = 0}; } mnt6753_libsnark::vector_Fr *mnt6753_libsnark::input_cb(groth16_input *input) { return new mnt6753_libsnark::vector_Fr{.data = input->cb, .offset = 0}; } mnt6753_libsnark::vector_Fr *mnt6753_libsnark::input_cc(groth16_input *input) { return new vector_Fr{.data = input->cc, .offset = 0}; } mnt6753_libsnark::field *mnt6753_libsnark::input_r(groth16_input *input) { return new mnt6753_libsnark::field{.data = input->r}; } mnt6753_libsnark::groth16_params * mnt6753_libsnark::read_params(const char *path) { return new mnt6753_libsnark::groth16_params(path); } size_t mnt6753_libsnark::params_d(mnt6753_libsnark::groth16_params *params) { return params->d; } size_t mnt6753_libsnark::params_m(mnt6753_libsnark::groth16_params *params) { return params->m; } mnt6753_libsnark::vector_G1 * mnt6753_libsnark::params_A(mnt6753_libsnark::groth16_params *params) { return new mnt6753_libsnark::vector_G1{.data = params->A}; } mnt6753_libsnark::vector_G1 * mnt6753_libsnark::params_B1(mnt6753_libsnark::groth16_params *params) { return new mnt6753_libsnark::vector_G1{.data = params->B1}; } mnt6753_libsnark::vector_G1 * mnt6753_libsnark::params_L(mnt6753_libsnark::groth16_params *params) { return new mnt6753_libsnark::vector_G1{.data = params->L}; } mnt6753_libsnark::vector_G1 * mnt6753_libsnark::params_H(mnt6753_libsnark::groth16_params *params) { return new mnt6753_libsnark::vector_G1{.data = params->H}; } mnt6753_libsnark::vector_G2 * mnt6753_libsnark::params_B2(mnt6753_libsnark::groth16_params *params) { return new mnt6753_libsnark::vector_G2{.data = params->B2}; } void mnt6753_libsnark::delete_G1(mnt6753_libsnark::G1 *a) { delete a; } void mnt6753_libsnark::delete_G2(mnt6753_libsnark::G1 *a) { delete a; } void mnt6753_libsnark::delete_vector_Fr(mnt6753_libsnark::vector_Fr *a) { delete a; } void mnt6753_libsnark::delete_vector_G1(mnt6753_libsnark::vector_G1 *a) { delete a; } void mnt6753_libsnark::delete_vector_G2(mnt6753_libsnark::vector_G2 *a) { delete a; } void mnt6753_libsnark::delete_groth16_input( mnt6753_libsnark::groth16_input *a) { delete a; } void mnt6753_libsnark::delete_groth16_params( mnt6753_libsnark::groth16_params *a) { delete a; } void mnt6753_libsnark::delete_evaluation_domain( mnt6753_libsnark::evaluation_domain *a) { delete a; } void mnt6753_libsnark::groth16_output_write(mnt6753_libsnark::G1 *A, mnt6753_libsnark::G2 *B, mnt6753_libsnark::G1 *C, const char *output_path) { FILE *out = fopen(output_path, "w"); write_g1<mnt6753_pp>(out, A->data); write_g2<mnt6753_pp>(out, B->data); write_g1<mnt6753_pp>(out, C->data); fclose(out); }
23,161
10,645
// INTERFACE / DEFINITION #include "orario.h" // ==== Costruttori orario::orario(){ sec = 0; } orario::orario(int o){ if(o<0 || o>23) sec = 0; // Controllo di sanità else sec = o*3600; } orario::orario(int o, int m){ if(o<0 || o>23 || m < 0 || m > 59) sec = 0; // " else sec = o*3600 + m*60; } orario::orario(int o, int m, int s){ if(o<0 || o>23 || m < 0 || m > 59 || s < 0 || s > 59) sec = 0; // "" else sec = o*3600 + m*60 + s; } // ==== Metodi int orario::Ore() const { return sec / 3600; } int orario::Minuti() const { return (sec/60) % 60;} int orario::Secondi() const { return (sec%60);} orario orario::AumentaUnOra() { orario aux; aux.sec = (sec + 3600) % 86400; return aux; } void orario::PrintSec() const{ cout << "Secondi totali: " << sec << endl; } orario orario::OraDiPranzo() { return orario(13,15,00); } // ==== Overloading operatori orario orario::operator+(orario x){ orario aux; aux.sec = (sec + x.sec) % 86400; return aux; } bool orario::operator==(orario x) const { return (sec == x.sec); } ostream& operator<<(ostream& os, const orario &o) { return os << o.Ore() << ':' << o.Minuti() << ':' << o.Secondi(); } // Altrimenti mettevo using std::ostream sul .h; // ==== Campi Dati int orario::UnOra = 3600;
1,271
606
class Solution { public: int XXX(int n) { if (n == 1) { return 1; } if (n == 2){ return 2; } int m1 = 1, m2 = 2; int i = 3; int sum = 0; while (i <= n) { sum = m1 + m2; m1 = m2; m2 = sum; i++; } return sum; } };
405
144
auto HotkeySettings::create() -> void { setIcon(Icon::Device::Keyboard); setText("Hotkeys"); layout.setPadding(5); mappingList.setBatchable(); mappingList.setHeadered(); mappingList.onActivate([&] { if(assignButton.enabled()) assignButton.doActivate(); }); mappingList.onChange([&] { auto batched = mappingList.batched(); assignButton.setEnabled(batched.size() == 1); clearButton.setEnabled(batched.size() >= 1); }); mappingList.onSize([&] { mappingList.resizeColumns(); }); assignButton.setText("Assign").onActivate([&] { assignMapping(); }); clearButton.setText("Clear").onActivate([&] { for(auto item : mappingList.batched()) { inputManager.hotkeys[item.offset()].unbind(); } refreshMappings(); }); } auto HotkeySettings::reloadMappings() -> void { mappingList.reset(); mappingList.append(TableViewColumn().setText("Name")); mappingList.append(TableViewColumn().setText("Mapping").setExpandable()); for(auto& hotkey : inputManager.hotkeys) { mappingList.append(TableViewItem() .append(TableViewCell().setText(hotkey.name).setFont(Font().setBold()).setBackgroundColor({240, 240, 255})) .append(TableViewCell()) ); } refreshMappings(); mappingList.doChange(); } auto HotkeySettings::refreshMappings() -> void { uint index = 0; for(auto& hotkey : inputManager.hotkeys) { mappingList.item(index++).cell(1).setText(hotkey.displayName()); } mappingList.resizeColumns(); } auto HotkeySettings::assignMapping() -> void { inputManager.poll(); //clear any pending events first if(auto item = mappingList.selected()) { activeMapping = inputManager.hotkeys[item.offset()]; settingsWindow.layout.setEnabled(false); settingsWindow.statusBar.setText({"Press a key or button to map [", activeMapping->name, "] ..."}); settingsWindow.setDismissable(false); } } auto HotkeySettings::cancelMapping() -> void { activeMapping.reset(); settingsWindow.statusBar.setText(); settingsWindow.layout.setEnabled(); settingsWindow.doSize(); settingsWindow.setDismissable(true); } auto HotkeySettings::inputEvent(shared_pointer<HID::Device> device, uint group, uint input, int16 oldValue, int16 newValue) -> void { if(!activeMapping) return; if(device->isMouse()) return; if(activeMapping->bind(device, group, input, oldValue, newValue)) { activeMapping.reset(); settingsWindow.statusBar.setText("Mapping assigned."); refreshMappings(); timer.onActivate([&] { timer.setEnabled(false); cancelMapping(); }).setInterval(200).setEnabled(); } }
2,611
821
#ifndef _GDI_WINDOW_ #define _GDI_WINDOW_ namespace Guarneri { static LRESULT event_callback(HWND, UINT, WPARAM, LPARAM); static bool closed; class GDIWindow { public: void* framebuffer; int width; int height; float aspect; LPCSTR title; LPCSTR name; bool initialized; int buffer_size; HWND window_handle; HDC window_device_context; HBITMAP bitmap_handle; HBITMAP original_handle; int text_start = 16; public: void initialize(int w, int h, LPCSTR title_str, LRESULT(*event_callback)(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)); void set_title(LPCSTR _title); void draw_text(const int& w, const int& h, LPCSTR text); bool is_valid(); void flush(); void get_mouse_position(float& x, float& y, int& xi, int& yi); RECT get_rect(); void dispose(); void send_message(); }; void GDIWindow::initialize(int w, int h, LPCSTR title_str, LRESULT(*event_callback)(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)) { if (initialized) { return; } this->width = w; this->height = h; this->aspect = (float)w / (float)h; this->title = title_str; this->name = title_str; buffer_size = width * height * 4; window_handle = nullptr; window_device_context = nullptr; framebuffer = nullptr; bitmap_handle = nullptr; closed = false; WNDCLASS win_class; win_class.style = CS_BYTEALIGNCLIENT; win_class.lpfnWndProc = (WNDPROC)event_callback; win_class.cbClsExtra = 0; win_class.cbWndExtra = 0; win_class.hInstance = GetModuleHandle(nullptr); win_class.hIcon = nullptr; win_class.hCursor = LoadCursor(nullptr, IDC_ARROW); win_class.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); win_class.lpszMenuName = title; win_class.lpszClassName = name; BITMAPINFO bitmap_info; BITMAPINFOHEADER bitmap_header; bitmap_header.biSize = sizeof(BITMAPINFOHEADER); bitmap_header.biWidth = width; bitmap_header.biHeight = height; bitmap_header.biPlanes = 1; bitmap_header.biBitCount = 32; bitmap_header.biCompression = BI_RGB; bitmap_header.biSizeImage = buffer_size; bitmap_header.biXPelsPerMeter = 0; bitmap_header.biYPelsPerMeter = 0; bitmap_header.biClrUsed = 0; bitmap_header.biClrImportant = 0; bitmap_info.bmiHeader = bitmap_header; RegisterClass(&win_class); window_handle = CreateWindow(name, title, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 0, 0, 0, 0, nullptr, nullptr, win_class.hInstance, nullptr); HDC hDC = GetDC(window_handle); window_device_context = CreateCompatibleDC(hDC); ReleaseDC(window_handle, hDC); LPVOID buffer; bitmap_handle = CreateDIBSection(window_device_context, &bitmap_info, DIB_RGB_COLORS, &buffer, 0, 0); if (bitmap_handle != nullptr) { original_handle = (HBITMAP)SelectObject(window_device_context, bitmap_handle); } framebuffer = (void*)buffer; memset(framebuffer, 0, buffer_size); RECT rect = { 0, 0, width, height }; AdjustWindowRect(&rect, GetWindowLong(window_handle, GWL_STYLE), 0); int real_width = rect.right - rect.left; int real_height = rect.bottom - rect.top; int window_x = (GetSystemMetrics(SM_CXSCREEN) - real_width) / 2; int window_y = (GetSystemMetrics(SM_CYSCREEN) - real_height) / 2; SetWindowPos(window_handle, nullptr, window_x, window_y, real_width, real_height, (SWP_NOCOPYBITS | SWP_NOZORDER | SWP_SHOWWINDOW)); SetForegroundWindow(window_handle); ShowWindow(window_handle, SW_NORMAL); // window initialized initialized = true; } void GDIWindow::set_title(LPCSTR _title) { SetWindowText(window_handle, _title); } void GDIWindow::draw_text(const int& w, const int& h, LPCSTR text) { RECT rect; rect.left = 1; rect.right = 1 + w; rect.bottom = text_start - h; rect.top = text_start; DrawText(window_device_context, text, -1, &rect, DT_SINGLELINE | DT_LEFT | DT_VCENTER); text_start += h - 4; } bool GDIWindow::is_valid() { return !closed; } void GDIWindow::flush() { text_start = 16; HDC hDC = GetDC(window_handle); BitBlt(hDC, 0, 0, width, height, window_device_context, 0, 0, SRCCOPY); ReleaseDC(window_handle, hDC); send_message(); } void GDIWindow::get_mouse_position(float& x, float& y, int& xi, int& yi) { POINT pt; if (GetCursorPos(&pt)) { ScreenToClient(window_handle, &pt); xi = (int)pt.x; yi = (int)pt.y; x = (float)pt.x / (float)this->width; y = (float)pt.y / (float)this->height; } } RECT GDIWindow::get_rect() { RECT rect; if (GetWindowRect(window_handle, &rect)) { return rect; } return rect; } void GDIWindow::dispose() { if (original_handle) { SelectObject(window_device_context, original_handle); original_handle = nullptr; } if (window_device_context) { DeleteDC(window_device_context); window_device_context = nullptr; } if (bitmap_handle) { DeleteObject(bitmap_handle); bitmap_handle = nullptr; } if (window_handle) { CloseWindow(window_handle); window_handle = nullptr; } closed = true; } void GDIWindow::send_message() { MSG msg; while (1) { if (!PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE)) break; if (!GetMessage(&msg, nullptr, 0, 0)) break; DispatchMessage(&msg); } } } #endif
5,214
2,281
#include "Engine.h" #include <thread> namespace mion { Engine * Engine::s_pInstance = nullptr; Engine::Engine() : m_bRunning( false ), m_pWindow( nullptr ) { } Engine::~Engine() { } Engine * const Engine::getInstance() { return s_pInstance; } void Engine::renderLoop() { const std::chrono::high_resolution_clock::duration dur = std::chrono::nanoseconds( 1000000000 / 60 ); std::chrono::high_resolution_clock::time_point tp; while ( m_bRunning ) { tp = std::chrono::high_resolution_clock::now() + dur; // do stuff! std::this_thread::sleep_until( tp ); } } void Engine::logicLoop() { const std::chrono::high_resolution_clock::duration dur = std::chrono::nanoseconds( 1000000000 / ( 60 * 4 ) ); std::chrono::high_resolution_clock::time_point tp; while ( m_bRunning ) { tp = std::chrono::high_resolution_clock::now() + dur; // do stuff! std::this_thread::sleep_until( tp ); } } } // namespace mion
1,006
382
#include <string> #include <sstream> #include "exception.h" MugenException::MugenException(): Exception::Base("", -1), reason("unspecified"), where("?"), line(0){ } MugenException::MugenException(const std::string & reason, const std::string & where, int line): Exception::Base(where, line), reason(reason), where(where), line(line){ } Exception::Base * MugenException::copy() const { return new MugenException(reason, where, line); } const std::string MugenException::getFullReason() const { std::ostringstream out; out << where << ":" << line << " " << reason; return out.str(); } MugenException::~MugenException() throw() { } ReloadMugenException::ReloadMugenException(){ } ReloadMugenException::~ReloadMugenException() throw(){ } CanceledException::CanceledException(){ } CanceledException::~CanceledException() throw(){ } QuitGameException::QuitGameException(): MugenException("Quit game", __FILE__, __LINE__){ } QuitGameException::~QuitGameException() throw (){ } MugenRuntimeException::MugenRuntimeException(){ } MugenRuntimeException::MugenRuntimeException(const std::string & reason, const std::string & where, int line): MugenException(reason, where, line){ } MugenNormalRuntimeException::MugenNormalRuntimeException(){ } MugenNormalRuntimeException::MugenNormalRuntimeException(const std::string & reason, const std::string & where, int line): MugenRuntimeException(reason, where, line){ } MugenFatalRuntimeException::MugenFatalRuntimeException(){ } MugenFatalRuntimeException::MugenFatalRuntimeException(const std::string & reason, const std::string & where, int line): MugenRuntimeException(reason, where, line){ }
1,688
518
/* ============================================================================== Copyright 2007-2013 William Andrew Burnson. All rights reserved. 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. THIS SOFTWARE IS PROVIDED BY WILLIAM ANDREW BURNSON ''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 WILLIAM ANDREW BURNSON 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. ------------------------------------------------------------------------------ This file is part of Belle, Bonne, Sage -- The 'Beautiful, Good, Wise' C++ Vector-Graphics Library for Music Notation ============================================================================== */ /*Include Belle, Bonne, Sage and compile it in this .cpp file. See the previous tutorials for an explanation.*/ #define BELLE_COMPILE_INLINE #include "Belle.h" int main() { //Helper namespaces using namespace prim; using namespace belle; using namespace belle::graph; //Create an empty music graph. Music g; //----------------// //Treble Clef Part// //----------------// /*Create barline, clef, key signature, and time signature tokens. Each token is created and added to its own island (which is a container for tokens).*/ MusicNode b = g.CreateAndAddBarline(); MusicNode c = g.CreateAndAddClef(mica::TrebleClef); MusicNode k = g.CreateAndAddKeySignature(mica::TwoSharps, mica::Major); MusicNode t = g.CreateAndAddTimeSignature(3, prim::Ratio(1, 4)); //Link the clef island from the barline island g.Connect(b, c)->Set(mica::Type) = mica::Partwise; //Link the key signature island from the clef island. g.Connect(c, k)->Set(mica::Type) = mica::Partwise; //Link the time signature island from the key signature island. g.Connect(k, t)->Set(mica::Type) = mica::Partwise; /*Create a quarter-note chord and link its island partwise from the time signature island.*/ MusicNode chord = g.CreateChord(prim::Ratio(3, 4)); g.CreateAndAddNote(chord, mica::D4); g.CreateAndAddNote(chord, mica::FSharp4); MusicNode chordIsland = g.AddChordToNewIsland(chord); g.Connect(t, chordIsland)->Set(mica::Type) = mica::Partwise; //Create a final barline. MusicNode f = g.CreateAndAddBarline(mica::EndBarline); g.Connect(chordIsland, f)->Set(mica::Type) = mica::Partwise; //--------------// //Bass Clef Part// //--------------// /*Create barline, clef, key signature, and time signature tokens. Each token is created and added to its own island (which is a container for tokens).*/ MusicNode b2 = g.CreateAndAddBarline(); MusicNode c2 = g.CreateAndAddClef(mica::BassClef); MusicNode k2 = g.CreateAndAddKeySignature(mica::TwoSharps, mica::Major); MusicNode t2 = g.CreateAndAddTimeSignature(3, prim::Ratio(1, 4)); //Link the clef island from the barline island g.Connect(b2, c2)->Set(mica::Type) = mica::Partwise; //Link the key signature island from the clef island. g.Connect(c2, k2)->Set(mica::Type) = mica::Partwise; //Link the time signature island from the key signature island. g.Connect(k2, t2)->Set(mica::Type) = mica::Partwise; /*Create a quarter-note chord and link its island partwise from the time signature island.*/ MusicNode chord2 = g.CreateChord(prim::Ratio(3, 4)); g.CreateAndAddNote(chord2, mica::D3); g.CreateAndAddNote(chord2, mica::A3); MusicNode chordIsland2= g.AddChordToNewIsland(chord2); g.Connect(t2, chordIsland2)->Set(mica::Type) = mica::Partwise; //Create a final barline. MusicNode f2 = g.CreateAndAddBarline(mica::EndBarline); g.Connect(chordIsland2, f2)->Set(mica::Type) = mica::Partwise; //-------------------------------// //Link Parts Together Instantwise// //-------------------------------// g.Connect(b, b2)->Set(mica::Type) = mica::Instantwise; g.Connect(c, c2)->Set(mica::Type) = mica::Instantwise; g.Connect(k, k2)->Set(mica::Type) = mica::Instantwise; g.Connect(t, t2)->Set(mica::Type) = mica::Instantwise; g.Connect(chordIsland, chordIsland2)->Set(mica::Type) = mica::Instantwise; g.Connect(f, f2)->Set(mica::Type) = mica::Instantwise; /*Export the graph, reimport the graph (as a test of serialization), and show a visualization of it.*/ Music h; h.ImportXML(g.ExportXML()); Utility::OpenGraphVisualization(h); prim::c >> h.ExportXML(); prim::c >> h; return prim::c.Finish(); }
5,420
1,890
/* * Copyright (c) 2012-2020 MIRACL UK Ltd. * * This file is part of MIRACL Core * (see https://github.com/miracl/core). * * 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 "arch.h" #include "fp_F384PM.h" namespace F384PM { /* NUMS 384-bit modulus */ #if CHUNK==16 #error Not supported #endif #if CHUNK==32 using namespace B384_29; // Base Bits= 29 const BIG Modulus= {0x1FFFFEC3,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7F}; const BIG ROI= {0x1FFFFEC2,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7F}; const BIG R2modp= {0x0,0x4448000,0x6,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0}; const chunk MConst= 0x13D; #endif #if CHUNK==64 using namespace B384_58; // Base Bits= 58 const BIG Modulus= {0x3FFFFFFFFFFFEC3L,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0xFFFFFFFFFL}; const BIG R2modp= {0x88900000000000L,0x6L,0x0L,0x0L,0x0L,0x0L,0x0L}; const BIG ROI= {0x3FFFFFFFFFFFEC2L,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0x3FFFFFFFFFFFFFFL,0xFFFFFFFFFL}; const chunk MConst= 0x13DL; #endif }
1,794
858
/* * kaze *__________________ * @file CPUInfo_Private.cpp * @author Clement Berthaud * @brief This file provides the definition for the FCPUInfo_Private tools. * @copyright Copyright 2021 Clement Berthaud. * @license Please refer to LICENSE.md */ #include "System/CPUInfo/CPUInfo_Private.h" #include "System/CPUInfo/CPUInfoHelpers.h" #if defined( ULIS_WIN ) #include "System/CPUInfo/CPUInfo_Windows.inl" #elif defined( ULIS_MACOS ) #include "System/CPUInfo/CPUInfo_macOS.inl" #elif defined( ULIS_LINUX ) #include "System/CPUInfo/CPUInfo_Linux.inl" #else #include "System/CPUInfo/CPUInfo_Generic.inl" #endif ULIS_NAMESPACE_BEGIN FCPUInfo_Private::FCPUInfo_Private() : features_bitfield( 0 ) , max_workers( static_cast< uint32 >( detail::num_workers() ) ) , l1_cache_size( 65536 ) , l1_cache_line_size( 64 ) { detail::cache_info( 1, &l1_cache_size, &l1_cache_line_size ); features_bitfield |= ULIS_W_OS_X64( uint64( detail::detect_OS_x64() ) ); features_bitfield |= ULIS_W_OS_AVX( uint64( detail::detect_OS_AVX() ) ); features_bitfield |= ULIS_W_OS_AVX512( uint64( detail::detect_OS_AVX512() ) ); std::string vendor( detail::get_vendor_string() ); if( vendor == "GenuineIntel" ) features_bitfield |= ULIS_R_HW_INTEL( 1 ); else if( vendor == "AuthenticAMD") features_bitfield |= ULIS_R_HW_AMD( 1 ); int info[4] { 0, 0, 0, 0 }; detail::cpuid( info, 0 ); int nIds = info[0]; detail::cpuid( info, 0x80000000 ); uint32_t nExIds = info[0]; if( nIds >= 0x00000001 ) { detail::cpuid( info, 0x00000001 ); features_bitfield |= ULIS_W_HW_MMX( uint64( ( info[3] & ( uint64( 1 ) << 23 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SSE( uint64( ( info[3] & ( uint64( 1 ) << 25 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SSE2( uint64( ( info[3] & ( uint64( 1 ) << 26 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SSE3( uint64( ( info[2] & ( uint64( 1 ) << 0 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SSSE3( uint64( ( info[2] & ( uint64( 1 ) << 9 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SSE41( uint64( ( info[2] & ( uint64( 1 ) << 19 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SSE42( uint64( ( info[2] & ( uint64( 1 ) << 20 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AES( uint64( ( info[2] & ( uint64( 1 ) << 25 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX( uint64( ( info[2] & ( uint64( 1 ) << 28 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_FMA3( uint64( ( info[2] & ( uint64( 1 ) << 12 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_RDRAND( uint64( ( info[2] & ( uint64( 1 ) << 30 ) ) != 0 ) ); } if( nIds >= 0x00000007 ) { detail::cpuid( info, 0x00000007 ); features_bitfield |= ULIS_W_HW_AVX2( uint64( ( info[1] & ( uint64( 1 ) << 5 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_BMI1( uint64( ( info[1] & ( uint64( 1 ) << 3 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_BMI2( uint64( ( info[1] & ( uint64( 1 ) << 8 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_ADX( uint64( ( info[1] & ( uint64( 1 ) << 19 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_MPX( uint64( ( info[1] & ( uint64( 1 ) << 14 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SHA( uint64( ( info[1] & ( uint64( 1 ) << 29 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_PREFETCHWT1( uint64( ( info[2] & ( uint64( 1 ) << 0 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_F( uint64( ( info[1] & ( uint64( 1 ) << 16 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_CD( uint64( ( info[1] & ( uint64( 1 ) << 28 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_PF( uint64( ( info[1] & ( uint64( 1 ) << 26 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_ER( uint64( ( info[1] & ( uint64( 1 ) << 27 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_VL( uint64( ( info[1] & ( uint64( 1 ) << 31 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_BW( uint64( ( info[1] & ( uint64( 1 ) << 30 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_DQ( uint64( ( info[1] & ( uint64( 1 ) << 17 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_IFMA( uint64( ( info[1] & ( uint64( 1 ) << 21 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_AVX512_VBMI( uint64( ( info[2] & ( uint64( 1 ) << 1 ) ) != 0 ) ); } if( nExIds >= 0x80000001 ) { detail::cpuid( info, 0x80000001 ); features_bitfield |= ULIS_W_HW_X64( uint64( ( info[3] & ( uint64( 1 ) << 29 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_ABM( uint64( ( info[2] & ( uint64( 1 ) << 5 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_SSE4A( uint64( ( info[2] & ( uint64( 1 ) << 6 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_FMA4( uint64( ( info[2] & ( uint64( 1 ) << 16 ) ) != 0 ) ); features_bitfield |= ULIS_W_HW_XOP( uint64( ( info[2] & ( uint64( 1 ) << 11 ) ) != 0 ) ); } } ULIS_NAMESPACE_END
5,177
2,474
//AC #include <bits/stdc++.h> #define LLI long long using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); LLI t; cin >> t; while (t--) { LLI x; cin >> x; if (x > 45) { cout << -1 << "\n"; continue; } string ans = ""; LLI s = 9; while (x > 0) { if (x < s) { s = x; } x -= s; ans = (char)('0' + s) + ans; s--; } cout << ans << "\n"; } return 0; }
584
219
#include <bits/stdc++.h> #include <cstdio> #include <cstring> #include <iostream> #include <cstdlib> #include <algorithm> #define MAX 4000 using namespace std; int n, s, peso[MAX], valor[MAX], dp[MAX][MAX]; int main() { memset(dp, -1, sizeof(dp)); // dp[all i] = -1 cin >> s >> n; for (int i=1; i<=n; i++) { cin >> peso[i] >> valor[i]; } // knapsack algo for (int i=0; i<=n; i++) { int obj = i; for (int j=0; j<=s; j++) { if (i == 0 || j == 0) dp[obj][j] = 0; else { int aguenta = j; int n_coloca = dp[obj-1][aguenta]; if (peso[obj] <= aguenta) { int coloca = valor[obj] + dp[obj-1][aguenta-peso[obj]]; dp[obj][aguenta] = max(coloca, n_coloca); } else { dp[obj][aguenta] = n_coloca; } } } } cout << dp[n][s]; return 0; }
836
458
//----------------------------------------------------------------------------- // File : asdxShader.h // Desc : Shader Set Module. // Copyright(c) Project Asura. ALl right reserved. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #include <asdxShader.h> #include <asdxLogger.h> namespace asdx { /////////////////////////////////////////////////////////////////////////////// // ShaderCBV class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- ShaderCBV::ShaderCBV() { /* DO_NOTHING */ } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- ShaderCBV::~ShaderCBV() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool ShaderCBV::Init ( ID3D11Device* pDevice, ID3D11ShaderReflectionConstantBuffer* pReflection ) { if (pDevice == nullptr || pReflection == nullptr) { ELOG("Error : Invalid Argument."); return false; } D3D11_SHADER_BUFFER_DESC buf_desc; auto hr = pReflection->GetDesc(&buf_desc); if (FAILED(hr)) { ELOG("Error : ID3D11ShaderReflectionConstantBuffer::GetDesc() Failed. recode = 0x%x", hr); return false; } auto size = buf_desc.Size; m_Memory.resize(size); D3D11_BUFFER_DESC cb_desc = {}; cb_desc.Usage = D3D11_USAGE_DEFAULT; cb_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cb_desc.ByteWidth = size; cb_desc.CPUAccessFlags = 0; hr = pDevice->CreateBuffer(&cb_desc, nullptr, m_CB.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateBuffer() Failed"); return false; } for(auto i=0u; i<buf_desc.Variables; ++i) { auto pVar = pReflection->GetVariableByIndex(i); if (pVar == nullptr) { continue; } D3D11_SHADER_VARIABLE_DESC var_desc; hr = pVar->GetDesc(&var_desc); if (FAILED(hr)) { continue; } BufferParam param; param.Offset = var_desc.StartOffset; param.Size = var_desc.Size; if (!Contain(var_desc.Name)) { m_ParamMap[var_desc.Name] = param; } auto head = m_Memory.data(); memcpy(head + var_desc.StartOffset, var_desc.DefaultValue, var_desc.Size); } return true; } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void ShaderCBV::Term() { m_CB.Reset(); m_ParamMap.clear(); m_Memory .clear(); } //----------------------------------------------------------------------------- // パラメータを設定します. //----------------------------------------------------------------------------- bool ShaderCBV::SetParam(const char* name, const void* ptr, size_t size) { if (!Contain(name)) { return false; } auto param = m_ParamMap[name]; if (param.Size != size) { return false; } auto head = m_Memory.data(); memcpy(head + param.Offset, ptr, param.Size); return true; } //----------------------------------------------------------------------------- // パラメータを取得します. //----------------------------------------------------------------------------- bool ShaderCBV::GetParam(const char* name, void* ptr, size_t size) const { if (!Contain(name)) { return false; } auto param = m_ParamMap.at(name); if (param.Size != size) { return false; } auto head = m_Memory.data(); memcpy(ptr, head + param.Offset, param.Size); return true; } //----------------------------------------------------------------------------- // 指定されたパラメータ名が含まれるかチェックします. //----------------------------------------------------------------------------- bool ShaderCBV::Contain(const char* name) const { return m_ParamMap.find(name) != m_ParamMap.end(); } //----------------------------------------------------------------------------- // サブリソースを更新します. //----------------------------------------------------------------------------- void ShaderCBV::UpdateSubresource(ID3D11DeviceContext* pContext) { pContext->UpdateSubresource(m_CB.GetPtr(), 0, nullptr, m_Memory.data(), 0, 0); } //----------------------------------------------------------------------------- // バッファを返却します //----------------------------------------------------------------------------- ID3D11Buffer* ShaderCBV::GetPtr() const { return m_CB.GetPtr(); } /////////////////////////////////////////////////////////////////////////////// // VertexShader class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- VertexShader::VertexShader() { /* DO_NOTHING */ } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- VertexShader::~VertexShader() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool VertexShader::Init ( ID3D11Device* pDevice, const uint8_t* pBinary, size_t binarySize, uint32_t elementCount, const D3D11_INPUT_ELEMENT_DESC* pElements ) { auto hr = pDevice->CreateVertexShader(pBinary, binarySize, nullptr, m_VS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateVertexShader() Failed."); Term(); return false; } hr = pDevice->CreateInputLayout(pElements, elementCount, pBinary, binarySize, m_IL.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateInputLayout() Failed."); Term(); return false; } hr = D3DReflect(pBinary, binarySize, IID_PPV_ARGS(m_Reflection.GetAddress())); if (FAILED(hr)) { ELOG("Error : D3DReflect() Failed."); Term(); return false; } return true; } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool VertexShader::Init ( ID3D11Device* pDevice, const wchar_t* path, const char* entryPoint, const char* shaderModel, uint32_t elementCount, const D3D11_INPUT_ELEMENT_DESC* pElements ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompileFromFile( path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize(), elementCount, pElements); } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool VertexShader::Init ( ID3D11Device* pDevice, const char* sourceCode, size_t sourceCodeSize, const char* entryPoint, const char* shaderModel, uint32_t elementCount, const D3D11_INPUT_ELEMENT_DESC* pElements ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompile( sourceCode, sourceCodeSize, "vertex_shader", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize(), elementCount, pElements); } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void VertexShader::Term() { m_VS.Reset(); m_IL.Reset(); m_Reflection.Reset(); } //----------------------------------------------------------------------------- // シェーダを設定します. //----------------------------------------------------------------------------- void VertexShader::Bind(ID3D11DeviceContext* pContext) { pContext->IASetInputLayout(m_IL.GetPtr()); pContext->VSSetShader(m_VS.GetPtr(), nullptr, 0); } //----------------------------------------------------------------------------- // シェーダの設定を解除します. //----------------------------------------------------------------------------- void VertexShader::UnBind(ID3D11DeviceContext* pContext) { pContext->IASetInputLayout(nullptr); pContext->VSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // シェーダリフレクションを取得します. //----------------------------------------------------------------------------- ID3D11ShaderReflection* VertexShader::GetReflection() const { return m_Reflection.GetPtr(); } /////////////////////////////////////////////////////////////////////////////// // PixelShader class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- PixelShader::PixelShader() { /* DO_NOTHING */ } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- PixelShader::~PixelShader() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool PixelShader::Init(ID3D11Device* pDevice, const uint8_t* pBinary, size_t binarySize) { auto hr = pDevice->CreatePixelShader(pBinary, binarySize, nullptr, m_PS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreatePixelShader() Failed."); Term(); return false; } hr = D3DReflect(pBinary, binarySize, IID_PPV_ARGS(m_Reflection.GetAddress())); if (FAILED(hr)) { ELOG("Error : D3DReflect() Failed."); Term(); return false; } return true; } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool PixelShader::Init ( ID3D11Device* pDevice, const wchar_t* path, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompileFromFile( path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool PixelShader::Init ( ID3D11Device* pDevice, const char* sourceCode, size_t sourceCodeSize, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompile( sourceCode, sourceCodeSize, "pixel_shader", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void PixelShader::Term() { m_PS.Reset(); m_Reflection.Reset(); } //----------------------------------------------------------------------------- // シェーダを設定します. //----------------------------------------------------------------------------- void PixelShader::Bind(ID3D11DeviceContext* pContext) { pContext->PSSetShader(m_PS.GetPtr(), nullptr, 0); } //----------------------------------------------------------------------------- // シェーダの設定を解除します. //----------------------------------------------------------------------------- void PixelShader::UnBind(ID3D11DeviceContext* pContext) { pContext->PSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // シェーダリフレクションを取得します. //----------------------------------------------------------------------------- ID3D11ShaderReflection* PixelShader::GetReflection() const { return m_Reflection.GetPtr(); } /////////////////////////////////////////////////////////////////////////////// // GeometryShader class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- GeometryShader::GeometryShader() { /* DO_NOTHING */ } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- GeometryShader::~GeometryShader() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool GeometryShader::Init(ID3D11Device* pDevice, const uint8_t* pBinary, size_t binarySize) { auto hr = pDevice->CreateGeometryShader(pBinary, binarySize, nullptr, m_GS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateGeometryShader() Failed."); Term(); return false; } hr = D3DReflect(pBinary, binarySize, IID_PPV_ARGS(m_Reflection.GetAddress())); if (FAILED(hr)) { ELOG("Error : D3DReflect() Failed."); Term(); return false; } return true; } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool GeometryShader::Init ( ID3D11Device* pDevice, const wchar_t* path, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompileFromFile( path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool GeometryShader::Init ( ID3D11Device* pDevice, const char* sourceCode, size_t sourceCodeSize, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompile( sourceCode, sourceCodeSize, "geometry_shader", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void GeometryShader::Term() { m_GS.Reset(); m_Reflection.Reset(); } //----------------------------------------------------------------------------- // シェーダを設定します. //----------------------------------------------------------------------------- void GeometryShader::Bind(ID3D11DeviceContext* pContext) { pContext->GSSetShader(m_GS.GetPtr(), nullptr, 0); } //----------------------------------------------------------------------------- // シェーダの設定を解除します. //----------------------------------------------------------------------------- void GeometryShader::UnBind(ID3D11DeviceContext* pContext) { pContext->GSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // シェーダリフレクションを取得します. //----------------------------------------------------------------------------- ID3D11ShaderReflection* GeometryShader::GetReflection() const { return m_Reflection.GetPtr(); } /////////////////////////////////////////////////////////////////////////////// // HullShader class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- HullShader::HullShader() { /* DO_NOTHING */ } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- HullShader::~HullShader() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool HullShader::Init(ID3D11Device* pDevice, const uint8_t* pBinary, size_t binarySize) { auto hr = pDevice->CreateHullShader(pBinary, binarySize, nullptr, m_HS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreatePixelShader() Failed."); Term(); return false; } hr = D3DReflect(pBinary, binarySize, IID_PPV_ARGS(m_Reflection.GetAddress())); if (FAILED(hr)) { ELOG("Error : D3DReflect() Failed."); Term(); return false; } return true; } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool HullShader::Init ( ID3D11Device* pDevice, const wchar_t* path, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompileFromFile( path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool HullShader::Init ( ID3D11Device* pDevice, const char* sourceCode, size_t sourceCodeSize, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompile( sourceCode, sourceCodeSize, "hull_shader", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void HullShader::Term() { m_HS.Reset(); m_Reflection.Reset(); } //----------------------------------------------------------------------------- // シェーダを設定します. //----------------------------------------------------------------------------- void HullShader::Bind(ID3D11DeviceContext* pContext) { pContext->HSSetShader(m_HS.GetPtr(), nullptr, 0); } //----------------------------------------------------------------------------- // シェーダの設定を解除します. //----------------------------------------------------------------------------- void HullShader::UnBind(ID3D11DeviceContext* pContext) { pContext->HSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // シェーダリフレクションを取得します. //----------------------------------------------------------------------------- ID3D11ShaderReflection* HullShader::GetReflection() const { return m_Reflection.GetPtr(); } /////////////////////////////////////////////////////////////////////////////// // DomainShader class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- DomainShader::DomainShader() { /* DO_NOTHING */ } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- DomainShader::~DomainShader() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool DomainShader::Init(ID3D11Device* pDevice, const uint8_t* pBinary, size_t binarySize) { auto hr = pDevice->CreateDomainShader(pBinary, binarySize, nullptr, m_DS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreateDomainShader() Failed."); Term(); return false; } hr = D3DReflect(pBinary, binarySize, IID_PPV_ARGS(m_Reflection.GetAddress())); if (FAILED(hr)) { ELOG("Error : D3DReflect() Failed."); Term(); return false; } return true; } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool DomainShader::Init ( ID3D11Device* pDevice, const wchar_t* path, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompileFromFile( path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool DomainShader::Init ( ID3D11Device* pDevice, const char* sourceCode, size_t sourceCodeSize, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompile( sourceCode, sourceCodeSize, "domain_shader", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void DomainShader::Term() { m_DS.Reset(); m_Reflection.Reset(); } //----------------------------------------------------------------------------- // シェーダを設定します. //----------------------------------------------------------------------------- void DomainShader::Bind(ID3D11DeviceContext* pContext) { pContext->DSSetShader(m_DS.GetPtr(), nullptr, 0); } //----------------------------------------------------------------------------- // シェーダの設定を解除します. //----------------------------------------------------------------------------- void DomainShader::UnBind(ID3D11DeviceContext* pContext) { pContext->DSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // シェーダリフレクションを取得します. //----------------------------------------------------------------------------- ID3D11ShaderReflection* DomainShader::GetReflection() const { return m_Reflection.GetPtr(); } /////////////////////////////////////////////////////////////////////////////// // ComputeShader class /////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // コンストラクタです. //----------------------------------------------------------------------------- ComputeShader::ComputeShader() : m_ThreadX(0) , m_ThreadY(0) , m_ThreadZ(0) { /* DO_NOTHING */ } //----------------------------------------------------------------------------- // デストラクタです. //----------------------------------------------------------------------------- ComputeShader::~ComputeShader() { Term(); } //----------------------------------------------------------------------------- // 初期化処理を行います. //----------------------------------------------------------------------------- bool ComputeShader::Init(ID3D11Device* pDevice, const uint8_t* pBinary, size_t binarySize) { auto hr = pDevice->CreateComputeShader(pBinary, binarySize, nullptr, m_CS.GetAddress()); if (FAILED(hr)) { ELOG("Error : ID3D11Device::CreatePixelShader() Failed."); Term(); return false; } hr = D3DReflect(pBinary, binarySize, IID_PPV_ARGS(m_Reflection.GetAddress())); if (FAILED(hr)) { ELOG("Error : D3DReflect() Failed."); Term(); return false; } m_Reflection->GetThreadGroupSize(&m_ThreadX, &m_ThreadY, &m_ThreadZ); return true; } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool ComputeShader::Init ( ID3D11Device* pDevice, const wchar_t* path, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompileFromFile( path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // ソースコードから初期化処理を行います. //----------------------------------------------------------------------------- bool ComputeShader::Init ( ID3D11Device* pDevice, const char* sourceCode, size_t sourceCodeSize, const char* entryPoint, const char* shaderModel ) { DWORD flag = D3DCOMPILE_ENABLE_STRICTNESS; #if defined(DEBUG) || defined(_DEBUG) flag |= D3DCOMPILE_DEBUG; #else flag |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif RefPtr<ID3DBlob> pBlob; RefPtr<ID3DBlob> pErrorBlob; auto hr = D3DCompile( sourceCode, sourceCodeSize, "compute_shader", nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel, flag, 0, pBlob.GetAddress(), pErrorBlob.GetAddress()); if (FAILED(hr)) { if (pErrorBlob.GetPtr() != nullptr) { ELOGA("Error : D3DCompileFromFile() Failed. msg = %s", pErrorBlob->GetBufferPointer()); } ELOGA("Error : D3DCompileFromFile() errcode = 0x%x", hr); Term(); return false; } return Init( pDevice, reinterpret_cast<uint8_t*>(pBlob->GetBufferPointer()), pBlob->GetBufferSize()); } //----------------------------------------------------------------------------- // 終了処理を行います. //----------------------------------------------------------------------------- void ComputeShader::Term() { m_CS.Reset(); m_Reflection.Reset(); m_ThreadX = m_ThreadY = m_ThreadZ = 0; } //----------------------------------------------------------------------------- // シェーダを設定します. //----------------------------------------------------------------------------- void ComputeShader::Bind(ID3D11DeviceContext* pContext) { pContext->CSSetShader(m_CS.GetPtr(), nullptr, 0); } //----------------------------------------------------------------------------- // シェーダの設定を解除します. //----------------------------------------------------------------------------- void ComputeShader::UnBind(ID3D11DeviceContext* pContext) { pContext->CSSetShader(nullptr, nullptr, 0); } //----------------------------------------------------------------------------- // ディスパッチします. //----------------------------------------------------------------------------- void ComputeShader::Dispatch(ID3D11DeviceContext* pContext) { pContext->Dispatch(m_ThreadX, m_ThreadY, m_ThreadZ); } //----------------------------------------------------------------------------- // シェーダリフレクションを取得します. //----------------------------------------------------------------------------- ID3D11ShaderReflection* ComputeShader::GetReflection() const { return m_Reflection.GetPtr(); } } // namespace asdx
38,083
11,614
// $Id: debug.cpp,v 1.2 2014-05-08 18:07:04-07 - - $ #include <cassert> #include <climits> #include <iostream> #include <vector> using namespace std; #include "debug.h" #include "util.h" vector<bool> debugflags::flags (UCHAR_MAX + 1, false); void debugflags::setflags (const string& initflags) { for (const char flag: initflags) { if (flag == '@') flags.assign (flags.size(), true); else flags[flag] = true; } // Note that DEBUGF can trace setflags. if (getflag ('x')) { string flag_chars; for (size_t index = 0; index < flags.size(); ++index) { if (getflag (index)) flag_chars += (char) index; } } } // // getflag - // Check to see if a certain flag is on. // bool debugflags::getflag (char flag) { // WARNING: Don't TRACE this function or the stack will blow up. unsigned uflag = (unsigned char) flag; assert (uflag < flags.size()); return flags[uflag]; } void debugflags::where (char flag, const char* file, int line, const char* func) { cout << sys_info::execname() << ": DEBUG(" << flag << ") " << file << "[" << line << "] " << func << "()" << endl; }
1,182
412
#include "path.h" #include "../container/symbol_tracker.h" #include "../../discretization/util/util.h" #include "../util/util.h" #include "../../util/util.h" namespace critter{ namespace internal{ namespace decomposition{ void path::exchange_communicators(MPI_Comm oldcomm, MPI_Comm newcomm){ // Accumulate the computation time between last communication routine // as both execution-time and computation time into both // the execution-time critical path data structures and the // per-process data structures. volatile auto curtime = MPI_Wtime(); auto save_comp_time = curtime - computation_timer; if (mode==1){ cp_costs[num_cp_measures-1] += save_comp_time; cp_costs[num_cp_measures-3] += save_comp_time; vol_costs[num_vol_measures-1] += save_comp_time; vol_costs[num_vol_measures-3] += save_comp_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-path_count-1-i] += save_comp_time; } } if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ // Get the current symbol's execution-time since last // communication routine or its inception. // Accumulate as both execution-time and computation time // into both the execution-time critical path data structures // and the per-process data structures. auto last_symbol_time = curtime - symbol_timers[symbol_stack.top()].start_timer.top(); for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } else if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += last_symbol_time; } } if (mode==1){ computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } } } bool path::initiate_comp(size_t id, volatile double curtime, float flop_count, int param1, int param2, int param3, int param4, int param5){ // accumulate computation time auto save_comp_time = curtime - computation_timer; cp_costs[num_cp_measures-3] += save_comp_time; cp_costs[num_cp_measures-1] += save_comp_time; vol_costs[num_vol_measures-3] += save_comp_time; vol_costs[num_vol_measures-1] += save_comp_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-path_count-1-i] += save_comp_time; } } if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ // Get the current symbol's execution-time since last // communication routine or its inception. // Accumulate as both execution-time and computation time // into both the execution-time critical path data structures // and the per-process data structures. auto last_symbol_time = curtime - symbol_timers[symbol_stack.top()].start_timer.top(); for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } else if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += last_symbol_time; } // start compunication timer for compunication routine comp_start_time = MPI_Wtime(); return true; } void path::complete_comp(double errtime, size_t id, float flop_count, int param1, int param2, int param3, int param4, int param5){ volatile auto comp_time = MPI_Wtime() - comp_start_time - errtime; // complete computation time // Save kernel information if (autotuning_debug == 1){ comp_kernel_key key(-1,id,flop_count,param1,param2,param3,param4,param5); if (comp_kernel_info.find(key) == comp_kernel_info.end()){ comp_kernel_info[key] = std::make_pair(1,comp_time); } else{ comp_kernel_info[key].first++; comp_kernel_info[key].second += comp_time; } } // Decompose measurements along multiple paths by symbol if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == path_measure_select.size()-5){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += flop_count; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += flop_count; } else if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comp_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comp_time; } else if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comp_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comp_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-5] += flop_count; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-5] += flop_count; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += comp_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += comp_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += comp_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += comp_time; } cp_costs[num_cp_measures-6] += flop_count; cp_costs[num_cp_measures-3] += comp_time; cp_costs[num_cp_measures-2] += comp_time; cp_costs[num_cp_measures-1] += comp_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-1-i] += comp_time; } for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-path_count-1-i] += comp_time; } for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-3*path_count-1-i] += flop_count; } } vol_costs[num_vol_measures-7] += flop_count; vol_costs[num_vol_measures-3] += comp_time; vol_costs[num_vol_measures-2] += comp_time; vol_costs[num_vol_measures-1] += comp_time; computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } } static void update_cp_decomp1(float* in, float* inout, size_t len){ assert(len == cp_costs_size); // this assert prevents user from obtaining wrong output if MPI implementation cuts up the message. if (path_count > 0){ // We do not track paths for synchronization time nor comp-kernel time, so check for those for (int i=0; i<path_index.size(); i++){ // 0->0, 1->1, 2->2, 3->3, 4->5, 5->7 int j= path_index[i]<4 ? path_index[i] : path_index[i]+1; if (j==6) j++; path_decisions[i] = inout[j] > in[j]; } for (int i=0; i<num_cp_measures; i++){ inout[i] = std::max(inout[i],in[i]); } for (int i=num_cp_measures; i<cp_costs_size; i++){ int idx = (i-num_cp_measures)%path_count; inout[i] = (path_decisions[idx] ? inout[i] : in[i]); } } else{ for (int i=0; i<num_cp_measures; i++){ inout[i] = std::max(inout[i],in[i]); } } } static void update_cp_decomp2(float* in, float* inout, size_t len){ assert(len == cp_costs_size); // this assert prevents user from obtaining wrong output if MPI implementation cuts up the message. if (path_count > 0){ // We do not track paths for synchronization time nor comp-kernel time, so check for those for (int i=0; i<path_index.size(); i++){ // 0->0, 1->1, 2->2, 3->3, 4->5, 5->7 int j= path_index[i]<4 ? path_index[i] : path_index[i]+1; if (j==6) j++; assert(path_index[i] == 5); path_decisions[i] = inout[j] > in[j]; } for (int i=0; i<num_cp_measures; i++){ inout[i] = std::max(inout[i],in[i]); } size_t path_select_offset = 4*num_decomp_cp_measures+1; for (int i=num_cp_measures; i<cp_costs_size; i++){ int idx = (i-num_cp_measures)%(path_count*path_select_offset);// restarts for each symbol idx /= path_select_offset; inout[i] = (path_decisions[idx] ? inout[i] : in[i]); } } else{ for (int i=0; i<num_cp_measures; i++){ inout[i] = std::max(inout[i],in[i]); } } } static void propagate_cp_decomp1_op(float* in, float* inout, int* len, MPI_Datatype* dtype){ update_cp_decomp1(in,inout,static_cast<size_t>(*len)); } static void propagate_cp_decomp2_op(float* in, float* inout, int* len, MPI_Datatype* dtype){ update_cp_decomp2(in,inout,static_cast<size_t>(*len)); } bool path::initiate_comm(blocking& tracker, volatile double curtime, int64_t nelem, MPI_Datatype t, MPI_Comm comm, bool is_sender, int partner1, int user_tag1, int partner2, int user_tag2){ // Check for conflicting communication tag(s) if (partner1 != -1) assert(!(user_tag1 >= internal_tag && user_tag1 <= internal_tag5)); if (partner2 != -1) assert(!(user_tag2 >= internal_tag && user_tag2 <= internal_tag5)); // Save and accumulate the computation time between last communication routine as both execution-time and computation time // into both the execution-time critical path data structures and the per-process data structures. tracker.comp_time = curtime - computation_timer; int rank; MPI_Comm_rank(comm, &rank); MPI_Buffer_attach(&eager_pad[0],eager_pad.size()); // Save caller communication attributes into reference object for use in corresponding static method 'complete' int word_size,np; MPI_Type_size(t, &word_size); int64_t nbytes = word_size * nelem; MPI_Comm_size(comm, &np); tracker.nbytes = nbytes; tracker.comm = comm; tracker.comm_size = np; tracker.is_sender = is_sender; tracker.partner1 = partner1; tracker.partner2 = partner2 != -1 ? partner2 : partner1;// Useful in propagation tracker.synch_time = 0.;// might get updated below tracker.barrier_time = 0.;// might get updated below if (partner1 == MPI_ANY_SOURCE){// only possible for 'MPI_Recv' MPI_Status st; PMPI_Probe(partner1,user_tag1,comm,&st); save_wildcard_id = st.MPI_SOURCE; tracker.partner1 = save_wildcard_id; } else if (partner2 == MPI_ANY_SOURCE){// only possible for 'MPI_Sendrecv' / 'MPI_Sendrecv_replace' assert((tracker.tag == 13) || (tracker.tag == 14)); MPI_Status st; PMPI_Probe(partner2,user_tag2,comm,&st); save_wildcard_id = st.MPI_SOURCE; tracker.partner2 = save_wildcard_id; } volatile auto init_time = MPI_Wtime(); if (tracker.partner1 == -1){ PMPI_Barrier(tracker.comm); tracker.barrier_time = MPI_Wtime() - init_time; } else { MPI_Request barrier_reqs[3]; int barrier_count=0; char sbuf='H'; char rbuf='H'; if ((is_sender) && (rank != tracker.partner1)){ PMPI_Bsend(&sbuf, 1, MPI_CHAR, tracker.partner1, internal_tag3, tracker.comm); } if ((!is_sender) && (rank != tracker.partner1)){ PMPI_Irecv(&rbuf, 1, MPI_CHAR, tracker.partner1, internal_tag3, tracker.comm, &barrier_reqs[barrier_count]); barrier_count++; } if ((partner2 != -1) && (rank != partner2)){ PMPI_Irecv(&rbuf, 1, MPI_CHAR, tracker.partner2, internal_tag3, tracker.comm, &barrier_reqs[barrier_count]); barrier_count++; } PMPI_Waitall(barrier_count,&barrier_reqs[0],MPI_STATUSES_IGNORE); if (barrier_count>0) tracker.barrier_time = MPI_Wtime() - init_time; } cp_costs[num_cp_measures-3] += tracker.comp_time; cp_costs[num_cp_measures-1] += tracker.comp_time; vol_costs[num_vol_measures-3] += tracker.comp_time; vol_costs[num_vol_measures-1] += tracker.comp_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-1-i-path_count] += tracker.comp_time; cp_costs[cp_costs_size-1-i-2*path_count] += tracker.barrier_time; } } if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ auto last_symbol_time = curtime - symbol_timers[symbol_stack.top()].start_timer.top(); for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } else if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += last_symbol_time; } if (track_synchronization && tracker.partner1==-1){ // Use the user communication routine to measre synchronization time. // Note the following consequences of using a tiny 1-byte message (note that 0-byte is trivially handled by most MPI implementations) on measuring synchronization time: // 1) The collective communication algorithm is likely different for small messages than large messages. // 2) The eager sending protocol will be utilized, which would incur a potentially significant difference in synchronization time than if rendezvous protocol was invoked. // Special arrays for use in the collective -v routines as well as Reduce_scatter. std::vector<int> counts(np,1); std::vector<int> disp(np,0); if (tracker.tag>=9 && tracker.tag<=12) for (int i=1; i<np; i++) disp[i]=disp[i-1]+1; // start synchronization timer for communication routine tracker.start_time = MPI_Wtime(); switch (tracker.tag){ case 0: PMPI_Barrier(tracker.comm); break; case 1: PMPI_Bcast(&synch_pad_send[0], 1, MPI_CHAR, 0, tracker.comm);// arbitrary root 0 break; case 2: PMPI_Reduce(&synch_pad_send[0], &synch_pad_recv[0], 1, MPI_CHAR, MPI_MAX, 0, tracker.comm);// arbitrary root 0 break; case 3: PMPI_Allreduce(MPI_IN_PLACE, &synch_pad_send[0], 1, MPI_CHAR, MPI_MAX, tracker.comm); break; case 4: PMPI_Gather(&synch_pad_send[0], 1, MPI_CHAR, &synch_pad_recv[0], 1, MPI_CHAR, 0, tracker.comm);// arbitrary root 0 break; case 5: PMPI_Allgather(&synch_pad_send[0], 1, MPI_CHAR, &synch_pad_recv[0], 1, MPI_CHAR, tracker.comm); break; case 6: PMPI_Scatter(&synch_pad_send[0], 1, MPI_CHAR, &synch_pad_recv[0], 1, MPI_CHAR, 0, tracker.comm);// arbitrary root 0 break; case 7: PMPI_Reduce_scatter(&synch_pad_send[0], &synch_pad_recv[0], &counts[0], MPI_CHAR, MPI_MAX, tracker.comm); break; case 8: PMPI_Alltoall(&synch_pad_send[0], 1, MPI_CHAR, &synch_pad_recv[0], 1, MPI_CHAR, tracker.comm); break; case 9: PMPI_Gatherv(&synch_pad_send[0], 1, MPI_CHAR, &synch_pad_recv[0], &counts[0], &disp[0], MPI_CHAR, 0, tracker.comm);// arbitrary root 0 break; case 10: PMPI_Allgatherv(&synch_pad_send[0], 1, MPI_CHAR, &synch_pad_recv[0], &counts[0], &disp[0], MPI_CHAR, tracker.comm); break; case 11: PMPI_Scatterv(&synch_pad_send[0], &counts[0], &disp[0], MPI_CHAR, &synch_pad_recv[0], 1, MPI_CHAR, 0, tracker.comm);// arbitrary root 0 break; case 12: PMPI_Alltoallv(&synch_pad_send[0], &counts[0], &disp[0], MPI_CHAR, &synch_pad_recv[0], &counts[0], &disp[0], MPI_CHAR, tracker.comm); break; } tracker.synch_time = MPI_Wtime()-tracker.start_time; } void* temp_buf; int temp_size; MPI_Buffer_detach(&temp_buf,&temp_size); // start communication timer for communication routine tracker.start_time = MPI_Wtime(); return true; } void path::complete_comm(blocking& tracker){ volatile auto comm_time = MPI_Wtime() - tracker.start_time; // complete communication time int rank; MPI_Comm_rank(tracker.comm, &rank); MPI_Buffer_attach(&eager_pad[0],eager_pad.size()); // Save kernel information if (autotuning_debug == 1){ assert(comm_channel_map.find(tracker.comm) != comm_channel_map.end()); int comm_sizes[2]={0,0}; int comm_strides[2]={0,0}; for (auto i=0; i<comm_channel_map[tracker.comm]->id.size(); i++){ comm_sizes[i]=comm_channel_map[tracker.comm]->id[i].first; comm_strides[i]=comm_channel_map[tracker.comm]->id[i].second; } comm_kernel_key key(rank,-1,tracker.tag,comm_sizes,comm_strides,tracker.nbytes,tracker.partner1); if (comm_kernel_info.find(key) == comm_kernel_info.end()){ comm_kernel_info[key] = std::make_pair(1,comm_time); } else{ comm_kernel_info[key].first++; comm_kernel_info[key].second += comm_time; } } std::pair<float,float> cost = cost_model == 0 ? tracker.cost_func_bsp(tracker.nbytes, tracker.comm_size) : tracker.cost_func_alphabeta(tracker.nbytes, tracker.comm_size); // Decompose measurements along multiple paths by MPI routine. *tracker.my_synch_time += tracker.synch_time; *tracker.my_comm_time += comm_time; *tracker.my_msg_count += cost.first; *tracker.my_wrd_count += cost.second; for (size_t i=0; i<path_count; i++){ *(tracker.cp_synch_time+i) += tracker.synch_time; *(tracker.cp_comm_time+i) += comm_time; *(tracker.cp_msg_count+i) += cost.first; *(tracker.cp_wrd_count+i) += cost.second; } // Decompose measurements along multiple paths by symbol if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ for (auto i=0; i<path_count; i++){ // update all communication-related measures for the top symbol in stack for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == 0){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += cost.second; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += cost.second; } else if (path_measure_index[j] == 1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += cost.second; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += cost.second; } else if (path_measure_index[j] == path_measure_select.size()-4){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comm_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comm_time; } else if (path_measure_index[j] == path_measure_select.size()-3){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += tracker.synch_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += tracker.synch_time; } else if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comm_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comm_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[0] += cost.second; symbol_timers[symbol_stack.top()].pp_excl_measure[0] += cost.second; symbol_timers[symbol_stack.top()].pp_exclusive_measure[1] += cost.first; symbol_timers[symbol_stack.top()].pp_excl_measure[1] += cost.first; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-4] += comm_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-4] += comm_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-3] += tracker.synch_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-3] += tracker.synch_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += comm_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += comm_time; if (include_barrier_time){ symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += tracker.barrier_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += tracker.barrier_time; } } // Update measurements that define the critical path for each metric. cp_costs[num_cp_measures-8] += cost.second; cp_costs[num_cp_measures-7] += cost.first; cp_costs[num_cp_measures-5] += comm_time; cp_costs[num_cp_measures-4] += tracker.synch_time; cp_costs[num_cp_measures-1] += comm_time; vol_costs[num_vol_measures-9] += cost.second; vol_costs[num_vol_measures-8] += cost.first; vol_costs[num_vol_measures-6] += tracker.barrier_time;// Note this will be a bit high, as it includes time for last process to enter vol_costs[num_vol_measures-5] += comm_time; vol_costs[num_vol_measures-4] += tracker.synch_time; vol_costs[num_vol_measures-1] += comm_time; if (include_barrier_time){ vol_costs[num_vol_measures-1] += tracker.barrier_time; } // Note that this block of code below is left in solely for blocking communication to avoid over-counting the idle time // If per-process execution-time gets larger than execution-time along the execution-time critical path, // subtract out the difference from idle time. auto path_diff = vol_costs[num_vol_measures-1]-cp_costs[num_cp_measures-1]; if (include_barrier_time==0) path_diff += vol_costs[num_vol_measures-6]; vol_costs[num_vol_measures-6] -= std::max((float)0.,path_diff); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ // Special handling of excessively large idle time caused by suspected tool interference // Specifically, this interference is caused by not subtracting out the barrier time of the last process to enter the barrier (which ideally is 0). if (include_barrier_time){ symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] -= std::max((float)0.,path_diff); symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] -= std::max((float)0.,path_diff); symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-6] -= std::max((float)0.,path_diff); symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-6] -= std::max((float)0.,path_diff); } } // Due to granularity of timing, if a per-process measure ever gets more expensive than a critical path measure, we set the per-process measure to the cp measure for (int i=1; i<=5; i++){ vol_costs[num_vol_measures-i] = std::min(vol_costs[num_vol_measures-i],cp_costs[num_cp_measures-i]); } propagate(tracker); void* temp_buf; int temp_size; MPI_Buffer_detach(&temp_buf,&temp_size); // Prepare to leave interception and re-enter user code by restarting computation timers. bsp_counter++; computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } } // Called by both nonblocking p2p and nonblocking collectives bool path::initiate_comm(nonblocking& tracker, volatile double curtime, int64_t nelem, MPI_Datatype t, MPI_Comm comm, bool is_sender, int partner, int user_tag){ // Check for conflicting communication tag(s) if (partner != -1) assert(!(user_tag >= internal_tag && user_tag <= internal_tag5)); tracker.comp_time = curtime - computation_timer; cp_costs[num_cp_measures-3] += tracker.comp_time; cp_costs[num_cp_measures-1] += tracker.comp_time; vol_costs[num_vol_measures-3] += tracker.comp_time; vol_costs[num_vol_measures-1] += tracker.comp_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-1-i-path_count] += tracker.comp_time; } } if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ auto last_symbol_time = curtime - symbol_timers[symbol_stack.top()].start_timer.top(); for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } else if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += last_symbol_time; } // Note: routine below will be called immediately afterward. return true; } // Called by both nonblocking p2p and nonblocking collectives void path::initiate_comm(nonblocking& tracker, volatile double itime, int64_t nelem, MPI_Datatype t, MPI_Comm comm, MPI_Request* request, bool is_sender, int partner, int user_tag){ // Check for conflicting communication tag(s) if (partner != -1) assert(!(user_tag >= internal_tag && user_tag <= internal_tag5)); // Deal with computational cost at the beginning, but don't synchronize to find computation-critical path-path yet or that will screw up calculation of overlap! tracker.comp_time = itime; cp_costs[num_cp_measures-3] += tracker.comp_time; cp_costs[num_cp_measures-1] += tracker.comp_time; vol_costs[num_vol_measures-3] += tracker.comp_time; vol_costs[num_vol_measures-1] += tracker.comp_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-1-i-path_count] += tracker.comp_time; } } if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ auto last_symbol_time = itime; for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } else if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += last_symbol_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += last_symbol_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += last_symbol_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += last_symbol_time; } int rank; MPI_Comm_rank(comm,&rank); int el_size,p; MPI_Type_size(t, &el_size); int64_t nbytes = el_size * nelem; MPI_Comm_size(comm, &p); MPI_Buffer_attach(&eager_pad[0],eager_pad.size()); MPI_Request barrier_req = MPI_REQUEST_NULL;// Only necessary for nonblocking receives // Issue the barrier call, regardless of msg size // Note that this is only necessary due to blocking+nonblocking p2p communication // Therefore, nonblocking collectives need not participate in the barrier call if (partner!=-1){// Branch protects against nonblocking collectives if (is_sender && rank != partner){ PMPI_Bsend(&barrier_pad_send, 1, MPI_CHAR, partner, internal_tag3, comm); } else if (!is_sender && rank != partner){ PMPI_Irecv(&barrier_pad_recv, 1, MPI_CHAR, partner, internal_tag3, comm, &barrier_req); } } tracker.comm = comm; tracker.is_sender = is_sender; tracker.partner1 = partner; tracker.partner2 = -1; tracker.comm_size = p; tracker.nbytes = nbytes; MPI_Request prop_req = MPI_REQUEST_NULL; float* path_data = nullptr; propagate(tracker,path_data,&prop_req); nonblocking_info msg_info(path_data,barrier_req,prop_req,is_sender,partner,comm,(float)nbytes,(float)p,&tracker); nonblocking_internal_info[*request] = msg_info; void* temp_buf; int temp_size; MPI_Buffer_detach(&temp_buf,&temp_size); computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } } void path::complete_comm(double comp_time){ cp_costs[num_cp_measures-3] += comp_time; cp_costs[num_cp_measures-1] += comp_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-1-i-path_count] += comp_time; } } vol_costs[num_vol_measures-3] += comp_time; vol_costs[num_vol_measures-1] += comp_time; // Decompose measurements along multiple paths by symbol if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comp_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comp_time; } else if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comp_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comp_time; } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += comp_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += comp_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += comp_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += comp_time; } } void path::complete_comm(nonblocking& tracker, MPI_Request* request, double comp_time, double comm_time){ auto info_it = nonblocking_internal_info.find(*request); assert(info_it != nonblocking_internal_info.end()); tracker.is_sender = info_it->second.is_sender; tracker.comm = info_it->second.comm; tracker.partner1 = info_it->second.partner; tracker.partner2 = -1; tracker.nbytes = info_it->second.nbytes; tracker.comm_size = info_it->second.comm_size; tracker.synch_time=0; int rank; MPI_Comm_rank(tracker.comm, &rank); if (autotuning_debug == 1){ assert(comm_channel_map.find(tracker.comm) != comm_channel_map.end()); int comm_sizes[2]={0,0}; int comm_strides[2]={0,0}; for (auto i=0; i<comm_channel_map[tracker.comm]->id.size(); i++){ comm_sizes[i]=comm_channel_map[tracker.comm]->id[i].first; comm_strides[i]=comm_channel_map[tracker.comm]->id[i].second; } comm_kernel_key key(rank,-1,tracker.tag,comm_sizes,comm_strides,tracker.nbytes,tracker.partner1); if (comm_kernel_info.find(key) == comm_kernel_info.end()){ comm_kernel_info[key] = std::make_pair(1,comm_time); } else{ comm_kernel_info[key].first++; comm_kernel_info[key].second += comm_time; } } std::pair<float,float> cost = cost_model == 0 ? tracker.cost_func_bsp(tracker.nbytes, tracker.comm_size) : tracker.cost_func_alphabeta(tracker.nbytes, tracker.comm_size); if (!is_first_request && cost_model==0) cost.first = 0; // Update measurements that define the critical path for each metric. cp_costs[0] += cost.second; cp_costs[1] += cost.first; cp_costs[num_cp_measures-5] += comm_time; cp_costs[num_cp_measures-4] += 0.; cp_costs[num_cp_measures-3] += comp_time; cp_costs[num_cp_measures-1] += comp_time+comm_time; if (path_decomposition == 1){ for (size_t i=0; i<path_count; i++){ cp_costs[cp_costs_size-1-i-path_count] += comp_time; } } vol_costs[0] += cost.second; vol_costs[1] += cost.first; vol_costs[num_vol_measures-5] += comm_time; vol_costs[num_vol_measures-3] += comp_time; vol_costs[num_vol_measures-1] += comp_time+comm_time; // Due to granularity of timing, if a per-process measure ever gets more expensive than a critical path measure, we set the per-process measure to the cp measure for (int i=1; i<=5; i++){ vol_costs[num_vol_measures-i] = std::min(vol_costs[num_vol_measures-i],cp_costs[num_cp_measures-i]); } // Decompose measurements along multiple paths by MPI routine. // Accumuate MPI routine-local measurements. The "my_..." members will never modify the accumulations, while the "cp_..." will first accumulate before path propagation. *tracker.my_synch_time += 0; *tracker.my_comm_time += comm_time; *tracker.my_msg_count += cost.first; *tracker.my_wrd_count += cost.second; for (size_t i=0; i<path_count; i++){ *(tracker.cp_synch_time+i) += tracker.synch_time; *(tracker.cp_comm_time+i) += comm_time; *(tracker.cp_msg_count+i) += cost.first; *(tracker.cp_wrd_count+i) += cost.second; } // Decompose measurements along multiple paths by symbol if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ for (auto i=0; i<path_count; i++){ for (auto j=0; j<path_measure_index.size(); j++){ if (path_measure_index[j] == 0){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += cost.second; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += cost.second; } else if (path_measure_index[j] == 1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += cost.first; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += cost.first; } else if (path_measure_index[j] == path_measure_select.size()-4){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comm_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comm_time; } else if (path_measure_index[j] == path_measure_select.size()-2){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += comp_time; symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += comp_time; } else if (path_measure_index[j] == path_measure_select.size()-1){ symbol_timers[symbol_stack.top()].cp_exclusive_measure[i][j] += (comp_time+comm_time); symbol_timers[symbol_stack.top()].cp_excl_measure[i][j] += (comp_time+comm_time); } } } symbol_timers[symbol_stack.top()].pp_exclusive_measure[0] += cost.second; symbol_timers[symbol_stack.top()].pp_exclusive_measure[1] += cost.first; symbol_timers[symbol_stack.top()].pp_excl_measure[0] += cost.second; symbol_timers[symbol_stack.top()].pp_excl_measure[1] += cost.first; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-4] += comm_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-2] += comp_time; symbol_timers[symbol_stack.top()].pp_exclusive_measure[num_decomp_pp_measures-1] += (comp_time+comm_time); symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-4] += comm_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-2] += comp_time; symbol_timers[symbol_stack.top()].pp_excl_measure[num_decomp_pp_measures-1] += (comp_time+comm_time); } nonblocking_internal_info.erase(*request); } int path::complete_comm(double curtime, MPI_Request* request, MPI_Status* status, int is_test, int* flag){ auto comp_time = curtime - computation_timer; int ret = MPI_SUCCESS; auto info_it = nonblocking_internal_info.find(*request); assert(info_it != nonblocking_internal_info.end()); MPI_Request save_request = info_it->first; volatile auto last_start_time = MPI_Wtime(); if (is_test == 0) ret = PMPI_Wait(request, status); else{ ret = PMPI_Test(request,flag,status); if (*flag == 0){ auto save_comm_time = MPI_Wtime() - last_start_time; complete_comm(save_comm_time+comp_time); computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } } auto save_comm_time = MPI_Wtime() - last_start_time; int rank; MPI_Comm_rank(info_it->second.track->comm,&rank); if (rank != info_it->second.partner){ // If receiver or collective, complete the barrier and the path data propagation if (!info_it->second.is_sender || info_it->second.partner==-1){ assert(info_it->second.path_data != nullptr); MPI_Request req_array[] = {info_it->second.barrier_req, info_it->second.prop_req}; PMPI_Waitall(2, &req_array[0], MPI_STATUSES_IGNORE); if (path_decomposition <= 1) update_cp_decomp1(info_it->second.path_data,&cp_costs[0],cp_costs_size); else if (path_decomposition == 2) update_cp_decomp2(info_it->second.path_data,&cp_costs[0],cp_costs_size); if (info_it->second.path_data != nullptr) free(info_it->second.path_data); if (info_it->second.partner == MPI_ANY_SOURCE) { info_it->second.track->partner1 = status->MPI_SOURCE; } } } complete_comm(*info_it->second.track, &save_request, comp_time, save_comm_time); computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } int path::complete_comm(double curtime, int count, MPI_Request array_of_requests[], int* indx, MPI_Status* status, int is_test, int* flag){ auto comp_time = curtime - computation_timer; int ret = MPI_SUCCESS; // We must save the requests before the completition of a request by the MPI implementation // because its tag is set to MPI_REQUEST_NULL and lost forever std::vector<MPI_Request> pt(count); for (int i=0;i<count;i++){pt[i]=(array_of_requests)[i];} volatile auto last_start_time = MPI_Wtime(); if (is_test == 0) ret = PMPI_Waitany(count,array_of_requests,indx,status); else{ ret = PMPI_Testany(count,array_of_requests,indx,flag,status); if (*flag == 0){ auto save_comm_time = MPI_Wtime() - last_start_time; complete_comm(save_comm_time+comp_time); computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } } auto waitany_comm_time = MPI_Wtime() - last_start_time; MPI_Request request = pt[*indx]; auto info_it = nonblocking_internal_info.find(request); assert(info_it != nonblocking_internal_info.end()); int rank; MPI_Comm_rank(info_it->second.track->comm,&rank); if (rank != info_it->second.partner){ // If receiver, complete the barrier and the path data propagation if (!info_it->second.is_sender || info_it->second.partner==-1){ assert(info_it->second.path_data != nullptr); MPI_Request req_array[] = {info_it->second.barrier_req, info_it->second.prop_req}; PMPI_Waitall(2, &req_array[0], MPI_STATUSES_IGNORE); if (path_decomposition <= 1) update_cp_decomp1(info_it->second.path_data,&cp_costs[0],cp_costs_size); else if (path_decomposition == 2) update_cp_decomp2(info_it->second.path_data,&cp_costs[0],cp_costs_size); if (info_it->second.path_data != nullptr) free(info_it->second.path_data); if (info_it->second.partner == MPI_ANY_SOURCE) { info_it->second.track->partner1 = status->MPI_SOURCE; } } } complete_comm(*info_it->second.track, &request, comp_time, waitany_comm_time); computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } int path::complete_comm(double curtime, int incount, MPI_Request array_of_requests[], int* outcount, int array_of_indices[], MPI_Status array_of_statuses[], int is_test){ auto waitsome_comp_time = curtime - computation_timer; int ret = MPI_SUCCESS; is_first_request=true; // We must save the requests before the completition of a request by the MPI implementation // because its tag is set to MPI_REQUEST_NULL and lost forever std::vector<MPI_Request> pt(incount); for (int i=0;i<incount;i++){pt[i]=(array_of_requests)[i];} volatile auto last_start_time = MPI_Wtime(); if (is_test == 0) ret = PMPI_Waitsome(incount,array_of_requests,outcount,array_of_indices,array_of_statuses); else{ ret = PMPI_Testsome(incount,array_of_requests,outcount,array_of_indices,array_of_statuses); if (*outcount == 0){ auto save_comm_time = MPI_Wtime() - last_start_time; complete_comm(save_comm_time+waitsome_comp_time); computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } } auto waitsome_comm_time = MPI_Wtime() - last_start_time; for (int i=0; i<*outcount; i++){ MPI_Request request = pt[(array_of_indices)[i]]; auto info_it = nonblocking_internal_info.find(request); assert(info_it != nonblocking_internal_info.end()); int rank; MPI_Comm_rank(info_it->second.track->comm,&rank); if (rank != info_it->second.partner){ // If receiver, complete the barrier and the path data propagation if (!info_it->second.is_sender || info_it->second.partner==-1){ assert(info_it->second.path_data != nullptr); MPI_Request req_array[] = {info_it->second.barrier_req, info_it->second.prop_req}; PMPI_Waitall(2, &req_array[0], MPI_STATUSES_IGNORE); if (path_decomposition <= 1) update_cp_decomp1(info_it->second.path_data,&cp_costs[0],cp_costs_size); else if (path_decomposition == 2) update_cp_decomp2(info_it->second.path_data,&cp_costs[0],cp_costs_size); if (info_it->second.path_data != nullptr) free(info_it->second.path_data); if (info_it->second.partner == MPI_ANY_SOURCE) { info_it->second.track->partner1 = (array_of_statuses)[i].MPI_SOURCE; } } } complete_comm(*info_it->second.track, &request, waitsome_comp_time, waitsome_comm_time); waitsome_comp_time=0; waitsome_comm_time=0; is_first_request=false; } computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } int path::complete_comm(double curtime, int count, MPI_Request array_of_requests[], MPI_Status array_of_statuses[], int is_test, int* flag){ auto waitall_comp_time = curtime - computation_timer; int ret = MPI_SUCCESS; is_first_request=true; // We must save the requests before the completition of a request by the MPI implementation // because its tag is set to MPI_REQUEST_NULL and lost forever std::vector<MPI_Request> pt(count); for (int i=0;i<count;i++){pt[i]=(array_of_requests)[i];} volatile auto last_start_time = MPI_Wtime(); if (is_test == 0) ret = PMPI_Waitall(count,array_of_requests,array_of_statuses); else{ ret = PMPI_Testall(count,array_of_requests,flag,array_of_statuses); if (*flag == 0){ auto save_comm_time = MPI_Wtime() - last_start_time; complete_comm(save_comm_time+waitall_comp_time); computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } } auto waitall_comm_time = MPI_Wtime() - last_start_time; for (int i=0; i<count; i++){ MPI_Request request = pt[i]; auto info_it = nonblocking_internal_info.find(request); assert(info_it != nonblocking_internal_info.end()); int rank; MPI_Comm_rank(info_it->second.track->comm,&rank); if (rank != info_it->second.partner){ // If receiver, complete the barrier and the path data propagation if (!info_it->second.is_sender || info_it->second.partner==-1){ assert(info_it->second.path_data != nullptr); MPI_Request req_array[] = {info_it->second.barrier_req, info_it->second.prop_req}; PMPI_Waitall(2, &req_array[0], MPI_STATUSES_IGNORE); if (path_decomposition <= 1) update_cp_decomp1(info_it->second.path_data,&cp_costs[0],cp_costs_size); else if (path_decomposition == 2) update_cp_decomp2(info_it->second.path_data,&cp_costs[0],cp_costs_size); if (info_it->second.path_data != nullptr) free(info_it->second.path_data); if (info_it->second.partner == MPI_ANY_SOURCE) { info_it->second.track->partner1 = (array_of_statuses)[i].MPI_SOURCE; } } } complete_comm(*info_it->second.track, &request, waitall_comp_time, waitall_comm_time); // Although we have to exchange the path data for each request, we do not want to float-count the computation time nor the communicaion time waitall_comp_time=0; waitall_comm_time=0; is_first_request=false; } computation_timer = MPI_Wtime(); if (path_decomposition == 2 && path_count>0 && symbol_stack.size()>0){ symbol_timers[symbol_stack.top()].start_timer.top() = computation_timer; } return ret; } void path::propagate(blocking& tracker){ int rank; MPI_Comm_rank(tracker.comm,&rank); if ((rank == tracker.partner1) && (rank == tracker.partner2)) { return; } // Exchange the tracked routine critical path data if (tracker.partner1 == -1){ MPI_Op op; if (path_decomposition <= 1) MPI_Op_create((MPI_User_function*) propagate_cp_decomp1_op,0,&op); else if (path_decomposition == 2) MPI_Op_create((MPI_User_function*) propagate_cp_decomp2_op,0,&op); PMPI_Allreduce(MPI_IN_PLACE, &cp_costs[0], cp_costs.size(), MPI_FLOAT, op, tracker.comm); MPI_Op_free(&op); } else{ if (tracker.is_sender){ PMPI_Bsend(&cp_costs[0], cp_costs.size(), MPI_FLOAT, tracker.partner1, internal_tag2, tracker.comm); } else{ PMPI_Recv(&cp_costs_foreign[0], cp_costs.size(), MPI_FLOAT, tracker.partner1, internal_tag2, tracker.comm, MPI_STATUS_IGNORE); if (path_decomposition <= 1) update_cp_decomp1(&cp_costs_foreign[0],&cp_costs[0],cp_costs_size); else if (path_decomposition == 2) update_cp_decomp2(&cp_costs_foreign[0],&cp_costs[0],cp_costs_size); } if (tracker.partner2 != tracker.partner1){ PMPI_Recv(&cp_costs_foreign[0], cp_costs.size(), MPI_FLOAT, tracker.partner2, internal_tag2, tracker.comm, MPI_STATUS_IGNORE); if (path_decomposition <= 1) update_cp_decomp1(&cp_costs_foreign[0],&cp_costs[0],cp_costs_size); else if (path_decomposition == 2) update_cp_decomp2(&cp_costs_foreign[0],&cp_costs[0],cp_costs_size); } } } void path::propagate(nonblocking& tracker, float*& path_data, MPI_Request* prop_req){ int rank; MPI_Comm_rank(tracker.comm,&rank); if (rank == tracker.partner1) { return; } // Exchange the tracked routine critical path data if (tracker.partner1 == -1){ MPI_Op op; if (path_decomposition <= 1) MPI_Op_create((MPI_User_function*) propagate_cp_decomp1_op,0,&op); else if (path_decomposition == 2) MPI_Op_create((MPI_User_function*) propagate_cp_decomp2_op,0,&op); path_data = (float*)malloc(cp_costs.size()*sizeof(float)); std::memcpy(path_data, &cp_costs[0], cp_costs.size()*sizeof(float)); PMPI_Iallreduce(MPI_IN_PLACE,path_data,cp_costs.size(),MPI_FLOAT,op,tracker.comm,prop_req); //MPI_Op_free(&op); } else{ if (tracker.is_sender){ PMPI_Bsend(&cp_costs[0], cp_costs.size(), MPI_FLOAT, tracker.partner1, internal_tag2, tracker.comm); } else{ path_data = (float*)malloc(cp_costs.size()*sizeof(float)); PMPI_Irecv(path_data, cp_costs.size(), MPI_FLOAT, tracker.partner1, internal_tag2, tracker.comm, prop_req); } } } } } }
50,009
18,831