file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestString.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "../test/util.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestString : public unittest_util::AXTestCase { public: void setUp() override { unittest_util::AXTestCase::setUp(); } CPPUNIT_TEST_SUITE(TestString); CPPUNIT_TEST(testAssignCompound); CPPUNIT_TEST(testAssignFromAttributes); CPPUNIT_TEST(testAssignFromLocals); CPPUNIT_TEST(testAssignNewOverwrite); CPPUNIT_TEST(testBinaryConcat); CPPUNIT_TEST(testDeclare); CPPUNIT_TEST_SUITE_END(); void testAssignCompound(); void testAssignFromAttributes(); void testAssignFromLocals(); void testAssignNewOverwrite(); void testBinaryConcat(); void testDeclare(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestString); void TestString::testAssignCompound() { mHarness.addAttributes<std::string>(unittest_util::nameSequence("test", 3), {"foo", "foobar", "aaaaaaaaaa"}); mHarness.executeCode("test/snippets/string/assignCompound"); AXTESTS_STANDARD_ASSERT(); } void TestString::testAssignFromAttributes() { mHarness.addInputPtAttributes<std::string>({"string_test1"}, {"test"}); mHarness.addExpectedAttributes<std::string>(unittest_util::nameSequence("string_test", 6), {"new value", "test", "new value", "new value", "", ""}); // Volume data needs to exist mHarness.addInputVolumes<std::string>(unittest_util::nameSequence("string_test", 6), {"test", "test", "new value", "new value", "", ""}); mHarness.executeCode("test/snippets/string/assignFromAttributes", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestString::testAssignFromLocals() { mHarness.addAttributes<std::string>(unittest_util::nameSequence("string_test", 4), {"test", "test", "new string size", ""}); mHarness.executeCode("test/snippets/string/assignFromLocals"); AXTESTS_STANDARD_ASSERT(); } void TestString::testAssignNewOverwrite() { mHarness.addExpectedAttributes<std::string>({"string_test1", "string_test2"}, {"next_value", "new_value"}); // Volume data needs to exist mHarness.addInputVolumes<std::string>({"string_test1", "string_test2"}, {"next_value", "new_value"}); mHarness.executeCode("test/snippets/string/assignNewOverwrite", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestString::testBinaryConcat() { mHarness.addExpectedAttributes<std::string>(unittest_util::nameSequence("string_test", 6), {"test new value", "test new value", "test new value", "test new value", "", "test new value"}); // Volume data needs to exist mHarness.addInputVolumes<std::string>(unittest_util::nameSequence("string_test", 6), {"test new value", "test new value", "test new value", "test new value", "", "test new value"}); mHarness.executeCode("test/snippets/string/binaryConcat", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestString::testDeclare() { mHarness.addAttribute<std::string>("string_test", "test"); mHarness.executeCode("test/snippets/string/declare"); AXTESTS_STANDARD_ASSERT(); }
3,224
C++
30.009615
104
0.695099
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestArrayUnpack.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "CompareGrids.h" #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestArrayUnpack : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestArrayUnpack); CPPUNIT_TEST(componentVectorAssignment); CPPUNIT_TEST(componentMatrixAssignment); CPPUNIT_TEST_SUITE_END(); void componentVectorAssignment(); void componentMatrixAssignment(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayUnpack); void TestArrayUnpack::componentVectorAssignment() { const std::string code = R"( vec2@test1[0] = vec2@test2[1]; vec2@test2[1] = vec2@test1[0]; vec3@test3[1] = vec3@test3[2]; vec3@test4[2] = vec3@test4[0]; vec3@test3[0] = vec3@test4[1]; vec4@test5[0] = vec4@test6[2]; vec4@test5[3] = vec4@test5[1]; vec4@test5[2] = vec4@test6[3]; vec4@test6[1] = vec4@test6[0]; )"; auto generate = [&](const auto& suffixes) { for (const auto& s : suffixes) { std::string repl = code; const std::string type = (s == 'i' ? "int" : (s == 'f' ? "float" : (s == 'd' ? "double" : ""))); CPPUNIT_ASSERT(!type.empty()); unittest_util::replace(repl, "vec2", std::string("vec2").append(1, s)); unittest_util::replace(repl, "vec3", std::string("vec3").append(1, s)); unittest_util::replace(repl, "vec4", std::string("vec4").append(1, s)); this->registerTest(repl, "array_unpack.vec." + type + ".ax"); unittest_util::replace(repl, "[0]", ".x"); unittest_util::replace(repl, "[1]", ".y"); unittest_util::replace(repl, "[2]", ".z"); this->registerTest(repl, "array_unpack.vec." + type + ".xyz" + ".ax"); unittest_util::replace(repl, ".x", ".r"); unittest_util::replace(repl, ".y", ".g"); unittest_util::replace(repl, ".z", ".b"); this->registerTest(repl, "array_unpack.vec." + type + ".rgb" + ".ax"); } }; generate(std::vector<char>{'i', 'f', 'd'}); const std::map<std::string, std::function<void()>> expected = { { "int", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test1", openvdb::math::Vec2<int32_t>( 1, 2), openvdb::math::Vec2<int32_t>( 4,2)); mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test2", openvdb::math::Vec2<int32_t>( 3, 4), openvdb::math::Vec2<int32_t>( 3, 4)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test3", openvdb::math::Vec3<int32_t>( 5 ,6, 7), openvdb::math::Vec3<int32_t>( 8 ,7, 7)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test4", openvdb::math::Vec3<int32_t>( 9, 8,-1), openvdb::math::Vec3<int32_t>( 9, 8, 9)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test5", openvdb::math::Vec4<int32_t>(-1,-2,-3,-4), openvdb::math::Vec4<int32_t>(-7,-2,-8,-2)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test6", openvdb::math::Vec4<int32_t>(-5,-6,-7,-8), openvdb::math::Vec4<int32_t>(-5,-5,-7,-8)); } }, { "float", [&]() { mHarness.addAttribute<openvdb::math::Vec2<float>>("test1", openvdb::math::Vec2<float>( 1.2f, 2.7f), openvdb::math::Vec2<float>(4.7f, 2.7f)); mHarness.addAttribute<openvdb::math::Vec2<float>>("test2", openvdb::math::Vec2<float>( 3.2f, 4.7f), openvdb::math::Vec2<float>(3.2f ,4.7f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("test3", openvdb::math::Vec3<float>( 5.2f ,6.7f, 7.4f), openvdb::math::Vec3<float>( 8.7f ,7.4f, 7.4f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("test4", openvdb::math::Vec3<float>( 9.2f, 8.7f,-1.4f), openvdb::math::Vec3<float>( 9.2f, 8.7f, 9.2f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("test5", openvdb::math::Vec4<float>(-1.2f,-2.7f,-3.4f,-4.1f), openvdb::math::Vec4<float>(-7.4f,-2.7f,-8.1f,-2.7f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("test6", openvdb::math::Vec4<float>(-5.2f,-6.7f,-7.4f,-8.1f), openvdb::math::Vec4<float>(-5.2f,-5.2f,-7.4f,-8.1f)); } }, { "double", [&]() { mHarness.addAttribute<openvdb::math::Vec2<double>>("test1", openvdb::math::Vec2<double>( 1.2, 2.7), openvdb::math::Vec2<double>(4.7, 2.7)); mHarness.addAttribute<openvdb::math::Vec2<double>>("test2", openvdb::math::Vec2<double>( 3.2, 4.7), openvdb::math::Vec2<double>(3.2, 4.7)); mHarness.addAttribute<openvdb::math::Vec3<double>>("test3", openvdb::math::Vec3<double>( 5.2 ,6.7, 7.4), openvdb::math::Vec3<double>( 8.7 ,7.4, 7.4)); mHarness.addAttribute<openvdb::math::Vec3<double>>("test4", openvdb::math::Vec3<double>( 9.2, 8.7,-1.4), openvdb::math::Vec3<double>( 9.2, 8.7, 9.2)); mHarness.addAttribute<openvdb::math::Vec4<double>>("test5", openvdb::math::Vec4<double>(-1.2,-2.7,-3.4,-4.1), openvdb::math::Vec4<double>(-7.4,-2.7,-8.1,-2.7)); mHarness.addAttribute<openvdb::math::Vec4<double>>("test6", openvdb::math::Vec4<double>(-5.2,-6.7,-7.4,-8.1), openvdb::math::Vec4<double>(-5.2,-5.2,-7.4,-8.1)); } }, }; const std::array<std::string, 3> suffixes {{ "", ".xyz", ".rgb" }}; for (const auto& expc : expected) { for (const auto& suffix : suffixes) { mHarness.reset(); expc.second.operator()(); this->execute("array_unpack.vec." + expc.first + suffix + ".ax"); } } } void TestArrayUnpack::componentMatrixAssignment() { const std::string code = R"( mat3@test1[0] = mat3@test2[4]; mat3@test2[1] = mat3@test1[0]; mat3@test1[2] = mat3@test2[5]; mat3@test2[3] = mat3@test1[6]; mat3@test1[4] = mat3@test2[3]; mat3@test2[5] = mat3@test1[1]; mat3@test1[6] = mat3@test2[7]; mat3@test2[7] = mat3@test1[8]; mat3@test1[8] = mat3@test2[2]; mat3@test3[0,0] = mat3@test4[1,1]; mat3@test4[0,1] = mat3@test3[0,0]; mat3@test3[0,2] = mat3@test4[1,2]; mat3@test4[1,0] = mat3@test3[2,0]; mat3@test3[1,1] = mat3@test4[1,0]; mat3@test4[1,2] = mat3@test3[0,1]; mat3@test3[2,0] = mat3@test4[2,1]; mat3@test4[2,1] = mat3@test3[2,2]; mat3@test3[2,2] = mat3@test4[0,2]; mat4@test5[0] = mat4@test6[15]; mat4@test6[1] = mat4@test5[0]; mat4@test5[2] = mat4@test6[11]; mat4@test6[3] = mat4@test5[6]; mat4@test5[4] = mat4@test6[13]; mat4@test6[5] = mat4@test5[1]; mat4@test5[6] = mat4@test6[10]; mat4@test6[7] = mat4@test5[8]; mat4@test5[8] = mat4@test6[2]; mat4@test6[9] = mat4@test5[7]; mat4@test5[10] = mat4@test6[14]; mat4@test6[11] = mat4@test5[3]; mat4@test5[12] = mat4@test6[4]; mat4@test6[13] = mat4@test5[12]; mat4@test5[14] = mat4@test6[5]; mat4@test6[15] = mat4@test5[9]; mat4@test7[0,0] = mat4@test8[3,3]; mat4@test8[0,1] = mat4@test7[0,0]; mat4@test7[0,2] = mat4@test8[2,3]; mat4@test8[0,3] = mat4@test7[1,2]; mat4@test7[1,0] = mat4@test8[3,1]; mat4@test8[1,1] = mat4@test7[0,1]; mat4@test7[1,2] = mat4@test8[2,2]; mat4@test8[1,3] = mat4@test7[2,0]; mat4@test7[2,0] = mat4@test8[0,2]; mat4@test8[2,1] = mat4@test7[1,3]; mat4@test7[2,2] = mat4@test8[3,2]; mat4@test8[2,3] = mat4@test7[0,3]; mat4@test7[3,0] = mat4@test8[1,0]; mat4@test8[3,1] = mat4@test7[3,0]; mat4@test7[3,2] = mat4@test8[1,1]; mat4@test8[3,3] = mat4@test7[2,1]; )"; auto generate = [&](const auto& suffixes) { for (const auto& s : suffixes) { std::string repl = code; unittest_util::replace(repl, "mat3", std::string("mat3").append(1,s)); unittest_util::replace(repl, "mat4", std::string("mat4").append(1,s)); const std::string type = s == 'f' ? "float" : s == 'd' ? "double" : ""; CPPUNIT_ASSERT(!type.empty()); this->registerTest(repl, "array_unpack.mat." + type + ".ax"); } }; generate(std::vector<char>{'f', 'd'}); const std::map<std::string, std::function<void()>> expected = { { "float", [&]() { mHarness.addAttribute<openvdb::math::Mat3<float>>("test1", openvdb::math::Mat3<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), // in openvdb::math::Mat3<float>(-6.7f, 2.3f, 0.8f, 5.4f, 9.1f, 7.8f, -0.5f, 4.5f,-1.3f)); // expected mHarness.addAttribute<openvdb::math::Mat3<float>>("test2", openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f), openvdb::math::Mat3<float>(9.1f,-6.7f, -1.3f, 9.1f, -6.7f, 2.3f, 9.1f, 8.2f, 8.2f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("test3", openvdb::math::Mat3<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), // in openvdb::math::Mat3<float>(-6.7f, 2.3f, 0.8f, 5.4f, 9.1f, 7.8f, -0.5f, 4.5f,-1.3f)); // expected mHarness.addAttribute<openvdb::math::Mat3<float>>("test4", openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f), openvdb::math::Mat3<float>(9.1f,-6.7f, -1.3f, 9.1f, -6.7f, 2.3f, 9.1f, 8.2f, 8.2f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("test5", openvdb::math::Mat4<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), // in openvdb::math::Mat4<float>(-1.7f, 2.3f, 2.5f, 5.4f, 0.5f, 7.8f,-0.3f, 4.5f, -9.3f, 3.3f, 8.1f, 5.9f, -1.7f, 0.3f, 2.3f, 1.9f)); // expected mHarness.addAttribute<openvdb::math::Mat4<float>>("test6", openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(0.1f,-1.7f,-9.3f, 9.1f, -1.7f, 2.3f, 2.1f, 8.2f, 3.3f, 4.5f,-0.3f, 5.4f, 5.1f,-1.7f, 8.1f, 3.3f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("test7", openvdb::math::Mat4<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), // in openvdb::math::Mat4<float>(-1.7f, 2.3f, 2.5f, 5.4f, 0.5f, 7.8f,-0.3f, 4.5f, -9.3f, 3.3f, 8.1f, 5.9f, -1.7f, 0.3f, 2.3f, 1.9f)); // expected mHarness.addAttribute<openvdb::math::Mat4<float>>("test8", openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(0.1f,-1.7f,-9.3f, 9.1f, -1.7f, 2.3f, 2.1f, 8.2f, 3.3f, 4.5f,-0.3f, 5.4f, 5.1f,-1.7f, 8.1f, 3.3f)); } }, { "double", [&]() { mHarness.addAttribute<openvdb::math::Mat3<double>>("test1", openvdb::math::Mat3<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), // in openvdb::math::Mat3<double>(-6.7, 2.3, 0.8, 5.4, 9.1, 7.8, -0.5, 4.5,-1.3)); // expected mHarness.addAttribute<openvdb::math::Mat3<double>>("test2", openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2), openvdb::math::Mat3<double>(9.1,-6.7, -1.3, 9.1, -6.7, 2.3, 9.1, 8.2, 8.2)); mHarness.addAttribute<openvdb::math::Mat3<double>>("test3", openvdb::math::Mat3<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), // in openvdb::math::Mat3<double>(-6.7, 2.3, 0.8, 5.4, 9.1, 7.8, -0.5, 4.5,-1.3)); // expected mHarness.addAttribute<openvdb::math::Mat3<double>>("test4", openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2), openvdb::math::Mat3<double>(9.1,-6.7, -1.3, 9.1, -6.7, 2.3, 9.1, 8.2, 8.2)); mHarness.addAttribute<openvdb::math::Mat4<double>>("test5", openvdb::math::Mat4<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), // in openvdb::math::Mat4<double>(-1.7, 2.3, 2.5, 5.4, 0.5, 7.8,-0.3, 4.5, -9.3, 3.3, 8.1, 5.9, -1.7, 0.3, 2.3, 1.9)); // expected mHarness.addAttribute<openvdb::math::Mat4<double>>("test6", openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(0.1,-1.7,-9.3, 9.1, -1.7, 2.3, 2.1, 8.2, 3.3, 4.5,-0.3, 5.4, 5.1,-1.7, 8.1, 3.3)); mHarness.addAttribute<openvdb::math::Mat4<double>>("test7", openvdb::math::Mat4<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), // in openvdb::math::Mat4<double>(-1.7, 2.3, 2.5, 5.4, 0.5, 7.8,-0.3, 4.5, -9.3, 3.3, 8.1, 5.9, -1.7, 0.3, 2.3, 1.9)); // expected mHarness.addAttribute<openvdb::math::Mat4<double>>("test8", openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(0.1,-1.7,-9.3, 9.1, -1.7, 2.3, 2.1, 8.2, 3.3, 4.5,-0.3, 5.4, 5.1,-1.7, 8.1, 3.3)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("array_unpack.mat." + expc.first + ".ax"); } }
13,765
C++
52.773437
181
0.537523
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestUnary.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "util.h" #include <cppunit/extensions/HelperMacros.h> class TestUnary : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestUnary); CPPUNIT_TEST(testBitwiseNot); CPPUNIT_TEST(testNegate); CPPUNIT_TEST(testNot); CPPUNIT_TEST(testUnaryVector); CPPUNIT_TEST_SUITE_END(); void testBitwiseNot(); void testNegate(); void testNot(); void testUnaryVector(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestUnary); void TestUnary::testBitwiseNot() { mHarness.addAttributes<int>({"int_test", "int_test2"}, {-9, -8}); mHarness.executeCode("test/snippets/unary/unaryBitwiseNot"); AXTESTS_STANDARD_ASSERT(); } void TestUnary::testNegate() { mHarness.addAttribute<int>("int_test", -3); mHarness.addAttribute<float>("float_test", -5.5f); mHarness.executeCode("test/snippets/unary/unaryNegate"); AXTESTS_STANDARD_ASSERT(); } void TestUnary::testNot() { mHarness.addAttributes<bool>({"bool_test", "bool_test2"}, {false, true}); mHarness.executeCode("test/snippets/unary/unaryNot"); AXTESTS_STANDARD_ASSERT(); } void TestUnary::testUnaryVector() { // vec3 mHarness.addAttributes<openvdb::math::Vec3<int32_t>> (unittest_util::nameSequence("v3i", 4), { openvdb::math::Vec3<int32_t>(0, 1,-1), openvdb::math::Vec3<int32_t>(0,-1, 1), openvdb::math::Vec3<int32_t>(-1,-2,0), openvdb::math::Vec3<int32_t>(1, 0, 0) }); mHarness.addAttributes<openvdb::math::Vec3<float>> (unittest_util::nameSequence("v3f", 2), { openvdb::math::Vec3<float>(0.0f, 1.1f,-1.1f), openvdb::math::Vec3<float>(0.0f,-1.1f, 1.1f), }); mHarness.addAttributes<openvdb::math::Vec3<double>> (unittest_util::nameSequence("v3d", 2), { openvdb::math::Vec3<double>(0.0, 1.1,-1.1), openvdb::math::Vec3<double>(0.0,-1.1, 1.1), }); // vec4 mHarness.addAttributes<openvdb::math::Vec4<int32_t>> (unittest_util::nameSequence("v4i", 4), { openvdb::math::Vec4<int32_t>(0, 1,-1, 2), openvdb::math::Vec4<int32_t>(0,-1, 1, -2), openvdb::math::Vec4<int32_t>(-1,-2,0,-3), openvdb::math::Vec4<int32_t>(1, 0, 0, 0) }); mHarness.addAttributes<openvdb::math::Vec4<float>> (unittest_util::nameSequence("v4f", 2), { openvdb::math::Vec4<float>(0.0f, 1.1f,-1.1f, 2.1f), openvdb::math::Vec4<float>(0.0f,-1.1f, 1.1f, -2.1f) }); mHarness.addAttributes<openvdb::math::Vec4<double>> (unittest_util::nameSequence("v4d", 2), { openvdb::math::Vec4<double>(0.0, 1.1,-1.1, 2.1), openvdb::math::Vec4<double>(0.0,-1.1, 1.1, -2.1) }); mHarness.executeCode("test/snippets/unary/unaryVector"); AXTESTS_STANDARD_ASSERT(); }
2,983
C++
25.882883
77
0.60409
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestLoop.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestLoop : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestLoop); CPPUNIT_TEST(testLoopForLoop); CPPUNIT_TEST(testLoopWhileLoop); CPPUNIT_TEST(testLoopDoWhileLoop); CPPUNIT_TEST(testLoopOverflow); CPPUNIT_TEST(testLoopErrors); CPPUNIT_TEST_SUITE_END(); void testLoopForLoop(); void testLoopWhileLoop(); void testLoopDoWhileLoop(); void testLoopOverflow(); void testLoopErrors(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLoop); void TestLoop::testLoopForLoop() { mHarness.addAttribute<openvdb::Vec3f>("loop_test1", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test2", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test3", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test15", openvdb::Vec3f(0.0,0.0,0.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test18", openvdb::math::Mat3s(1.0,2.0,3.0, 4.0,5.0,6.0, 7.0,8.0,9.0)); mHarness.addAttribute<int32_t>("loop_test22", 3); mHarness.addAttribute<int32_t>("loop_test23", 4); mHarness.addAttribute<int32_t>("loop_test25", 1); mHarness.addAttribute<int32_t>("loop_test27", 14); mHarness.addAttribute<int32_t>("loop_test30", 19); mHarness.executeCode("test/snippets/loop/forLoop"); AXTESTS_STANDARD_ASSERT(); } void TestLoop::testLoopWhileLoop() { mHarness.addAttribute<openvdb::Vec3f>("loop_test9", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test16", openvdb::Vec3f(0.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test28", openvdb::Vec3f(0.0,0.0,0.0)); mHarness.addAttribute<int32_t>("loop_test31", 2); mHarness.executeCode("test/snippets/loop/whileLoop"); AXTESTS_STANDARD_ASSERT(); } void TestLoop::testLoopDoWhileLoop() { mHarness.addAttribute<openvdb::Vec3f>("loop_test12", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test17", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test29", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<int32_t>("loop_test32", 2); mHarness.executeCode("test/snippets/loop/doWhileLoop"); AXTESTS_STANDARD_ASSERT(); } void TestLoop::testLoopOverflow() { // Disable all optimizations to force the loop to not remove the interior // allocation. The loop should generate its allocas in the function prologue // to avoid stack overflow openvdb::ax::CompilerOptions opts; opts.mOptLevel = openvdb::ax::CompilerOptions::OptLevel::NONE; mHarness.mOpts = opts; mHarness.executeCode("test/snippets/loop/loopOverflow"); } void TestLoop::testLoopErrors() { const bool success = mHarness.executeCode("test/snippets/loop/loopErrors"); CPPUNIT_ASSERT(!success); }
3,035
C++
32
86
0.707743
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestConditional.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestConditional : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestConditional); CPPUNIT_TEST(testConditionalIfWithinElse); CPPUNIT_TEST(testConditionalScopingStatement); CPPUNIT_TEST(testConditionalSimpleStatement); CPPUNIT_TEST(testConditionalSimpleElseIf); CPPUNIT_TEST(testConditionalErrors); CPPUNIT_TEST_SUITE_END(); void testConditionalIfWithinElse(); void testConditionalSimpleStatement(); void testConditionalScopingStatement(); void testConditionalSimpleElseIf(); void testConditionalErrors(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestConditional); void TestConditional::testConditionalIfWithinElse() { mHarness.addAttribute<bool>("bool_test", true); mHarness.executeCode("test/snippets/conditional/conditionalIfWithinElse"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalSimpleStatement() { mHarness.addAttribute<bool>("bool_test", true); mHarness.addAttribute<float>("float_test", 1.0f); mHarness.executeCode("test/snippets/conditional/conditionalSimpleStatement"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalScopingStatement() { mHarness.addAttribute<int32_t>("int_test", 1); mHarness.executeCode("test/snippets/conditional/conditionalScopingStatement"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalSimpleElseIf() { mHarness.addAttribute("bool_test", true); mHarness.addAttribute("int_test", 2); mHarness.executeCode("test/snippets/conditional/conditionalSimpleElseIf"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalErrors() { const bool success = mHarness.executeCode("test/snippets/conditional/conditionalErrors"); CPPUNIT_ASSERT(!success); }
1,984
C++
24.448718
93
0.767641
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/CompareGrids.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file test/integration/CompareGrids.h /// /// @authors Francisco Gochez, Nick Avramoussis /// /// @brief Functions for comparing entire VDB grids and generating /// reports on their differences /// #ifndef OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED #define OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED #include <openvdb/openvdb.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/tree/LeafManager.h> #include <openvdb/tools/Prune.h> namespace unittest_util { struct ComparisonSettings { bool mCheckTransforms = true; // Check grid transforms bool mCheckTopologyStructure = true; // Checks node (voxel/leaf/tile) layout bool mCheckActiveStates = true; // Checks voxel active states match bool mCheckBufferValues = true; // Checks voxel buffer values match bool mCheckDescriptors = true; // Check points leaf descriptors bool mCheckArrayValues = true; // Checks attribute array sizes and values bool mCheckArrayFlags = true; // Checks attribute array flags }; /// @brief The results collected from compareGrids() /// struct ComparisonResult { ComparisonResult(std::ostream& os = std::cout) : mOs(os) , mDifferingTopology(openvdb::MaskGrid::create()) , mDifferingValues(openvdb::MaskGrid::create()) {} std::ostream& mOs; openvdb::MaskGrid::Ptr mDifferingTopology; // Always empty if mCheckActiveStates is false openvdb::MaskGrid::Ptr mDifferingValues; // Always empty if mCheckBufferValues is false // or if mCheckBufferValues and mCheckArrayValues // is false for point data grids }; template <typename GridType> bool compareGrids(ComparisonResult& resultData, const GridType& firstGrid, const GridType& secondGrid, const ComparisonSettings& settings, const openvdb::MaskGrid::ConstPtr maskGrid, const typename GridType::ValueType tolerance = openvdb::zeroVal<typename GridType::ValueType>()); bool compareUntypedGrids(ComparisonResult& resultData, const openvdb::GridBase& firstGrid, const openvdb::GridBase& secondGrid, const ComparisonSettings& settings, const openvdb::MaskGrid::ConstPtr maskGrid); } // namespace unittest_util #endif // OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED
2,627
C
36.014084
96
0.660069
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestAssign.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "CompareGrids.h" #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; // Configuration values for assignment code using ConfigMap = std::unordered_map<std::string, std::unordered_map<std::string, std::string>>; static const ConfigMap integral = { { "bool", { { "_l1_", "true" }, { "_l2_", "false" } } }, { "int32", { { "_l1_", "2" }, { "_l2_", "3" } } }, { "int64", { { "_l1_", "2l" }, { "_l2_", "3l" } } } }; static const ConfigMap floating = { { "float", { { "_l1_", "1.1f" }, { "_l2_", "2.3f" } } }, { "double", { { "_l1_", "1.1" }, { "_l2_", "2.3" } } } }; static const ConfigMap vec2 = { { "vec2i", { { "_l1_", "{1, 2}" }, { "_l2_", "{3, 4}" } } }, { "vec2f", { { "_l1_", "{1.1f, 2.3f}" }, { "_l2_", "{4.1f, 5.3f}" } } }, { "vec2d", { { "_l1_", "{1.1, 2.3}" }, { "_l2_", "{4.1, 5.3}" } } } }; static const ConfigMap vec3 = { { "vec3i", { { "_l1_", "{1, 2, 3}" }, { "_l2_", "{4, 5, 6}" } } }, { "vec3f", { { "_l1_", "{1.1f, 2.3f, 4.3f}" }, { "_l2_", "{4.1f, 5.3f, 6.3f}" } } }, { "vec3d", { { "_l1_", "{1.1, 2.3 , 4.3}" }, { "_l2_", "{4.1, 5.3, 6.3}" } } } }; static const ConfigMap vec4 = { { "vec4i", { { "_l1_", "{1, 2, 3, 4}" }, { "_l2_", "{5, 6, 7, 8}" } } }, { "vec4f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f}" }, { "_l2_", "{5.1f, 6.3f, 7.3f, 8.4f}" } } }, { "vec4d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4}" }, { "_l2_", "{5.1, 6.3, 7.3, 8.4}" } } } }; static const ConfigMap mat3 = { { "mat3f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f }" }, { "_l2_", "{9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f }" } } }, { "mat3d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2 }" }, { "_l2_", "{9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2 }" } } } }; static const ConfigMap mat4 = { { "mat4f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f}" }, { "_l2_", "{0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f}" } } }, { "mat4d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9}" }, { "_l2_", "{0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7}" } } } }; static const ConfigMap string = { { "string", { { "_l1_", "\"foo\"" }, { "_l2_", "\"bar\"" } } } }; // class TestAssign : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestAssign); CPPUNIT_TEST(directAssignment); CPPUNIT_TEST(compoundIntegralAssignment); CPPUNIT_TEST(compoundFloatingAssignment); CPPUNIT_TEST(compoundVectorAssignment); CPPUNIT_TEST(compoundMatrixAssignment); CPPUNIT_TEST(compoundStringAssignment); CPPUNIT_TEST(implicitScalarAssignment); CPPUNIT_TEST(implicitContainerAssignment); CPPUNIT_TEST(implicitContainerScalarAssignment); CPPUNIT_TEST(scopedAssign); CPPUNIT_TEST_SUITE_END(); void directAssignment(); void compoundIntegralAssignment(); void compoundFloatingAssignment(); void compoundVectorAssignment(); void compoundMatrixAssignment(); void compoundStringAssignment(); void implicitScalarAssignment(); void implicitContainerAssignment(); void implicitContainerScalarAssignment(); void scopedAssign(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAssign); void TestAssign::directAssignment() { const std::string code = R"( _T1_@test1 = _l1_; _T1_ local1 = _l1_; _T1_@test2 = local1; _T1_@test3 = _T1_@test4 = _T1_@test2; _T1_ local3, local2 = _l2_; _T1_@test5 = local3 = local2; _T1_@test6 = _l2_, _T1_@test7 = _l1_; _T1_@test8 = _l2_; _T1_@test8 = _l1_; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign." + config.first + ".ax"); } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); generate(string); const auto names = unittest_util::nameSequence("test", 8); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttributes<bool>(names, { true, true, true, true, false, false, true, true }); }, }, { "int32", [&](){ mHarness.addAttributes<int32_t>(names, { 2, 2, 2, 2, 3, 3, 2, 2 }); }, }, { "int64", [&](){ mHarness.addAttributes<int64_t>(names, { 2, 2, 2, 2, 3, 3, 2, 2 }); }, }, { "float", [&](){ mHarness.addAttributes<float>(names, { 1.1f, 1.1f, 1.1f, 1.1f, 2.3f, 2.3f, 1.1f, 1.1f }); }, }, { "double", [&](){ mHarness.addAttributes<double>(names, { 1.1, 1.1, 1.1, 1.1, 2.3, 2.3, 1.1, 1.1 }); }, }, { "vec2i", [&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names, { openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(3,4), openvdb::math::Vec2<int32_t>(3,4), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2) }); }, }, { "vec2f", [&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names, { openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f) }); }, }, { "vec2d", [&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names, { openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3) }); }, }, { "vec3i", [&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names, { openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(4,5,6), openvdb::math::Vec3<int32_t>(4,5,6), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3) }); }, }, { "vec3f", [&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names, { openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) }); }, }, { "vec3d", [&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names, { openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3) }); }, }, { "vec4i", [&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names, { openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(5, 6, 7, 8), openvdb::math::Vec4<int32_t>(5, 6, 7, 8), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4) }); }, }, { "vec4f", [&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names, { openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) }); }, }, { "vec4d", [&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names, { openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) }); }, }, { "mat3f", [&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names, { openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f, -0.5f, 8.2f), openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f, -0.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) }); }, }, { "mat3d", [&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names, { openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1, -0.5, 8.2), openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1, -0.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) }); }, }, { "mat4f", [&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names, { openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) }); }, }, { "mat4d", [&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names, { openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) }); }, }, { "string", [&](){ mHarness.addAttributes<std::string>(names, { "foo", "foo", "foo", "foo", "bar", "bar", "foo", "foo" }); }, } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign." + expc.first + ".ax"); } } void TestAssign::compoundIntegralAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_@test4 /= _l1_; _T1_@test5 %= _l1_; _T1_@test6 <<= _l1_; _T1_@test7 >>= _l1_; _T1_@test8 &= _l1_; _T1_@test9 ^= _l1_; _T1_@test10 |= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test11 = local1; _T1_@test12 += _T1_@test13; _T1_@test14 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(integral); const auto names = unittest_util::nameSequence("test", 14); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "bool", { [&](){ mHarness.addAttributes<bool>(names, { true, true, false, false, false, false, false, false, true, true, true, false, false, false }); }, [&](){ mHarness.addAttributes<bool>(names, { true, true, true, true, true, true, true, true, true, true, false, true, true, true }, // in { true, false, true, true, false, true, false, true, false, true, true, true, true, true }); // expected }, } }, { "int32", { [&](){ mHarness.addAttributes<int32_t>(names, { 2, -2, 0, 0, 0, 0, 0, 0, 2, 2, 5, 0, 0, 3 }); }, [&](){ mHarness.addAttributes<int32_t>(names, { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 12, 13, 14 }, // in { 3, 0, 6, 2, 1, 24, 1, 0, 11, 10, 5, 25, 13, 17 }); // expected }, } }, { "int64", { [&](){ mHarness.addAttributes<int64_t>(names, { 2, -2, 0, 0, 0, 0, 0, 0, 2, 2, 5, 0, 0, 3 }); }, [&](){ mHarness.addAttributes<int64_t>(names, { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 12, 13, 14 }, // in { 3, 0, 6, 2, 1, 24, 1, 0, 11, 10, 5, 25, 13, 17 }); // expected }, } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundFloatingAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_@test4 /= _l1_; _T1_@test5 %= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test6 = local1; _T1_@test7 += _T1_@test8; _T1_@test9 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(floating); const auto names = unittest_util::nameSequence("test", 9); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "float", { [&](){ mHarness.addAttributes<float>(names, { 1.1f, -1.1f, 0.0f, 0.0f, 0.0f, (1.1f+2.3f), 0.0f, 0.0f, 2.3f }); }, [&](){ mHarness.addAttributes<float>(names, { 1.1f, 2.3f, 4.5f, 6.7f, 8.9f, -1.1f, -2.3f, -4.5f, 6.1f }, // in { (1.1f+1.1f), (2.3f-1.1f), (4.5f*1.1f), (6.7f/1.1f), std::fmod(8.9f,1.1f), (1.1f+2.3f), (-2.3f+-4.5f), (-4.5f), (6.1f+2.3f) }); // expected } } }, { "double", { [&](){ mHarness.addAttributes<double>(names, { 1.1, -1.1, 0.0, 0.0, 0.0, (1.1+2.3), 0.0, 0.0, 2.3 }); }, [&](){ mHarness.addAttributes<double>(names, { 1.1, 2.3, 4.5, 6.7, 8.9, -1.1, -2.3, -4.5, 6.1 }, // in { (1.1+1.1), (2.3-1.1), (4.5*1.1), (6.7/1.1), std::fmod(8.9,1.1), (1.1+2.3), (-2.3+-4.5), (-4.5), (6.1+2.3) }); // expected } } }, }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundVectorAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_@test4 /= _l1_; _T1_@test5 %= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test6 = local1; _T1_@test7 += _T1_@test8; _T1_@test9 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(vec2); generate(vec3); generate(vec4); const auto names = unittest_util::nameSequence("test", 9); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "vec2i", { [&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names, { openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(-1,-2), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(4,6), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(3,4) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names, { openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(3,4), openvdb::math::Vec2<int32_t>(5,6), openvdb::math::Vec2<int32_t>(7,8), openvdb::math::Vec2<int32_t>(3,9), openvdb::math::Vec2<int32_t>(9,-1), openvdb::math::Vec2<int32_t>(-2,-3), openvdb::math::Vec2<int32_t>(-4,-5), openvdb::math::Vec2<int32_t>(-6,-7) }, // in { openvdb::math::Vec2<int32_t>(2,4), openvdb::math::Vec2<int32_t>(2,2), openvdb::math::Vec2<int32_t>(5,12), openvdb::math::Vec2<int32_t>(7,4), openvdb::math::Vec2<int32_t>(0,1), openvdb::math::Vec2<int32_t>(4,6), openvdb::math::Vec2<int32_t>(-6,-8), openvdb::math::Vec2<int32_t>(-4,-5), openvdb::math::Vec2<int32_t>(-3,-3) }); // expected } } }, { "vec2f", { [&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names, { openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(-1.1f,-2.3f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(1.1f, 2.3f) + openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(4.1f,5.3f) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names, { openvdb::math::Vec2<float>(1.1f,2.2f), openvdb::math::Vec2<float>(3.3f,4.4f), openvdb::math::Vec2<float>(5.5f,6.6f), openvdb::math::Vec2<float>(7.7f,8.8f), openvdb::math::Vec2<float>(2.3f,5.5f), openvdb::math::Vec2<float>(9.9f,-1.1f), openvdb::math::Vec2<float>(-2.2f,-3.3f), openvdb::math::Vec2<float>(-4.3f,-5.5f), openvdb::math::Vec2<float>(-6.1f,-8.2f) }, // in { openvdb::math::Vec2<float>(1.1f,2.2f) + openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(3.3f,4.4f) - openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(5.5f,6.6f) * openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(7.7f,8.8f) / openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(std::fmod(2.3f, 1.1f), std::fmod(5.5f, 2.3f)), openvdb::math::Vec2<float>(1.1f, 2.3f) + openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(-2.2f,-3.3f) + openvdb::math::Vec2<float>(-4.3f,-5.5f), openvdb::math::Vec2<float>(-4.3f,-5.5f), openvdb::math::Vec2<float>(-6.1f,-8.2f) + openvdb::math::Vec2<float>(4.1f,5.3f) }); // expected } } }, { "vec2d", { [&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names, { openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(-1.1,-2.3), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(1.1, 2.3) + openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(4.1,5.3) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names, { openvdb::math::Vec2<double>(1.1,2.2), openvdb::math::Vec2<double>(3.3,4.4), openvdb::math::Vec2<double>(5.5,6.6), openvdb::math::Vec2<double>(7.7,8.8), openvdb::math::Vec2<double>(2.3,5.5), openvdb::math::Vec2<double>(9.9,-1.1), openvdb::math::Vec2<double>(-2.2,-3.3), openvdb::math::Vec2<double>(-4.3,-5.5), openvdb::math::Vec2<double>(-6.1,-8.2) }, // in { openvdb::math::Vec2<double>(1.1,2.2) + openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(3.3,4.4) - openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(5.5,6.6) * openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(7.7,8.8) / openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(std::fmod(2.3, 1.1), std::fmod(5.5, 2.3)), openvdb::math::Vec2<double>(1.1, 2.3) + openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(-2.2,-3.3) + openvdb::math::Vec2<double>(-4.3,-5.5), openvdb::math::Vec2<double>(-4.3,-5.5), openvdb::math::Vec2<double>(-6.1,-8.2) + openvdb::math::Vec2<double>(4.1,5.3) }); // expected } } }, { "vec3i", { [&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names, { openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(-1,-2,-3), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(5,7,9), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(4,5,6) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names, { openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(4,5,6), openvdb::math::Vec3<int32_t>(7,8,9), openvdb::math::Vec3<int32_t>(-1,-2,-3), openvdb::math::Vec3<int32_t>(4,-5,6), openvdb::math::Vec3<int32_t>(5,7,9), openvdb::math::Vec3<int32_t>(-7,-8,-9), openvdb::math::Vec3<int32_t>(-1,2,-3), openvdb::math::Vec3<int32_t>(-4,5,-6) }, // in { openvdb::math::Vec3<int32_t>(2,4,6), openvdb::math::Vec3<int32_t>(3,3,3), openvdb::math::Vec3<int32_t>(7,16,27), openvdb::math::Vec3<int32_t>(-1,-1,-1), openvdb::math::Vec3<int32_t>(0,1,0), openvdb::math::Vec3<int32_t>(5,7,9), openvdb::math::Vec3<int32_t>(-8,-6,-12), openvdb::math::Vec3<int32_t>(-1,2,-3), openvdb::math::Vec3<int32_t>(0,10,0) }); // expected } } }, { "vec3f", { [&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names, { openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(-1.1f,-2.3f,-4.3f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names, { openvdb::math::Vec3<float>(1.1f,2.2f,3.3f), openvdb::math::Vec3<float>(3.3f,4.4f,5.5f), openvdb::math::Vec3<float>(5.5f,6.6f,7.7f), openvdb::math::Vec3<float>(7.7f,8.8f,9.9f), openvdb::math::Vec3<float>(7.7f,8.8f,9.9f), openvdb::math::Vec3<float>(9.9f,-1.1f,-2.2f), openvdb::math::Vec3<float>(-2.2f,-3.3f,-4.4f), openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f), openvdb::math::Vec3<float>(-7.1f,8.5f,-9.9f), }, // in { openvdb::math::Vec3<float>(1.1f,2.2f,3.3f) + openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(3.3f,4.4f,5.5f) - openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(5.5f,6.6f,7.7f) * openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(7.7f,8.8f,9.9f) / openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(std::fmod(7.7f,1.1f), std::fmod(8.8f,2.3f), std::fmod(9.9f,4.3f)), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(-2.2f,-3.3f,-4.4f) + openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f), openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f), openvdb::math::Vec3<float>(-7.1f,8.5f,-9.9f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f) }); // expected } } }, { "vec3d", { [&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names, { openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(-1.1,-2.3,-4.3), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(1.1, 2.3, 4.3) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(4.1, 5.3, 6.3) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names, { openvdb::math::Vec3<double>(1.1,2.2,3.3), openvdb::math::Vec3<double>(3.3,4.4,5.5), openvdb::math::Vec3<double>(5.5,6.6,7.7), openvdb::math::Vec3<double>(7.7,8.8,9.9), openvdb::math::Vec3<double>(7.7,8.8,9.9), openvdb::math::Vec3<double>(9.9,-1.1,-2.2), openvdb::math::Vec3<double>(-2.2,-3.3,-4.4), openvdb::math::Vec3<double>(-4.3,-5.5,-6.6), openvdb::math::Vec3<double>(-7.1,8.5,-9.9), }, // in { openvdb::math::Vec3<double>(1.1,2.2,3.3) + openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(3.3,4.4,5.5) - openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(5.5,6.6,7.7) * openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(7.7,8.8,9.9) / openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(std::fmod(7.7,1.1), std::fmod(8.8,2.3), std::fmod(9.9,4.3)), openvdb::math::Vec3<double>(1.1, 2.3, 4.3) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(-2.2,-3.3,-4.4) + openvdb::math::Vec3<double>(-4.3,-5.5,-6.6), openvdb::math::Vec3<double>(-4.3,-5.5,-6.6), openvdb::math::Vec3<double>(-7.1,8.5,-9.9) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3) }); // expected } } }, { "vec4i", { [&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names, { openvdb::math::Vec4<int32_t>(1,2,3,4), openvdb::math::Vec4<int32_t>(-1,-2,-3,-4), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(6,8,10,12), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(5,6,7,8) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names, { openvdb::math::Vec4<int32_t>(1,2,3,4), openvdb::math::Vec4<int32_t>(4,5,6,7), openvdb::math::Vec4<int32_t>(7,8,9,-1), openvdb::math::Vec4<int32_t>(-1,-2,-3,1), openvdb::math::Vec4<int32_t>(-4,-5,-6,2), openvdb::math::Vec4<int32_t>(4,5,-6,2), openvdb::math::Vec4<int32_t>(-7,-8,-9,3), openvdb::math::Vec4<int32_t>(-1,2,-3,4), openvdb::math::Vec4<int32_t>(-5,6,-7,8) }, // in { openvdb::math::Vec4<int32_t>(2,4,6,8), openvdb::math::Vec4<int32_t>(3,3,3,3), openvdb::math::Vec4<int32_t>(7,16,27,-4), openvdb::math::Vec4<int32_t>(-1,-1,-1,0), openvdb::math::Vec4<int32_t>(0,1,0,2), openvdb::math::Vec4<int32_t>(6,8,10,12), openvdb::math::Vec4<int32_t>(-8,-6,-12,7), openvdb::math::Vec4<int32_t>(-1,2,-3,4), openvdb::math::Vec4<int32_t>(0,12,0,16) }); // expected } } }, { "vec4f", { [&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names, { openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(-1.1f,-2.3f,-4.3f,-5.4f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names, { openvdb::math::Vec4<float>(1.1f,2.2f,3.3f,4.4f), openvdb::math::Vec4<float>(3.3f,4.4f,5.5f,6.6f), openvdb::math::Vec4<float>(5.5f,6.6f,7.7f,8.8f), openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f), openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f), openvdb::math::Vec4<float>(9.9f,-1.1f,-2.2f,-3.3f), openvdb::math::Vec4<float>(-2.2f,-3.3f,-4.4f,-5.5f), openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f), openvdb::math::Vec4<float>(-8.2f,-9.3f,0.6f,-1.7f) }, // in { openvdb::math::Vec4<float>(1.1f,2.2f,3.3f,4.4f) + openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(3.3f,4.4f,5.5f,6.6f) - openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(5.5f,6.6f,7.7f,8.8f) * openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f) / openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(std::fmod(7.7f,1.1f),std::fmod(8.8f,2.3f),std::fmod(9.9f,4.3f),std::fmod(-1.1f,5.4f)+5.4f), // floored mod openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(-2.2f,-3.3f,-4.4f,-5.5f) + openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f), openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f), openvdb::math::Vec4<float>(-8.2f,-9.3f,0.6f,-1.7f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f) }); // expected } } }, { "vec4d", { [&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names, { openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(-1.1,-2.3,-4.3,-5.4), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names, { openvdb::math::Vec4<double>(1.1,2.2,3.3,4.4), openvdb::math::Vec4<double>(3.3,4.4,5.5,6.6), openvdb::math::Vec4<double>(5.5,6.6,7.7,8.8), openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1), openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1), openvdb::math::Vec4<double>(9.9,-1.1,-2.2,-3.3), openvdb::math::Vec4<double>(-2.2,-3.3,-4.4,-5.5), openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7), openvdb::math::Vec4<double>(-8.2,-9.3,0.6,-1.7) }, // in { openvdb::math::Vec4<double>(1.1,2.2,3.3,4.4) + openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(3.3,4.4,5.5,6.6) - openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(5.5,6.6,7.7,8.8) * openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1) / openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(std::fmod(7.7,1.1),std::fmod(8.8,2.3),std::fmod(9.9,4.3),std::fmod(-1.1,5.4)+5.4), // floored mod openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(-2.2,-3.3,-4.4,-5.5) + openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7), openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7), openvdb::math::Vec4<double>(-8.2,-9.3,0.6,-1.7) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4) }); // expected } } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundMatrixAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test4 = local1; _T1_@test5 += _T1_@test6; _T1_@test7 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(mat3); generate(mat4); const openvdb::math::Mat3<float> m3fl1(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f); const openvdb::math::Mat3<float> m3fl2(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f); const openvdb::math::Mat3<double> m3dl1(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2); const openvdb::math::Mat3<double> m3dl2(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2); const openvdb::math::Mat4<float> m4fl1(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f); const openvdb::math::Mat4<float> m4fl2(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f); const openvdb::math::Mat4<double> m4dl1(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9); const openvdb::math::Mat4<double> m4dl2(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7); const auto names = unittest_util::nameSequence("test", 7); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "mat3f", { [&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names, { m3fl1, -m3fl1, openvdb::math::Mat3<float>::zero(), m3fl1 + m3fl2, openvdb::math::Mat3<float>::zero(), openvdb::math::Mat3<float>::zero(), m3fl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names, { openvdb::math::Mat3<float>(2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f), openvdb::math::Mat3<float>(4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f), openvdb::math::Mat3<float>(5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f), openvdb::math::Mat3<float>(8.3f, 2.3f, 6.1f, 4.5f, 0.1f, 0.1f, 5.3f, 4.5f, 8.9f), openvdb::math::Mat3<float>(6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f), openvdb::math::Mat3<float>(-6.8f,-8.1f,-4.5f, 5.2f,-1.1f, 2.3f, -0.3f, 5.4f,-3.7f) }, // in { openvdb::math::Mat3<float>(2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f) + m3fl1, openvdb::math::Mat3<float>(4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f) - m3fl1, openvdb::math::Mat3<float>(5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f) * m3fl1, m3fl1 + m3fl2, openvdb::math::Mat3<float>(6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f), openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f), openvdb::math::Mat3<float>(-6.8f,-8.1f,-4.5f, 5.2f,-1.1f, 2.3f, -0.3f, 5.4f,-3.7f) + m3fl2 }); // expected } } }, { "mat3d", { [&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names, { m3dl1, -m3dl1, openvdb::math::Mat3<double>::zero(), m3dl1 + m3dl2, openvdb::math::Mat3<double>::zero(), openvdb::math::Mat3<double>::zero(), m3dl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names, { openvdb::math::Mat3<double>(2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1), openvdb::math::Mat3<double>(4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3), openvdb::math::Mat3<double>(5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3), openvdb::math::Mat3<double>(8.3, 2.3, 6.1, 4.5, 0.1, 0.1, 5.3, 4.5, 8.9), openvdb::math::Mat3<double>(6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4), openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7), openvdb::math::Mat3<double>(-6.8,-8.1,-4.5, 5.2,-1.1, 2.3, -0.3, 5.4,-3.7) }, // in { openvdb::math::Mat3<double>(2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1) + m3dl1, openvdb::math::Mat3<double>(4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3) - m3dl1, openvdb::math::Mat3<double>(5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3) * m3dl1, m3dl1 + m3dl2, openvdb::math::Mat3<double>(6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4) + openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7), openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7), openvdb::math::Mat3<double>(-6.8,-8.1,-4.5, 5.2,-1.1, 2.3, -0.3, 5.4,-3.7) + m3dl2 }); // expected } } }, { "mat4f", { [&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names, { m4fl1, -m4fl1, openvdb::math::Mat4<float>::zero(), m4fl1 + m4fl2, openvdb::math::Mat4<float>::zero(), openvdb::math::Mat4<float>::zero(), m4fl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names, { openvdb::math::Mat4<float>(2.3f,-4.3f, 5.4f, 6.7f, 7.8f,-9.1f, 4.5f, 8.2f, 1.1f,-5.4f,-6.7f, 7.8f, 6.7f, 7.8f, 9.1f,-2.4f), openvdb::math::Mat4<float>(4.3f,-5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 6.7f, 7.8f, 9.1f, -1.3f,-0.1f, 1.1f, 0.9f), openvdb::math::Mat4<float>(5.4f, 6.7f, 7.8f, 9.1f, -4.5f, 8.2f, 1.1f,-2.3f, -4.3f,-7.8f, 9.1f, 4.5f, -6.7f, 2.2f,-7.1f, 1.1f), openvdb::math::Mat4<float>(1.2f, 5.1f, 8.2f, 3.1f, -3.3f, -7.3f, 0.2f,-0.1f, 1.4f, 0.8f, 8.8f,-1.1f, -7.8f, 4.1f, 4.4f, -4.7f), openvdb::math::Mat4<float>(5.4f, 6.7f, 8.2f, 1.1f, -2.3f, -4.3f, 2.2f,-7.1f, 1.1f, 7.8f, 9.1f,-4.5f, -7.8f, 9.1f, 4.5f, -6.7f), openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f), openvdb::math::Mat4<float>(4.3f,-5.1f,-5.3f, 2.2f, 2.1f, -4.2f, 2.3f,-1.1f, 0.5f, 0.7f, 1.3f, 0.7f, -1.2f, 3.4f, 9.9f, 9.8f), }, // in { openvdb::math::Mat4<float>(2.3f,-4.3f, 5.4f, 6.7f, 7.8f,-9.1f, 4.5f, 8.2f, 1.1f,-5.4f,-6.7f, 7.8f, 6.7f, 7.8f, 9.1f,-2.4f) + m4fl1, openvdb::math::Mat4<float>(4.3f,-5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 6.7f, 7.8f, 9.1f, -1.3f,-0.1f, 1.1f, 0.9f) - m4fl1, openvdb::math::Mat4<float>(5.4f, 6.7f, 7.8f, 9.1f, -4.5f, 8.2f, 1.1f,-2.3f, -4.3f,-7.8f, 9.1f, 4.5f, -6.7f, 2.2f,-7.1f, 1.1f) * m4fl1, m4fl1 + m4fl2, openvdb::math::Mat4<float>(5.4f, 6.7f, 8.2f, 1.1f, -2.3f, -4.3f, 2.2f,-7.1f, 1.1f, 7.8f, 9.1f,-4.5f, -7.8f, 9.1f, 4.5f, -6.7f) + openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f), openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f), openvdb::math::Mat4<float>(4.3f,-5.1f,-5.3f, 2.2f, 2.1f, -4.2f, 2.3f,-1.1f, 0.5f, 0.7f, 1.3f, 0.7f, -1.2f, 3.4f, 9.9f, 9.8f) + m4fl2 }); // expected } } }, { "mat4d", { [&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names, { m4dl1, -m4dl1, openvdb::math::Mat4<double>::zero(), m4dl1 + m4dl2, openvdb::math::Mat4<double>::zero(), openvdb::math::Mat4<double>::zero(), m4dl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names, { openvdb::math::Mat4<double>(2.3,-4.3, 5.4, 6.7, 7.8,-9.1, 4.5, 8.2, 1.1,-5.4,-6.7, 7.8, 6.7, 7.8, 9.1,-2.4), openvdb::math::Mat4<double>(4.3,-5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 6.7, 7.8, 9.1, -1.3,-0.1, 1.1, 0.9), openvdb::math::Mat4<double>(5.4, 6.7, 7.8, 9.1, -4.5, 8.2, 1.1,-2.3, -4.3,-7.8, 9.1, 4.5, -6.7, 2.2,-7.1, 1.1), openvdb::math::Mat4<double>(1.2, 5.1, 8.2, 3.1, -3.3, -7.3, 0.2,-0.1, 1.4, 0.8, 8.8,-1.1, -7.8, 4.1, 4.4, -4.7), openvdb::math::Mat4<double>(5.4, 6.7, 8.2, 1.1, -2.3, -4.3, 2.2,-7.1, 1.1, 7.8, 9.1,-4.5, -7.8, 9.1, 4.5, -6.7), openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8), openvdb::math::Mat4<double>(4.3,-5.1,-5.3, 2.2, 2.1, -4.2, 2.3,-1.1, 0.5, 0.7, 1.3, 0.7, -1.2, 3.4, 9.9, 9.8), }, // in { openvdb::math::Mat4<double>(2.3,-4.3, 5.4, 6.7, 7.8,-9.1, 4.5, 8.2, 1.1,-5.4,-6.7, 7.8, 6.7, 7.8, 9.1,-2.4) + m4dl1, openvdb::math::Mat4<double>(4.3,-5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 6.7, 7.8, 9.1, -1.3,-0.1, 1.1, 0.9) - m4dl1, openvdb::math::Mat4<double>(5.4, 6.7, 7.8, 9.1, -4.5, 8.2, 1.1,-2.3, -4.3,-7.8, 9.1, 4.5, -6.7, 2.2,-7.1, 1.1) * m4dl1, m4dl1 + m4dl2, openvdb::math::Mat4<double>(5.4, 6.7, 8.2, 1.1, -2.3, -4.3, 2.2,-7.1, 1.1, 7.8, 9.1,-4.5, -7.8, 9.1, 4.5, -6.7) + openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8), openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8), openvdb::math::Mat4<double>(4.3,-5.1,-5.3, 2.2, 2.1, -4.2, 2.3,-1.1, 0.5, 0.7, 1.3, 0.7, -1.2, 3.4, 9.9, 9.8) + m4dl2 }); // expected } } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundStringAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_ local1 = _l1_, local2 = _l2_; // test default init and empty string string empty = ""; string defaultstr; local1 += local2; defaultstr += local1; defaultstr += empty; _T1_@test2 = defaultstr; _T1_@test3 += _T1_@test4; _T1_@test5 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(string); const auto names = unittest_util::nameSequence("test", 5); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "string", { [&](){ mHarness.addAttributes<std::string>(names, { "foo", "foobar", "", "", "bar" }); }, [&](){ mHarness.addAttributes<std::string>(names, { "abc ", "xyz", " 123", "4560", " " }, // in { "abc foo", "foobar", " 1234560", "4560", " bar" }); // expected }, } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::implicitScalarAssignment() { auto generate = [this](const auto& source, const auto& targets) { for (const auto& t1 : source) { std::string code = "_T1_ local = _l1_;\n"; unittest_util::replace(code, "_T1_", t1.first); unittest_util::replace(code, "_l1_", t1.second.at("_l1_")); for (const auto& target : targets) { for (const auto& t2 : *target) { if (t1.first == t2.first) continue; std::string tmp = "_T2_@_A1_ = local;"; unittest_util::replace(tmp, "_A1_", "test" + t2.first); unittest_util::replace(tmp, "_T2_", t2.first); code += tmp + "\n"; } } this->registerTest(code, "assign_implicit_scalar." + t1.first + ".ax"); } }; // source -> dest generate(integral, std::vector<decltype(integral)*>{ &integral, &floating }); generate(floating, std::vector<decltype(integral)*>{ &integral, &floating }); // source -> dest const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); mHarness.addAttribute<int64_t>("testint64", 1); mHarness.addAttribute<float>("testfloat", 1.0f); mHarness.addAttribute<double>("testdouble", 1.0); } }, { "int32", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int64_t>("testint64", 2); mHarness.addAttribute<float>("testfloat", 2.0f); mHarness.addAttribute<double>("testdouble", 2.0); } }, { "int64", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int32_t>("testint32", 2); mHarness.addAttribute<float>("testfloat", 2.0f); mHarness.addAttribute<double>("testdouble", 2.0); } }, { "float", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int32_t>("testint32", 1); mHarness.addAttribute<int64_t>("testint64", 1); mHarness.addAttribute<double>("testdouble", double(1.1f)); } }, { "double", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int32_t>("testint32", 1); mHarness.addAttribute<int64_t>("testint64", 1); mHarness.addAttribute<float>("testfloat", float(1.1)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign_implicit_scalar." + expc.first + ".ax"); } } void TestAssign::implicitContainerAssignment() { auto generate = [this](const auto& source, const auto& target) { for (const auto& t1 : source) { std::string code = "_T1_ local = _l1_;\n"; unittest_util::replace(code, "_T1_", t1.first); unittest_util::replace(code, "_l1_", t1.second.at("_l1_")); for (const auto& t2 : target) { if (t1.first == t2.first) continue; std::string tmp = "_T2_@_A1_ = local;"; unittest_util::replace(tmp, "_A1_", "test" + t2.first); unittest_util::replace(tmp, "_T2_", t2.first); code += tmp + "\n"; } this->registerTest(code, "assign_implicit_container." + t1.first + ".ax"); } }; // source -> dest generate(vec2, vec2); generate(vec3, vec3); generate(vec4, vec4); generate(mat3, mat3); generate(mat4, mat4); // test name is the source type in use. source -> dest const std::map<std::string, std::function<void()>> expected = { { "vec2i", [&]() { mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.0,2.0)); } }, { "vec2f", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,2)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(double(1.1f),double(2.3f))); } }, { "vec2d", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,2)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(float(1.1),float(2.3))); } }, { "vec3i", [&]() { mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.0f,2.0f,3.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.0,2.0,3.0)); } }, { "vec3f", [&]() { mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,2,4)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(double(1.1f),double(2.3f),double(4.3f))); } }, { "vec3d", [&]() { mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,2,4)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(float(1.1),float(2.3),float(4.3))); } }, { "vec4i", [&]() { mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.0f,2.0f,3.0f,4.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.0,2.0,3.0,4.0)); } }, { "vec4f", [&]() { mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,2,4,5)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(double(1.1f),double(2.3f),double(4.3f),double(5.4f))); } }, { "vec4d", [&]() { mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,2,4,5)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(float(1.1),float(2.3),float(4.3),float(5.4))); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>( double(1.1f),double(2.3f),double(4.3f), double(5.4f),double(6.7f),double(7.8f), double(9.1f),double(4.5f),double(8.2f))); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>( float(1.1),float(2.3),float(4.3), float(5.4),float(6.7),float(7.8), float(9.1),float(4.5),float(8.2))); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>( double(1.1f),double(2.3f),double(4.3f),double(5.4f), double(6.7f),double(7.8f),double(9.1f),double(4.5f), double(8.2f),double(3.3f),double(2.9f),double(5.9f), double(0.1f),double(0.3f),double(5.1f),double(1.9f))); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>( float(1.1),float(2.3),float(4.3),float(5.4), float(6.7),float(7.8),float(9.1),float(4.5), float(8.2),float(3.3),float(2.9),float(5.9), float(0.1),float(0.3),float(5.1),float(1.9))); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign_implicit_container." + expc.first + ".ax"); } } void TestAssign::implicitContainerScalarAssignment() { auto generate = [this](const auto& source, const auto& targets) { for (const auto& t1 : source) { std::string code = "_T1_ local = _l1_;\n"; unittest_util::replace(code, "_T1_", t1.first); unittest_util::replace(code, "_l1_", t1.second.at("_l1_")); for (const auto& target : targets) { for (const auto& t2 : *target) { if (t1.first == t2.first) continue; std::string tmp = "_T2_@_A1_ = local;"; unittest_util::replace(tmp, "_A1_", "test" + t2.first); unittest_util::replace(tmp, "_T2_", t2.first); code += tmp + "\n"; } } this->registerTest(code, "assign_implicit_container_scalar." + t1.first + ".ax"); } }; generate(integral, std::vector<decltype(integral)*>{ &vec2, &vec3, &vec4, &mat3, &mat4 }); generate(floating, std::vector<decltype(integral)*>{ &vec2, &vec3, &vec4, &mat3, &mat4 }); auto symmetric3 = [](auto val) -> openvdb::math::Mat3<decltype(val)> { openvdb::math::Mat3<decltype(val)> mat; mat.setZero(); mat(0,0) = val; mat(1,1) = val; mat(2,2) = val; return mat; }; auto symmetric4 = [](auto val) -> openvdb::math::Mat4<decltype(val)> { openvdb::math::Mat4<decltype(val)> mat; mat.setZero(); mat(0,0) = val; mat(1,1) = val; mat(2,2) = val; mat(3,3) = val; return mat; }; const std::map<std::string, std::function<void()>> expected = { { "bool", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.0f,1.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.0,1.0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.0f,1.0f,1.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.0,1.0,1.0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.0f,1.0f,1.0f,1.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.0,1.0,1.0,1.0)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(1.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(1.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(1.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(1.0)); } }, { "int32", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(2,2)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(2,2,2)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(2,2,2,2)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(2.0,2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(2.0f,2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(2.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(2.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(2.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(2.0)); } }, { "int64", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(2,2)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(2,2,2)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(2,2,2,2)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(2.0,2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(2.0f,2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(2.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(2.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(2.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(2.0)); } }, { "float", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(double(1.1f),double(1.1f))); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f,1.1f)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(double(1.1f),double(1.1f),double(1.1f))); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f,1.1f,1.1f)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(double(1.1f),double(1.1f),double(1.1f),double(1.1f))); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f,1.1f,1.1f,1.1f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(1.1f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(double(1.1f))); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(1.1f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(double(1.1f))); } }, { "double", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1,1.1)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(float(1.1),float(1.1))); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1,1.1,1.1)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(float(1.1),float(1.1),float(1.1))); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1,1.1,1.1,1.1)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(float(1.1),float(1.1),float(1.1),float(1.1))); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(float(1.1))); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(1.1)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(float(1.1))); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(1.1)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign_implicit_container_scalar." + expc.first + ".ax"); } } void TestAssign::scopedAssign() { const std::string code = R"( float var = 30.0f; { float var = 3.0f; } { float var = 1.0f; float@test2 = var; { float var = -10.0f; float@test3 = var; } { float@test7 = var; } } { float var = -100.0f; } { float var = 50.0f; { float var = -15.0f; float@test4 = var; } { float var = -10.0f; } { float@test5 = var; } float@test6 = var; } float@test1 = var; )"; this->registerTest(code, "assign_scoped.float.ax"); const auto names = unittest_util::nameSequence("test", 7); mHarness.addAttributes<float>(names, {30.0f, 1.0f, -10.0f, -15.0f, 50.0f, 50.0f, 1.0f}); this->execute("assign_scoped.float.ax"); CPPUNIT_ASSERT(mHarness.mLogger.hasWarning()); }
77,820
C++
51.019385
162
0.455744
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestKeyword.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestKeyword : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestKeyword); CPPUNIT_TEST(testKeywordSimpleReturn); CPPUNIT_TEST(testKeywordReturnBranchIf); CPPUNIT_TEST(testKeywordReturnBranchLoop); CPPUNIT_TEST(testKeywordConditionalReturn); CPPUNIT_TEST(testKeywordForLoopKeywords); CPPUNIT_TEST(testKeywordWhileLoopKeywords); CPPUNIT_TEST(testKeywordDoWhileLoopKeywords); CPPUNIT_TEST_SUITE_END(); void testKeywordSimpleReturn(); void testKeywordReturnBranchIf(); void testKeywordReturnBranchLoop(); void testKeywordConditionalReturn(); void testKeywordForLoopKeywords(); void testKeywordWhileLoopKeywords(); void testKeywordDoWhileLoopKeywords(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestKeyword); void TestKeyword::testKeywordSimpleReturn() { mHarness.addAttribute<int>("return_test0", 0); mHarness.executeCode("test/snippets/keyword/simpleReturn"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordReturnBranchIf() { mHarness.addAttribute<int>("return_test1", 1); mHarness.executeCode("test/snippets/keyword/returnBranchIf"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordReturnBranchLoop() { mHarness.addAttribute<int>("return_test2", 1); mHarness.executeCode("test/snippets/keyword/returnBranchLoop"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordConditionalReturn() { mHarness.addAttribute<int>("return_test3", 3); mHarness.executeCode("test/snippets/keyword/conditionalReturn"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordForLoopKeywords() { mHarness.addAttribute<openvdb::Vec3f>("loop_test4", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test5", openvdb::Vec3f(1.0,0.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test6", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test7", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test8", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test19", openvdb::math::Mat3s(1.0,2.0,3.0, 0.0,0.0,0.0, 7.0,8.0,9.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test20", openvdb::math::Mat3s(1.0,0.0,0.0, 0.0,0.0,0.0, 7.0,0.0,0.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test21", openvdb::math::Mat3s(1.0,0.0,3.0, 0.0,0.0,0.0, 7.0,0.0,9.0)); mHarness.addAttribute<openvdb::Vec3f>("return_test4", openvdb::Vec3f(10,10,10)); mHarness.executeCode("test/snippets/keyword/forLoopKeywords"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordWhileLoopKeywords() { mHarness.addAttribute<openvdb::Vec3f>("loop_test10", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test11", openvdb::Vec3f(0.0,0.0,2.0)); mHarness.addAttribute<openvdb::Vec3f>("return_test6", openvdb::Vec3f(100,100,100)); mHarness.executeCode("test/snippets/keyword/whileLoopKeywords"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordDoWhileLoopKeywords() { mHarness.addAttribute<openvdb::Vec3f>("loop_test13", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test14", openvdb::Vec3f(0.0,0.0,2.0)); mHarness.addAttribute<openvdb::Vec3f>("return_test7", openvdb::Vec3f(100,100,100)); mHarness.executeCode("test/snippets/keyword/doWhileLoopKeywords"); AXTESTS_STANDARD_ASSERT(); }
3,690
C++
31.377193
87
0.726829
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestBinary.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "../test/util.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; // Configuration values for binary code using ConfigMap = std::unordered_map<std::string, std::unordered_map<std::string, std::string>>; static const ConfigMap integral = { { "bool", { { "_L1_", "true" }, { "_L2_", "false" } } }, { "int16", { { "_L1_", "2" }, { "_L2_", "3" } } }, { "int32", { { "_L1_", "2" }, { "_L2_", "3" } } }, { "int64", { { "_L1_", "2l" }, { "_L2_", "3l" } } } }; static const ConfigMap floating = { { "float", { { "_L1_", "1.1f" }, { "_L2_", "2.3f" } } }, { "double", { { "_L1_", "1.1" }, { "_L2_", "2.3" } } } }; static const ConfigMap vec2 = { { "vec2i", { { "_L1_", "{1, 2}" }, { "_L2_", "{3, 4}" } } }, { "vec2f", { { "_L1_", "{1.1f, 2.3f}" }, { "_L2_", "{4.1f, 5.3f}" } } }, { "vec2d", { { "_L1_", "{1.1, 2.3}" }, { "_L2_", "{4.1, 5.3}" } } } }; static const ConfigMap vec3 = { { "vec3i", { { "_L1_", "{1, 2, 3}" }, { "_L2_", "{4, 5, 6}" } } }, { "vec3f", { { "_L1_", "{1.1f, 2.3f, 4.3f}" }, { "_L2_", "{4.1f, 5.3f, 6.3f}" } } }, { "vec3d", { { "_L1_", "{1.1, 2.3 , 4.3}" }, { "_L2_", "{4.1, 5.3, 6.3}" } } } }; static const ConfigMap vec4 = { { "vec4i", { { "_L1_", "{1, 2, 3, 4}" }, { "_L2_", "{5, 6, 7, 8}" } } }, { "vec4f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f}" }, { "_L2_", "{5.1f, 6.3f, 7.3f, 8.4f}" } } }, { "vec4d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4}" }, { "_L2_", "{5.1, 6.3, 7.3, 8.4}" } } } }; static const ConfigMap mat3 = { { "mat3f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f }" }, { "_L2_", "{9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f }" } } }, { "mat3d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2 }" }, { "_L2_", "{9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2 }" } } } }; static const ConfigMap mat4 = { { "mat4f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f}" }, { "_L2_", "{0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f}" } } }, { "mat4d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9}" }, { "_L2_", "{0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7}" } } } }; static const ConfigMap string = { { "string", { { "_L1_", "\"foo\"" }, { "_L2_", "\"bar\"" } } } }; class TestBinary : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestBinary); CPPUNIT_TEST(plus); CPPUNIT_TEST(minus); CPPUNIT_TEST(mult); CPPUNIT_TEST(div); CPPUNIT_TEST(mod); CPPUNIT_TEST(btand); CPPUNIT_TEST(btor); CPPUNIT_TEST(btxor); CPPUNIT_TEST(logicaland); CPPUNIT_TEST(logicalor); CPPUNIT_TEST(equalsequals); CPPUNIT_TEST(notequals); CPPUNIT_TEST(greaterthan); CPPUNIT_TEST(lessthan); CPPUNIT_TEST(greaterthanequals); CPPUNIT_TEST(lessthanequals); CPPUNIT_TEST(shiftleft); CPPUNIT_TEST(shiftright); CPPUNIT_TEST_SUITE_END(); void plus(); void minus(); void mult(); void div(); void mod(); void btand(); void btor(); void btxor(); void logicaland(); void logicalor(); void equalsequals(); void notequals(); void greaterthan(); void lessthan(); void greaterthanequals(); void lessthanequals(); void shiftleft(); void shiftright(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestBinary); void TestBinary::plus() { const std::string code = R"( _T1_@_A1_ = _L1_ + _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); generate(string); this->registerTest(repl, "binary_plus.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 5); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 5); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 5); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f + 2.3f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 + 2.3); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(4,6)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f+4.1f, 2.3f+5.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1+4.1, 2.3+5.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(5,7,9)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f+4.1f, 2.3f+5.3f, 4.3f+6.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1+4.1, 2.3+5.3, 4.3+6.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(6,8,10,12)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f+5.1f, 2.3f+6.3f, 4.3f+7.3f, 5.4f+8.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1+5.1, 2.3+6.3, 4.3+7.3, 5.4+8.4)); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) + openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) + openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) + openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) + openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); } }, { "string", [&](){ mHarness.addAttribute<std::string>("teststring", "foobar"); } } }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_plus.ax"); } void TestBinary::minus() { const std::string code = R"( _T1_@_A1_ = _L1_ - _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_minus.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", -1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", -1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", -1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f - 2.3f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 - 2.3); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(-2,-2)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f-4.1f, 2.3f-5.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1-4.1, 2.3-5.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(-3,-3,-3)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f-4.1f, 2.3f-5.3f, 4.3f-6.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1-4.1, 2.3-5.3, 4.3-6.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(-4,-4,-4,-4)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f-5.1f, 2.3f-6.3f, 4.3f-7.3f, 5.4f-8.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1-5.1, 2.3-6.3, 4.3-7.3, 5.4-8.4)); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) - openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) - openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) - openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) - openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_minus.ax"); } void TestBinary::mult() { const std::string code = R"( _T1_@_A1_ = _L1_ * _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_mult.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 6); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 6); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 6); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f * 2.3f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 * 2.3); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(3,8)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f*4.1f, 2.3f*5.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1*4.1, 2.3*5.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(4,10,18)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f*4.1f, 2.3f*5.3f, 4.3f*6.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1*4.1, 2.3*5.3, 4.3*6.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(5,12,21,32)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f*5.1f, 2.3f*6.3f, 4.3f*7.3f, 5.4f*8.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1*5.1, 2.3*6.3, 4.3*7.3, 5.4*8.4)); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) * openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) * openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) * openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) * openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); } } }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_mult.ax"); } void TestBinary::div() { // @note reverses L1 and L2 as L2 is usually larger const std::string code = R"( _T1_@_A1_ = _L2_ / _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); this->registerTest(repl, "binary_div.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 2.3f/1.1f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 2.3/1.1); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(3,2)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(4.1f/1.1f, 5.3f/2.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(4.1/1.1, 5.3/2.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(4,2,2)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(4.1f/1.1f, 5.3f/2.3f, 6.3f/4.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(4.1/1.1, 5.3/2.3, 6.3/4.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(5,3,2,2)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(5.1f/1.1f, 6.3f/2.3f, 7.3f/4.3f, 8.4f/5.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(5.1/1.1, 6.3/2.3, 7.3/4.3, 8.4/5.4)); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_div.ax"); } void TestBinary::mod() { // @note reverses L1 and L2 as L2 is usually larger const std::string code = R"( _T1_@_A1_ = _L2_ % _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); this->registerTest(repl, "binary_mod.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", std::fmod(2.3f,1.1f)); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", std::fmod(2.3,1.1)); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(0,0)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(std::fmod(4.1f,1.1f), std::fmod(5.3f,2.3f))); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(std::fmod(4.1,1.1), std::fmod(5.3,2.3))); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(0,1,0)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(std::fmod(4.1f,1.1f), std::fmod(5.3f,2.3f), std::fmod(6.3f,4.3f))); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(std::fmod(4.1,1.1), std::fmod(5.3,2.3), std::fmod(6.3,4.3))); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(0,0,1,0)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(std::fmod(5.1f,1.1f), std::fmod(6.3f,2.3f), std::fmod(7.3f,4.3f), std::fmod(8.4f,5.4f))); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(std::fmod(5.1,1.1), std::fmod(6.3,2.3), std::fmod(7.3,4.3), std::fmod(8.4,5.4))); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_mod.ax"); } void TestBinary::btand() { const std::string code = R"( _T1_@_A1_ = _L1_ & _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_bitand.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 2); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 2); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 2); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_bitand.ax"); } void TestBinary::btor() { const std::string code = R"( _T1_@_A1_ = _L1_ | _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_bitor.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 3); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 3); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 3); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_bitor.ax"); } void TestBinary::btxor() { const std::string code = R"( _T1_@_A1_ = _L1_ ^ _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_bitxor.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_bitxor.ax"); } void TestBinary::logicaland() { const std::string code = R"( _T1_@_A1_ = _L1_ && _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_logicaland.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.0f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.0); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_logicaland.ax"); // Also test short circuiting logical op for && mHarness.reset(); this->registerTest(R"( int@scircuit1 = 0; int@scircuit2 = 1; int@scircuit3 = 2; int@scircuit1++ && ++int@scircuit2; ++int@scircuit1 && ++int@scircuit3; int@scircuit4 = 1; int@scircuit5 = 1; true && int@scircuit4 = 2; false && int@scircuit5 = 2;)", "binary_logicaland_scircuit.ax"); mHarness.addAttributes<int32_t>(unittest_util::nameSequence("scircuit", 5), { 2, 1, 3, 2, 1 }); this->execute("binary_logicaland_scircuit.ax"); } void TestBinary::logicalor() { const std::string code = R"( _T1_@_A1_ = _L1_ || _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_logicalor.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.0f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.0); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_logicalor.ax"); // Also test short circuiting logical op for || mHarness.reset(); this->registerTest(R"( int@scircuit1 = 0; int@scircuit2 = 1; int@scircuit3 = 2; int@scircuit1++ || ++int@scircuit2; ++int@scircuit1 || ++int@scircuit3; int@scircuit4 = 1; int@scircuit5 = 1; true || int@scircuit4 = 2; false || int@scircuit5 = 2;)", "binary_logicalor_scircuit.ax"); mHarness.addAttributes<int32_t>(unittest_util::nameSequence("scircuit", 5), { 2, 2, 2, 1, 2 }); this->execute("binary_logicalor_scircuit.ax"); } void TestBinary::equalsequals() { const std::string code = R"( bool@_A1_ = _L1_ == _L2_; bool@_A2_ = _L2_ == _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_relational_equalsequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (size_t i = 0; i < idx-1; ++i) { results.emplace_back((i % 2 == 0) ? false : true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_equalsequals.ax"); } void TestBinary::notequals() { const std::string code = R"( bool@_A1_ = _L1_ != _L2_; bool@_A2_ = _L2_ != _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_relational_notequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (size_t i = 0; i < idx-1; ++i) { results.emplace_back((i % 2 == 1) ? false : true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_notequals.ax"); } void TestBinary::greaterthan() { const std::string code = R"( bool@_A1_ = _L1_ > _L2_; bool@_A2_ = _L2_ > _L1_; bool@_A3_ = _L2_ > _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_greaterthan.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(true); results.emplace_back(false); results.emplace_back(false); } else { results.emplace_back(false); results.emplace_back(true); results.emplace_back(false); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(false); results.emplace_back(true); results.emplace_back(false); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_greaterthan.ax"); } void TestBinary::lessthan() { const std::string code = R"( bool@_A1_ = _L1_ < _L2_; bool@_A2_ = _L2_ < _L1_; bool@_A3_ = _L2_ < _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_lessthan.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(false); results.emplace_back(true); results.emplace_back(false); } else { results.emplace_back(true); results.emplace_back(false); results.emplace_back(false); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(true); results.emplace_back(false); results.emplace_back(false); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_lessthan.ax"); } void TestBinary::greaterthanequals() { const std::string code = R"( bool@_A1_ = _L1_ >= _L2_; bool@_A2_ = _L2_ >= _L1_; bool@_A3_ = _L2_ >= _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_greaterthanequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(true); results.emplace_back(false); results.emplace_back(true); } else { results.emplace_back(false); results.emplace_back(true); results.emplace_back(true); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(false); results.emplace_back(true); results.emplace_back(true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_greaterthanequals.ax"); } void TestBinary::lessthanequals() { const std::string code = R"( bool@_A1_ = _L1_ <= _L2_; bool@_A2_ = _L2_ <= _L1_; bool@_A3_ = _L2_ <= _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_lessthanequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(false); results.emplace_back(true); results.emplace_back(true); } else { results.emplace_back(true); results.emplace_back(false); results.emplace_back(true); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(true); results.emplace_back(false); results.emplace_back(true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_lessthanequals.ax"); } void TestBinary::shiftleft() { const std::string code = R"( _T1_@_A1_ = _L1_ << _L2_; _T1_@_A2_ = _L2_ << _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first + "1"); unittest_util::replace(tmp, "_A2_", "test" + config.first + "2"); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_shiftleft.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool1", true); mHarness.addAttribute<bool>("testbool2", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint161", 16); mHarness.addAttribute<int16_t>("testint162", 12); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint321", 16); mHarness.addAttribute<int32_t>("testint322", 12); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint641", 16); mHarness.addAttribute<int64_t>("testint642", 12); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_shiftleft.ax"); } void TestBinary::shiftright() { const std::string code = R"( _T1_@_A1_ = _L1_ >> _L2_; _T1_@_A2_ = _L2_ >> _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first + "1"); unittest_util::replace(tmp, "_A2_", "test" + config.first + "2"); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_shiftright.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool1", true); mHarness.addAttribute<bool>("testbool2", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint161", 0); mHarness.addAttribute<int16_t>("testint162", 0); } }, { "int", [&](){ mHarness.addAttribute<int32_t>("testint321", 0); mHarness.addAttribute<int32_t>("testint322", 0); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint641", 0); mHarness.addAttribute<int64_t>("testint642", 0); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_shiftright.ax"); }
42,437
C++
38.330862
211
0.525579
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestCrement.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "CompareGrids.h" #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestCrement : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestCrement); CPPUNIT_TEST(crementScalar); CPPUNIT_TEST(crementComponent); CPPUNIT_TEST_SUITE_END(); void crementScalar(); void crementComponent(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCrement); void TestCrement::crementScalar() { const std::string code = R"( _T1_@test1 = ++_T1_@test2; _T1_@test3 = _T1_@test4++; _T1_@test5 = (_T1_@test6++, _T1_@test7++, ++_T1_@test6); _T1_@test8 = (++_T1_@test6, ++_T1_@test7, _T1_@test6++); ++_T1_@test9 = _T1_@test9; )"; auto generate = [&](const auto& types) { for (const auto& type : types) { std::string repl = code; unittest_util::replace(repl, "_T1_", type); this->registerTest(repl, "crement_inc." + type + ".ax"); unittest_util::replace(repl, "++", "--"); this->registerTest(repl, "crement_dec." + type + ".ax"); } }; generate(std::vector<std::string>{ "int16", "int32", "int64", "float", "double", }); const auto names = unittest_util::nameSequence("test", 9); const std::map<std::string, std::function<void(bool)>> expected = { { "int16", [&](bool inc){ if (inc) mHarness.addAttributes<int16_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 2, 2, 2, 3, 6, 8, -1, 7, -3 }); else mHarness.addAttributes<int16_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 0, 0, 2, 1, 2, 0, -5, 1, -5 }); }, }, { "int32", [&](bool inc){ if (inc) mHarness.addAttributes<int32_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 2, 2, 2, 3, 6, 8, -1, 7, -3 }); else mHarness.addAttributes<int32_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 0, 0, 2, 1, 2, 0, -5, 1, -5 }); }, }, { "int64", [&](bool inc){ if (inc) mHarness.addAttributes<int64_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 2, 2, 2, 3, 6, 8, -1, 7, -3 }); else mHarness.addAttributes<int64_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 0, 0, 2, 1, 2, 0, -5, 1, -5 }); }, }, { "float", [&](bool inc){ if (inc) mHarness.addAttributes<float>(names, { 0.1f, 1.4f, -1.9f, 2.5f, -3.3f, 4.5f, -3.3f, 4.7f, -4.8f }, { (1.4f+1.0f), (1.4f+1.0f), 2.5f, (2.5f+1.0f), (4.5f+1.0f+1.0f), (4.5f+1.0f+1.0f+1.0f+1.0f), (-3.3f+1.0f+1.0f), (4.5f+1.0f+1.0f+1.0f), (-4.8f+1.0f) }); else mHarness.addAttributes<float>(names, { 0.1f, 1.4f, -1.9f, 2.5f, -3.3f, 4.5f, -3.3f, 4.7f, -4.8f }, { (1.4f-1.0f), (1.4f-1.0f), 2.5f, (2.5f-1.0f), (4.5f-1.0f-1.0f), (4.5f-1.0f-1.0f-1.0f-1.0f), (-3.3f-1.0f-1.0f), (4.5f-1.0f-1.0f-1.0f), (-4.8f-1.0f) }); }, }, { "double", [&](bool inc){ if (inc) mHarness.addAttributes<double>(names, { 0.1, 1.4, -1.9, 2.5, -3.3, 4.5, -3.3, 4.7, -4.8 }, { (1.4+1.0), (1.4+1.0), 2.5, (2.5+1.0), (4.5+1.0+1.0), (4.5+1.0+1.0+1.0+1.0), (-3.3+1.0+1.0), (4.5+1.0+1.0+1.0), (-4.8+1.0) }); else mHarness.addAttributes<double>(names, { 0.1, 1.4, -1.9, 2.5, -3.3, 4.5, -3.3, 4.7, -4.8 }, { (1.4-1.0), (1.4-1.0), 2.5, (2.5-1.0), (4.5-1.0-1.0), (4.5-1.0-1.0-1.0-1.0), (-3.3-1.0-1.0), (4.5-1.0-1.0-1.0), (-4.8-1.0) }); }, }, }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(true); // increment this->execute("crement_inc." + expc.first + ".ax"); mHarness.reset(); expc.second.operator()(false); // decrement this->execute("crement_dec." + expc.first + ".ax"); } } void TestCrement::crementComponent() { // Just tests the first two components of every container const std::string code = R"( _T1_@_A1_[0] = ++_T1_@_A2_[0]; _T1_@_A1_[1] = _T1_@_A2_[1]++; )"; auto generate = [&](const auto& types) { std::string repl; for (const auto& type : types) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", type); unittest_util::replace(tmp, "_A1_", "test" + type + "1"); unittest_util::replace(tmp, "_A2_", "test" + type + "2"); repl += tmp; } this->registerTest(repl, "crement_inc.component.ax"); unittest_util::replace(repl, "++", "--"); this->registerTest(repl, "crement_dec.component.ax"); }; generate(std::vector<std::string>{ "vec2i", "vec2f", "vec2d", "vec3i", "vec3f", "vec3d", "vec4i", "vec4f", "vec4d", "mat3f", "mat3d", "mat4f", "mat4d" }); const std::map<std::string, std::function<void()>> expected = { { "inc", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i1", openvdb::math::Vec2<int32_t>(0,1)); mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i2", openvdb::math::Vec2<int32_t>(-1,1), openvdb::math::Vec2<int32_t>(0,2)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f1", openvdb::math::Vec2<float>(-1.1f+1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f2", openvdb::math::Vec2<float>(-1.1f,1.1f), openvdb::math::Vec2<float>(-1.1f+1.0f, 1.1f+1.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d1", openvdb::math::Vec2<double>(-1.1+1.0, 1.1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d2", openvdb::math::Vec2<double>(-1.1,1.1), openvdb::math::Vec2<double>(-1.1+1.0, 1.1+1.0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i1", openvdb::math::Vec3<int32_t>(0,1,0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i2", openvdb::math::Vec3<int32_t>(-1,1,0), openvdb::math::Vec3<int32_t>(0,2,0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f1", openvdb::math::Vec3<float>(-1.1f+1.0f, 1.1f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f2", openvdb::math::Vec3<float>(-1.1f,1.1f,0.0f), openvdb::math::Vec3<float>(-1.1f+1.0f, 1.1f+1.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d1", openvdb::math::Vec3<double>(-1.1+1.0, 1.1, 0.0)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d2", openvdb::math::Vec3<double>(-1.1,1.1,0.0), openvdb::math::Vec3<double>(-1.1+1.0, 1.1+1.0 ,0.0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i1", openvdb::math::Vec4<int32_t>(0,1,0,0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i2", openvdb::math::Vec4<int32_t>(-1,1,0,0), openvdb::math::Vec4<int32_t>(0,2,0,0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f1", openvdb::math::Vec4<float>(-1.1f+1.0f, 1.1f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f2", openvdb::math::Vec4<float>(-1.1f,1.1f,0.0f,0.0f), openvdb::math::Vec4<float>(-1.1f+1.0f, 1.1f+1.0f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d1", openvdb::math::Vec4<double>(-1.1+1.0, 1.1, 0.0, 0.0)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d2", openvdb::math::Vec4<double>(-1.1,1.1,0.0,0.0), openvdb::math::Vec4<double>(-1.1+1.0, 1.1+1.0, 0.0, 0.0)); auto getmat = [](auto x, auto a, auto b) -> decltype(x) { x = decltype(x)::zero(); x(0,0) = a; x(0,1) = b; return x; }; mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f1", getmat(openvdb::math::Mat3<float>(), -1.1f+1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f2", getmat(openvdb::math::Mat3<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat3<float>(),-1.1f+1.0f,1.1f+1.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d1", getmat(openvdb::math::Mat3<double>(), -1.1+1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d2", getmat(openvdb::math::Mat3<double>(),-1.1,1.1), getmat(openvdb::math::Mat3<double>(),-1.1+1.0, 1.1+1.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f1", getmat(openvdb::math::Mat4<float>(), -1.1f+1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f2", getmat(openvdb::math::Mat4<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat4<float>(),-1.1f+1.0f,1.1f+1.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d1", getmat(openvdb::math::Mat4<double>(), -1.1+1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d2", getmat(openvdb::math::Mat4<double>(),-1.1,1.1), getmat(openvdb::math::Mat4<double>(),-1.1+1.0, 1.1+1.0)); } }, { "dec", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i1", openvdb::math::Vec2<int32_t>(-2,1)); mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i2", openvdb::math::Vec2<int32_t>(-1,1), openvdb::math::Vec2<int32_t>(-2,0)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f1", openvdb::math::Vec2<float>(-1.1f-1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f2", openvdb::math::Vec2<float>(-1.1f,1.1f), openvdb::math::Vec2<float>(-1.1f-1.0f, 1.1f-1.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d1", openvdb::math::Vec2<double>(-1.1-1.0, 1.1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d2", openvdb::math::Vec2<double>(-1.1,1.1), openvdb::math::Vec2<double>(-1.1-1.0, 1.1-1.0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i1", openvdb::math::Vec3<int32_t>(-2,1,0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i2", openvdb::math::Vec3<int32_t>(-1,1,0), openvdb::math::Vec3<int32_t>(-2,0,0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f1", openvdb::math::Vec3<float>(-1.1f-1.0f, 1.1f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f2", openvdb::math::Vec3<float>(-1.1f,1.1f,0.0f), openvdb::math::Vec3<float>(-1.1f-1.0f, 1.1f-1.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d1", openvdb::math::Vec3<double>(-1.1-1.0, 1.1, 0.0)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d2", openvdb::math::Vec3<double>(-1.1,1.1,0.0), openvdb::math::Vec3<double>(-1.1-1.0, 1.1-1.0 ,0.0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i1", openvdb::math::Vec4<int32_t>(-2,1,0,0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i2", openvdb::math::Vec4<int32_t>(-1,1,0,0), openvdb::math::Vec4<int32_t>(-2,0,0,0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f1", openvdb::math::Vec4<float>(-1.1f-1.0f, 1.1f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f2", openvdb::math::Vec4<float>(-1.1f,1.1f,0.0f,0.0f), openvdb::math::Vec4<float>(-1.1f-1.0f, 1.1f-1.0f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d1", openvdb::math::Vec4<double>(-1.1-1.0, 1.1, 0.0, 0.0)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d2", openvdb::math::Vec4<double>(-1.1,1.1,0.0,0.0), openvdb::math::Vec4<double>(-1.1-1.0, 1.1-1.0, 0.0, 0.0)); auto getmat = [](auto x, auto a, auto b) -> decltype(x) { x = decltype(x)::zero(); x(0,0) = a; x(0,1) = b; return x; }; mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f1", getmat(openvdb::math::Mat3<float>(), -1.1f-1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f2", getmat(openvdb::math::Mat3<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat3<float>(),-1.1f-1.0f,1.1f-1.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d1", getmat(openvdb::math::Mat3<double>(), -1.1-1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d2", getmat(openvdb::math::Mat3<double>(),-1.1,1.1), getmat(openvdb::math::Mat3<double>(),-1.1-1.0, 1.1-1.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f1", getmat(openvdb::math::Mat4<float>(), -1.1f-1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f2", getmat(openvdb::math::Mat4<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat4<float>(),-1.1f-1.0f,1.1f-1.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d1", getmat(openvdb::math::Mat4<double>(), -1.1-1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d2", getmat(openvdb::math::Mat4<double>(),-1.1,1.1), getmat(openvdb::math::Mat4<double>(),-1.1-1.0, 1.1-1.0)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("crement_" + expc.first + ".component.ax"); } }
16,068
C++
45.712209
138
0.483321
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestLogger.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/ast/Parse.h> #include <openvdb_ax/compiler/Logger.h> #include <cppunit/extensions/HelperMacros.h> class TestLogger : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestLogger); //CPPUNIT_TEST(testParseNewNode); CPPUNIT_TEST(testParseSetsTree); CPPUNIT_TEST(testAddError); CPPUNIT_TEST(testAddWarning); CPPUNIT_TEST(testWarningsAsErrors); CPPUNIT_TEST(testMaxErrors); CPPUNIT_TEST_SUITE_END(); //void testParseNewNode(); void testParseSetsTree(); void testAddError(); void testAddWarning(); void testWarningsAsErrors(); void testMaxErrors(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLogger); /* extern openvdb::ax::Logger* axlog; /// @note We don't deploy the grammar c files as part of the AX install. /// Because the unit tests are structured to be able to build against /// an existing version of AX we can't include the parser.cc here for /// access to newNode. It's tested through other methods, but we /// should restructure how this code is shared by perhaps moving it to /// a shared header (including the definition of AXLTYPE) void TestLogger::testParseNewNode() { openvdb::ax::Logger logger; axlog = &logger;// setting global Logger* used in parser AXLTYPE location; location.first_line = 100; location.first_column = 65; const auto& nodeToLineColMap = logger.mNodeToLineColMap; CPPUNIT_ASSERT(nodeToLineColMap.empty()); const openvdb::ax::ast::Local* testLocal = newNode<openvdb::ax::ast::Local>(&location, "test"); CPPUNIT_ASSERT_EQUAL(nodeToLineColMap.size(),static_cast<size_t>(1)); openvdb::ax::Logger::CodeLocation lineCol = nodeToLineColMap.at(testLocal); CPPUNIT_ASSERT_EQUAL(lineCol.first, static_cast<size_t>(100)); CPPUNIT_ASSERT_EQUAL(lineCol.second, static_cast<size_t>(65)); } */ void TestLogger::testParseSetsTree() { openvdb::ax::Logger logger; CPPUNIT_ASSERT(!logger.mTreePtr); std::string code(""); openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(code.c_str(), logger); CPPUNIT_ASSERT(tree); CPPUNIT_ASSERT_EQUAL(tree, logger.mTreePtr); } void TestLogger::testAddError() { std::vector<std::string> messages; openvdb::ax::Logger logger([&messages](const std::string& message) { messages.emplace_back(message); }); CPPUNIT_ASSERT(!logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), messages.size()); openvdb::ax::Logger::CodeLocation codeLocation(1,1); std::string message("test"); logger.error(message, codeLocation); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:1"), 0); logger.error(message, codeLocation); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(2)); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(2)); logger.clear(); CPPUNIT_ASSERT(!logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(0)); openvdb::ax::ast::Local testLocal("name"); logger.error(message, &testLocal); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(3)); CPPUNIT_ASSERT(!logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test"), 0); logger.clear(); CPPUNIT_ASSERT(!logger.hasError()); // test that add error finds code location { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(" a;", logger); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); logger.error(message, local); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:2"), 0); } logger.clear(); CPPUNIT_ASSERT(!logger.hasError()); // test add error finds code location even when node is deep copy { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("a;", logger); openvdb::ax::ast::Tree::ConstPtr treeCopy(tree->copy()); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); const openvdb::ax::ast::Node* localCopy = treeCopy->child(0)->child(0); CPPUNIT_ASSERT(localCopy); // add referring to copy logger.error(message, localCopy); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(5)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:1"), 0); } } void TestLogger::testAddWarning() { std::vector<std::string> messages; openvdb::ax::Logger logger([](const std::string&) {}, [&messages](const std::string& message) { messages.emplace_back(message); }); CPPUNIT_ASSERT(!logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), messages.size()); openvdb::ax::Logger::CodeLocation codeLocation(1,1); std::string message("test"); logger.warning(message, codeLocation); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:1"), 0); logger.warning(message, codeLocation); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(2)); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(2)); logger.clear(); CPPUNIT_ASSERT(!logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(0)); openvdb::ax::ast::Local testLocal("name"); logger.warning(message, &testLocal); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(3)); CPPUNIT_ASSERT(!logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test"), 0); logger.clear(); CPPUNIT_ASSERT(!logger.hasWarning()); // test that add warning finds code location { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(" a;", logger); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); logger.warning(message, local); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:2"), 0); } logger.clear(); CPPUNIT_ASSERT(!logger.hasWarning()); // test add warning finds code location even when node is deep copy { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("a;", logger); openvdb::ax::ast::Tree::ConstPtr treeCopy(tree->copy()); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); const openvdb::ax::ast::Node* localCopy = treeCopy->child(0)->child(0); CPPUNIT_ASSERT(localCopy); // add referring to copy logger.warning(message, localCopy); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(5)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:1"), 0); } } void TestLogger::testWarningsAsErrors() { openvdb::ax::Logger logger([](const std::string&) {}); const std::string message("test"); const openvdb::ax::Logger::CodeLocation location(10,20); logger.setWarningsAsErrors(true); CPPUNIT_ASSERT(!logger.hasError()); CPPUNIT_ASSERT(!logger.hasWarning()); logger.warning(message, location); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT(!logger.hasWarning()); } void TestLogger::testMaxErrors() { openvdb::ax::Logger logger([](const std::string&) {}); const std::string message("test"); const openvdb::ax::Logger::CodeLocation location(10,20); CPPUNIT_ASSERT(logger.error(message, location)); CPPUNIT_ASSERT(logger.error(message, location)); CPPUNIT_ASSERT(logger.error(message, location)); logger.clear(); logger.setMaxErrors(2); CPPUNIT_ASSERT(logger.error(message, location)); CPPUNIT_ASSERT(!logger.error(message, location)); CPPUNIT_ASSERT(!logger.error(message, location)); }
9,112
C++
34.877953
90
0.664618
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionGroup.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/FunctionTypes.h> #include <cppunit/extensions/HelperMacros.h> #include <memory> #include <string> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Framework methods for the subsequent unit tests /// @brief Dummy derived function which implemented types struct TestFunction : public openvdb::ax::codegen::Function { static_assert(std::has_virtual_destructor <openvdb::ax::codegen::Function>::value, "Base class destructor is not virtual"); TestFunction(const std::vector<llvm::Type*>& types, llvm::Type* ret, const std::string& symbol) : openvdb::ax::codegen::Function(types.size(), symbol) , mTypes(types), mRet(ret) {} ~TestFunction() override {} llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext&) const override { types = mTypes; return mRet; } const std::vector<llvm::Type*> mTypes; llvm::Type* mRet; }; inline openvdb::ax::codegen::FunctionGroup::Ptr axtestscalar(llvm::LLVMContext& C) { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; llvm::Type* voidty = llvm::Type::getVoidTy(C); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { Function::Ptr(new TestFunction({llvm::Type::getDoubleTy(C)}, voidty, "ax.testd")), Function::Ptr(new TestFunction({llvm::Type::getFloatTy(C)}, voidty, "ax.testf")), Function::Ptr(new TestFunction({llvm::Type::getInt64Ty(C)}, voidty, "ax.testi64")), Function::Ptr(new TestFunction({llvm::Type::getInt32Ty(C)}, voidty, "ax.testi32")), Function::Ptr(new TestFunction({llvm::Type::getInt16Ty(C)}, voidty, "ax.testi16")), Function::Ptr(new TestFunction({llvm::Type::getInt1Ty(C)}, voidty, "ax.testi1")) })); return group; } inline openvdb::ax::codegen::FunctionGroup::Ptr axtestsize(llvm::LLVMContext& C) { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; llvm::Type* voidty = llvm::Type::getVoidTy(C); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { Function::Ptr(new TestFunction({}, voidty, "ax.empty")), Function::Ptr(new TestFunction({llvm::Type::getDoubleTy(C)}, voidty, "ax.d")), Function::Ptr(new TestFunction({ llvm::Type::getDoubleTy(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.dd")), })); return group; } inline openvdb::ax::codegen::FunctionGroup::Ptr axtestmulti(llvm::LLVMContext& C) { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; llvm::Type* voidty = llvm::Type::getVoidTy(C); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { Function::Ptr(new TestFunction({}, voidty, "ax.empty")), Function::Ptr(new TestFunction({llvm::Type::getInt32Ty(C)}, voidty, "ax.i32")), Function::Ptr(new TestFunction({ llvm::Type::getDoubleTy(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.dd")), Function::Ptr(new TestFunction({ llvm::Type::getInt32Ty(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.i32d")), Function::Ptr(new TestFunction({ llvm::Type::getDoubleTy(C)->getPointerTo(), llvm::Type::getInt32Ty(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.d*i32d")), Function::Ptr(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo(), }, voidty, "ax.i32x1")), Function::Ptr(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), }, voidty, "ax.i32x2")), })); return group; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// class TestFunctionGroup : public CppUnit::TestCase { public: // Test FunctionGroup signature matching and execution errors CPPUNIT_TEST_SUITE(TestFunctionGroup); CPPUNIT_TEST(testFunctionGroup); CPPUNIT_TEST(testMatch); CPPUNIT_TEST(testExecute); CPPUNIT_TEST_SUITE_END(); void testFunctionGroup(); void testMatch(); void testExecute(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionGroup); void TestFunctionGroup::testFunctionGroup() { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Type* voidty = llvm::Type::getVoidTy(C); Function::Ptr decl1(new TestFunction({}, voidty, "ax.test1")); Function::Ptr decl2(new TestFunction({}, voidty, "ax.test2")); Function::Ptr decl3(new TestFunction({}, voidty, "ax.test3")); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { decl1, decl2, decl3 })); CPPUNIT_ASSERT_EQUAL(std::string("test"), std::string(group->name())); CPPUNIT_ASSERT_EQUAL(std::string("The documentation"), std::string(group->doc())); CPPUNIT_ASSERT_EQUAL(size_t(3), group->list().size()); CPPUNIT_ASSERT_EQUAL(decl1, group->list()[0]); CPPUNIT_ASSERT_EQUAL(decl2, group->list()[1]); CPPUNIT_ASSERT_EQUAL(decl3, group->list()[2]); } void TestFunctionGroup::testMatch() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); std::vector<llvm::Type*> types; Function::SignatureMatch match; Function::Ptr result; // FunctionGroup::Ptr group = axtestscalar(C); const std::vector<Function::Ptr>* list = &group->list(); // test explicit matching types.resize(1); types[0] = llvm::Type::getInt1Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[5], result); // types[0] = llvm::Type::getInt16Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[4], result); // types[0] = llvm::Type::getInt32Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[3], result); // types[0] = llvm::Type::getInt64Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types[0] = llvm::Type::getFloatTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[1], result); // types[0] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); // test unsigned integers automatic type creation - these are not supported in the // language however can be constructed from the API. The function framework does // not differentiate between signed and unsigned integers types[0] = LLVMType<uint64_t>::get(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // test implicit matching - types should match to the first available castable signature // which is always the void(double) "tsfd" function for all provided scalars types[0] = llvm::Type::getInt8Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); types.clear(); // test invalid matching - Size matching returns the first function which matched // the size result = group->match(types, C, &match); CPPUNIT_ASSERT_EQUAL(Function::SignatureMatch::None, match); CPPUNIT_ASSERT(!result); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::None == match); CPPUNIT_ASSERT(!result); // types.emplace_back(llvm::Type::getInt1Ty(C)->getPointerTo()); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Size == match); CPPUNIT_ASSERT(!result); // types[0] = llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Size == match); CPPUNIT_ASSERT(!result); // types[0] = llvm::Type::getInt1Ty(C); types.emplace_back(llvm::Type::getInt1Ty(C)); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::None == match); CPPUNIT_ASSERT(!result); // // Test varying argument size function // test explicit matching group = axtestsize(C); list = &group->list(); types.resize(2); types[0] = llvm::Type::getDoubleTy(C); types[1] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types.resize(1); types[0] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[1], result); // types.clear(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); // Test implicit matching types.resize(2); types[0] = llvm::Type::getFloatTy(C); types[1] = llvm::Type::getInt32Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // Test non matching types.resize(3); types[0] = llvm::Type::getDoubleTy(C); types[1] = llvm::Type::getDoubleTy(C); types[2] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::None == match); CPPUNIT_ASSERT(!result); // // Test multi function group = axtestmulti(C); list = &group->list(); // test explicit/implicit matching types.clear(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); // types.resize(2); types[0] = llvm::Type::getDoubleTy(C); types[1] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types[0] = llvm::Type::getInt32Ty(C); types[1] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[3], result); // types[0] = llvm::Type::getInt32Ty(C); types[1] = llvm::Type::getInt32Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types.resize(1); types[0] = llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[5], result); // types[0] = llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[6], result); } void TestFunctionGroup::testExecute() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::IRBuilder<> B(state.scratchBlock()); llvm::Value* result = nullptr; llvm::CallInst* call = nullptr; llvm::Function* target = nullptr; std::vector<llvm::Value*> args; // test execution // test invalid arguments throws FunctionGroup::Ptr group(new FunctionGroup("empty", "", {})); CPPUNIT_ASSERT(!group->execute(/*args*/{}, B)); group = axtestscalar(C); const std::vector<Function::Ptr>* list = &group->list(); CPPUNIT_ASSERT(!group->execute({}, B)); CPPUNIT_ASSERT(!group->execute({ B.getTrue(), B.getTrue() }, B)); args.resize(1); // test llvm function calls - execute and get the called function. // check this is already inserted into the module and is expected // llvm::Function using create on the expected function signature args[0] = B.getTrue(); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[5]->create(state.module()), target); // args[0] = B.getInt16(1); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[4]->create(state.module()), target); // args[0] = B.getInt32(1); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[3]->create(state.module()), target); // args[0] = B.getInt64(1); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[2]->create(state.module()), target); // args[0] = llvm::ConstantFP::get(llvm::Type::getFloatTy(C), 1.0f); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[1]->create(state.module()), target); // args[0] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[0]->create(state.module()), target); // // Test multi function group = axtestmulti(C); list = &group->list(); args.clear(); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[0]->create(state.module()), target); // args.resize(1); args[0] = B.CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[5]->create(state.module()), target); // args[0] = B.CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[6]->create(state.module()), target); // args.resize(2); args[0] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0); args[1] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[2]->create(state.module()), target); }
18,078
C++
30.829225
95
0.623797
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionRegistry.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <iostream> #include "util.h" #include <openvdb_ax/compiler/CompilerOptions.h> #include <openvdb_ax/codegen/Functions.h> #include <openvdb_ax/codegen/FunctionRegistry.h> #include <cppunit/extensions/HelperMacros.h> class TestFunctionRegistry : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestFunctionRegistry); CPPUNIT_TEST(testCreateAllVerify); CPPUNIT_TEST_SUITE_END(); void testCreateAllVerify(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionRegistry); void TestFunctionRegistry::testCreateAllVerify() { openvdb::ax::codegen::FunctionRegistry::UniquePtr reg = openvdb::ax::codegen::createDefaultRegistry(); openvdb::ax::FunctionOptions opts; // check that no warnings are printed during registration // @todo Replace this with a better logger once AX has one! std::streambuf* sbuf = std::cerr.rdbuf(); try { // Redirect cerr std::stringstream buffer; std::cerr.rdbuf(buffer.rdbuf()); reg->createAll(opts, true); const std::string& result = buffer.str(); CPPUNIT_ASSERT_MESSAGE(result, result.empty()); } catch (...) { std::cerr.rdbuf(sbuf); throw; } std::cerr.rdbuf(sbuf); }
1,325
C++
23.555555
64
0.686038
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestSymbolTable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/SymbolTable.h> #include <cppunit/extensions/HelperMacros.h> template <typename T> using LLVMType = openvdb::ax::codegen::LLVMType<T>; class TestSymbolTable : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestSymbolTable); CPPUNIT_TEST(testSingleTable); CPPUNIT_TEST(testTableBlocks); CPPUNIT_TEST_SUITE_END(); void testSingleTable(); void testTableBlocks(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestSymbolTable); void TestSymbolTable::testSingleTable() { unittest_util::LLVMState state; llvm::IRBuilder<> builder(state.scratchBlock()); llvm::Type* type = LLVMType<float>::get(state.context()); llvm::Value* value1 = builder.CreateAlloca(type); llvm::Value* value2 = builder.CreateAlloca(type); CPPUNIT_ASSERT(value1); CPPUNIT_ASSERT(value2); openvdb::ax::codegen::SymbolTable table; CPPUNIT_ASSERT(table.map().empty()); CPPUNIT_ASSERT(table.insert("test", value1)); CPPUNIT_ASSERT(!table.insert("test", nullptr)); CPPUNIT_ASSERT(table.exists("test")); CPPUNIT_ASSERT_EQUAL(value1, table.get("test")); table.clear(); CPPUNIT_ASSERT(table.map().empty()); CPPUNIT_ASSERT(!table.exists("test")); CPPUNIT_ASSERT(table.insert("test", value1)); CPPUNIT_ASSERT(table.replace("test", value2)); CPPUNIT_ASSERT(!table.replace("other", value2)); CPPUNIT_ASSERT(table.exists("test")); CPPUNIT_ASSERT(table.exists("other")); CPPUNIT_ASSERT_EQUAL(value2, table.get("test")); CPPUNIT_ASSERT_EQUAL(value2, table.get("other")); } void TestSymbolTable::testTableBlocks() { unittest_util::LLVMState state; llvm::IRBuilder<> builder(state.scratchBlock()); llvm::Type* type = LLVMType<float>::get(state.context()); llvm::Value* value1 = builder.CreateAlloca(type); llvm::Value* value2 = builder.CreateAlloca(type); llvm::Value* value3 = builder.CreateAlloca(type); llvm::Value* value4 = builder.CreateAlloca(type); CPPUNIT_ASSERT(value1); CPPUNIT_ASSERT(value2); CPPUNIT_ASSERT(value3); CPPUNIT_ASSERT(value4); // test table insertion and erase openvdb::ax::codegen::SymbolTableBlocks tables; openvdb::ax::codegen::SymbolTable* table1 = &(tables.globals()); openvdb::ax::codegen::SymbolTable* table2 = tables.getOrInsert(0); CPPUNIT_ASSERT_EQUAL(table1, table2); table2 = &(tables.get(0)); CPPUNIT_ASSERT_EQUAL(table1, table2); CPPUNIT_ASSERT_THROW(tables.erase(0), std::runtime_error); tables.getOrInsert(1); tables.getOrInsert(2); tables.getOrInsert(4); CPPUNIT_ASSERT_THROW(tables.get(3), std::runtime_error); CPPUNIT_ASSERT(tables.erase(4)); CPPUNIT_ASSERT(tables.erase(2)); CPPUNIT_ASSERT(tables.erase(1)); tables.globals().insert("global1", value1); tables.globals().insert("global2", value2); // test find methods llvm::Value* result = tables.find("global1"); CPPUNIT_ASSERT_EQUAL(value1, result); result = tables.find("global2"); CPPUNIT_ASSERT_EQUAL(value2, result); table1 = tables.getOrInsert(2); table2 = tables.getOrInsert(4); tables.getOrInsert(5); // test multi table find methods table1->insert("table_level_2", value3); table2->insert("table_level_4", value4); // test find second nested value result = tables.find("table_level_2", 0); CPPUNIT_ASSERT(!result); result = tables.find("table_level_2", 1); CPPUNIT_ASSERT(!result); result = tables.find("table_level_2", 2); CPPUNIT_ASSERT_EQUAL(value3, result); // test find fourth nested value result = tables.find("table_level_4", 0); CPPUNIT_ASSERT(!result); result = tables.find("table_level_4", 3); CPPUNIT_ASSERT(!result); result = tables.find("table_level_4", 4); CPPUNIT_ASSERT_EQUAL(value4, result); result = tables.find("table_level_4", 10000); CPPUNIT_ASSERT_EQUAL(value4, result); // test find fourth nested value with matching global name tables.globals().insert("table_level_4", value1); result = tables.find("table_level_4"); CPPUNIT_ASSERT_EQUAL(value4, result); result = tables.find("table_level_4", 4); CPPUNIT_ASSERT_EQUAL(value4, result); result = tables.find("table_level_4", 3); CPPUNIT_ASSERT_EQUAL(value1, result); // test replace CPPUNIT_ASSERT(tables.replace("table_level_4", value2)); result = tables.find("table_level_4"); CPPUNIT_ASSERT_EQUAL(value2, result); // test global was not replaced result = tables.find("table_level_4", 0); CPPUNIT_ASSERT_EQUAL(value1, result); CPPUNIT_ASSERT(!tables.replace("empty", nullptr)); }
4,781
C++
27.295858
70
0.678101
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestComputeGeneratorFailures.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include "../util.h" #include <openvdb_ax/compiler/CompilerOptions.h> #include <openvdb_ax/compiler/Logger.h> #include <openvdb_ax/codegen/FunctionRegistry.h> #include <openvdb_ax/codegen/ComputeGenerator.h> #include <openvdb_ax/ast/AST.h> #include <cppunit/extensions/HelperMacros.h> static const std::vector<std::string> tests { // codegen errors /// implicit narrow "int a; vec2i b; a=b;", "int a; vec3i b; a=b;", "int a; vec4i b; a=b;", "float a; vec2f b; a=b;", "float a; vec3f b; a=b;", "float a; vec4f b; a=b;", "float a; mat3f b; a=b;", "float a; mat4f b; a=b;", "double a; vec2d b; a=b;", "double a; vec3d b; a=b;", "double a; vec4d b; a=b;", "double a; mat3f b; a=b;", "double a; mat4f b; a=b;", /// unsupported bin ops "float a; a << 1;", "float a; a >> 1;", "float a; a | 1;", "float a; a ^ 1;", "float a; a & 1;", "double a; a << 1;", "double a; a >> 1;", "double a; a | 1;", "double a; a ^ 1;", "double a; a & 1;", "mat3d a,b; a % b;", "mat3d a,b; a & b;", "mat3d a,b; a && b;", "mat3d a,b; a << b;", "mat3d a,b; a >> b;", "mat3d a,b; a ^ b;", "mat3d a,b; a || b;", "mat3f a,b; a % b;", "mat3f a,b; a & b;", "mat3f a,b; a && b;", "mat3f a,b; a << b;", "mat3f a,b; a >> b;", "mat3f a,b; a ^ b;", "mat3f a,b; a || b;", "mat4d a,b; a % b;", "mat4d a,b; a & b;", "mat4d a,b; a && b;", "mat4d a,b; a << b;", "mat4d a,b; a >> b;", "mat4d a,b; a ^ b;", "mat4d a,b; a || b;", "string a,b; a & b;", "string a,b; a && b;", "string a,b; a - b;", "string a,b; a << b;", "string a,b; a >> b;", "string a,b; a ^ b;", "string a,b; a | b;", "string a,b; a || b;", "vec2d a,b; a & b;", "vec2d a,b; a && b;", "vec2d a,b; a << b;", "vec2d a,b; a >> b;", "vec2d a,b; a ^ b;", "vec2d a,b; a | b;", "vec2d a,b; a || b;", "vec2f a,b; a & b;", "vec2f a,b; a && b;", "vec2f a,b; a << b;", "vec2f a,b; a >> b;", "vec2f a,b; a ^ b;", "vec2f a,b; a | b;", "vec2f a,b; a || b;", "vec2i a,b; a & b;", "vec2i a,b; a && b;", "vec2i a,b; a << b;", "vec2i a,b; a >> b;", "vec2i a,b; a ^ b;", "vec2i a,b; a | b;", "vec2i a,b; a || b;", "vec3d a,b; a & b;", "vec3d a,b; a && b;", "vec3d a,b; a << b;", "vec3d a,b; a >> b;", "vec3d a,b; a ^ b;", "vec3d a,b; a | b;", "vec3d a,b; a || b;", "vec3f a,b; a & b;", "vec3f a,b; a && b;", "vec3f a,b; a << b;", "vec3f a,b; a >> b;", "vec3f a,b; a ^ b;", "vec3f a,b; a | b;", "vec3f a,b; a || b;", "vec3i a,b; a & b;", "vec3i a,b; a && b;", "vec3i a,b; a << b;", "vec3i a,b; a >> b;", "vec3i a,b; a ^ b;", "vec3i a,b; a | b;", "vec3i a,b; a || b;", "vec4d a,b; a & b;", "vec4d a,b; a && b;", "vec4d a,b; a << b;", "vec4d a,b; a >> b;", "vec4d a,b; a ^ b;", "vec4d a,b; a ^ b;", "vec4d a,b; a || b;", "vec4f a,b; a & b;", "vec4f a,b; a && b;", "vec4f a,b; a << b;", "vec4f a,b; a >> b;", "vec4f a,b; a ^ b;", "vec4f a,b; a | b;", "vec4f a,b; a || b;", "vec4i a,b; a & b;", "vec4i a,b; a && b;", "vec4i a,b; a << b;", "vec4i a,b; a >> b;", "vec4i a,b; a ^ b;", "vec4i a,b; a | b;", "vec4i a,b; a || b;", /// invalid unary ops "vec2f a; !a;", "vec2d a; !a;", "vec3d a; !a;", "vec3f a; !a;", "vec4f a; !a;", "vec4d a; !a;", "mat3f a; !a;", "mat3d a; !a;", "mat3f a; !a;", "mat4d a; !a;", "vec2f a; ~a;", "vec2d a; ~a;", "vec3d a; ~a;", "vec3f a; ~a;", "vec4f a; ~a;", "vec4d a; ~a;", "mat3f a; ~a;", "mat3d a; ~a;", "mat3f a; ~a;", "mat4d a; ~a;", /// missing function "nonexistent();", /// non/re declared "a;", "int a; int a;", "{ int a; int a; }", "int a, a;", "a ? b : c;", "a ? true : false;", "true ? a : c;", "true ? a : false;", "true ? true : c;", "a && b;", "a && true;", "true && b;", /// invalid crement "string a; ++a;", "vec2f a; ++a;", "vec3f a; ++a;", "vec4f a; ++a;", "mat3f a; ++a;", "mat4f a; ++a;", /// array size assignments "vec2f a; vec3f b; a=b;", "vec3f a; vec2f b; a=b;", "vec4f a; vec3f b; a=b;", "vec2d a; vec3d b; a=b;", "vec3d a; vec2d b; a=b;", "vec4d a; vec3d b; a=b;", "vec2i a; vec3i b; a=b;", "vec3i a; vec2i b; a=b;", "vec4i a; vec3i b; a=b;", "mat4f a; mat3f b; a=b;", "mat4d a; mat3d b; a=b;", /// string assignments "string a = 1;", "int a; string b; b=a;", "float a; string b; b=a;", "double a; string b; b=a;", "vec3f a; string b; b=a;", "mat3f a; string b; b=a;", /// array index "int a; a[0];", "vec3f a; string b; a[b];", "vec3f a; vec3f b; a[b];", "vec3f a; mat3f b; a[b];", "vec3f a; a[1,1];", "mat3f a; vec3f b; a[b,1];", "mat3f a; vec3f b; a[1,b];", /// unsupported implicit casts/ops "vec2f a; vec3f b; a*b;", "vec3f a; vec4f b; a*b;", "vec3f a; vec2f b; a*b;", "vec2i a; vec3f b; a*b;", "mat3f a; mat4f b; a*b;", "string a; mat4f b; a*b;", "int a; string b; a*b;", "string a; string b; a*b;", "string a; string b; a-b;", "string a; string b; a/b;", "~0.0f;", "vec3f a; ~a;" /// loops "break;", "continue;", // ternary "int a = true ? print(1) : print(2);", "true ? print(1) : 1;", "mat4d a; a ? 0 : 1;", "mat4f a; a ? 0 : 1;", "string a; a ? 0 : 1;", "vec2d a; a ? 0 : 1;", "vec2f a; a ? 0 : 1;", "vec2i a; a ? 0 : 1;", "vec3d a; a ? 0 : 1;", "vec3f a; a ? 0 : 1;", "vec3i a; a ? 0 : 1;", "vec4d a; a ? 0 : 1;", "vec4f a; a ? 0 : 1;", "vec4i a; a ? 0 : 1;", // "int a, b; (a ? b : 2) = 1;", "true ? {1,2} : {1,2,3};", "true ? \"foo\" : 1;", "true ? 1.0f : \"foo\";", "{1,1} && 1 ? true : false;", "{1,1} ? true : false;", "{1,1} && 1 ? \"foo\" : false;", "\"foo\" ? true : false;", "true ? {1,1} && 1: {1,1};", "true ? {1,1} : {1,1} && 1;", "string a; true ? a : 1;", "string a; true ? 1.0f : a;", // conditional "mat4d a; if (a) 1;", "mat4f a; if (a) 1;", "string a; if (a) 1;", "vec2d a; if (a) 1;", "vec2f a; if (a) 1;", "vec2i a; if (a) 1;", "vec3d a; if (a) 1;", "vec3f a; if (a) 1;", "vec3i a; if (a) 1;", "vec4d a; if (a) 1;", "vec4f a; if (a) 1;", "vec4i a; if (a) 1;", "if ({1,1} && 1) 1;", "if (true) {1,1} && 1;", // loops "mat4d a; for (;a;) 1;", "mat4f a; for (;a;) 1;", "string a; for (;a;) 1;", "vec2d a; for (;a;) 1;", "vec2f a; for (;a;) 1;", "vec2i a; for (;a;) 1;", "vec3d a; for (;a;) 1;", "vec3f a; for (;a;) 1;", "vec3i a; for (;a;) 1;", "vec4d a; for (;a;) 1;", "vec4f a; for (;a;) 1;", "vec4i a; for (;a;) 1;", "mat4d a; while (a) 1;", "mat4f a; while (a) 1;", "string a; while (a) 1;", "vec2d a; while (a) 1;", "vec2f a; while (a) 1;", "vec2i a; while (a) 1;", "vec3d a; while (a) 1;", "vec3f a; while (a) 1;", "vec3i a; while (a) 1;", "vec4d a; while (a) 1;", "vec4f a; while (a) 1;", "vec4i a; while (a) 1;", "mat4d a; do { 1; } while(a);", "mat4f a; do { 1; } while(a);", "string a; do { 1; } while(a);", "vec2d a; do { 1; } while(a);", "vec2f a; do { 1; } while(a);", "vec2i a; do { 1; } while(a);", "vec3d a; do { 1; } while(a);", "vec3f a; do { 1; } while(a);", "vec3i a; do { 1; } while(a);", "vec4d a; do { 1; } while(a);", "vec4f a; do { 1; } while(a);", "vec4i a; do { 1; } while(a);", // comma "vec2i v; v++, 1;", "vec2i v; 1, v++;" }; class TestComputeGeneratorFailures : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestComputeGeneratorFailures); CPPUNIT_TEST(testFailures); CPPUNIT_TEST_SUITE_END(); void testFailures(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestComputeGeneratorFailures); void TestComputeGeneratorFailures::testFailures() { openvdb::ax::FunctionOptions opts; openvdb::ax::codegen::FunctionRegistry reg; // create logger that suppresses all messages, but still logs number of errors/warnings openvdb::ax::Logger logger([](const std::string&) {}); logger.setMaxErrors(1); for (const auto& code : tests) { const openvdb::ax::ast::Tree::ConstPtr ast = openvdb::ax::ast::parse(code.c_str(), logger); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to parse", code), ast.get()); unittest_util::LLVMState state; openvdb::ax::codegen::codegen_internal::ComputeGenerator gen(state.module(), opts, reg, logger); gen.generate(*ast); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected Compiler Error", code), logger.hasError()); logger.clear(); } }
9,126
C++
25.609329
104
0.446198
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionTypes.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/FunctionTypes.h> #include <cppunit/extensions/HelperMacros.h> #include <llvm/IR/Verifier.h> #include <llvm/Support/raw_ostream.h> #include <sstream> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /// @brief Dummy derived function which implemented types struct TestFunction : public openvdb::ax::codegen::Function { static_assert(std::has_virtual_destructor <openvdb::ax::codegen::Function>::value, "Base class destructor is not virtual"); TestFunction(const std::vector<llvm::Type*>& types, llvm::Type* ret, const std::string& symbol) : openvdb::ax::codegen::Function(types.size(), symbol) , mTypes(types), mRet(ret) {} ~TestFunction() override {} llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext&) const override { types = mTypes; return mRet; } const std::vector<llvm::Type*> mTypes; llvm::Type* mRet; }; /// @brief Dummy derived IR function which implemented types and /// forwards on the generator struct TestIRFunction : public openvdb::ax::codegen::IRFunctionBase { static_assert(std::has_virtual_destructor <openvdb::ax::codegen::IRFunctionBase>::value, "Base class destructor is not virtual"); TestIRFunction(const std::vector<llvm::Type*>& types, llvm::Type* ret, const std::string& symbol, const openvdb::ax::codegen::IRFunctionBase::GeneratorCb& gen) : openvdb::ax::codegen::IRFunctionBase(symbol, gen, types.size()) , mTypes(types), mRet(ret) {} ~TestIRFunction() override {} llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext&) const override { types = mTypes; return mRet; } const std::vector<llvm::Type*> mTypes; llvm::Type* mRet; }; /// @brief static function to test c binding addresses struct CBindings { static void voidfunc() {} static int16_t scalarfunc(bool,int16_t,int32_t,int64_t,float,double) { return int16_t(); } static int32_t scalatptsfunc(bool*,int16_t*,int32_t*,int64_t*,float*,double*) { return int32_t(); } static int64_t arrayfunc(bool(*)[1],int16_t(*)[2],int32_t(*)[3],int64_t(*)[4],float(*)[5],double(*)[6]) { return int64_t(); } static void multiptrfunc(void*, void**, void***, float*, float**, float***) { } template <typename Type> static inline Type tmplfunc() { return Type(); } }; /// @brief Helper method to finalize a function (with a terminator) /// If F is nullptr, finalizes the current function inline llvm::Instruction* finalizeFunction(llvm::IRBuilder<>& B, llvm::Function* F = nullptr) { auto IP = B.saveIP(); if (F) { if (F->empty()) { B.SetInsertPoint(llvm::BasicBlock::Create(B.getContext(), "", F)); } else { B.SetInsertPoint(&(F->getEntryBlock())); } } llvm::Instruction* ret = B.CreateRetVoid(); B.restoreIP(IP); return ret; } /// @brief Defines to wrap the verification of IR #define VERIFY_FUNCTION_IR(Function) { \ std::string error; llvm::raw_string_ostream os(error); \ const bool valid = !llvm::verifyFunction(*Function, &os); \ CPPUNIT_ASSERT_MESSAGE(os.str(), valid); \ } #define VERIFY_MODULE_IR(Module) { \ std::string error; llvm::raw_string_ostream os(error); \ const bool valid = !llvm::verifyModule(*Module, &os); \ CPPUNIT_ASSERT_MESSAGE(os.str(), valid); \ } #define VERIFY_MODULE_IR_INVALID(Module) { \ const bool valid = llvm::verifyModule(*Module); \ CPPUNIT_ASSERT_MESSAGE("Expected IR to be invalid!", valid); \ } #define VERIFY_FUNCTION_IR_INVALID(Function) { \ const bool valid = llvm::verifyFunction(*Function); \ CPPUNIT_ASSERT_MESSAGE("Expected IR to be invalid!", valid); \ } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// class TestFunctionTypes : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestFunctionTypes); CPPUNIT_TEST(testLLVMTypesFromSignature); CPPUNIT_TEST(testLLVMFunctionTypeFromSignature); CPPUNIT_TEST(testPrintSignature); // Test Function::create, Function::types and other base methods CPPUNIT_TEST(testFunctionCreate); // Test Function::call CPPUNIT_TEST(testFunctionCall); // Test Function::match CPPUNIT_TEST(testFunctionMatch); // Test derived CFunctions, mainly CFunction::create and CFunction::types CPPUNIT_TEST(testCFunctions); // Test C constant folding CPPUNIT_TEST(testCFunctionCF); // Test derived IR Function, IRFunctionBase::create and IRFunctionBase::call CPPUNIT_TEST(testIRFunctions); // Test SRET methods for both C and IR functions CPPUNIT_TEST(testSRETFunctions); CPPUNIT_TEST_SUITE_END(); void testLLVMTypesFromSignature(); void testLLVMFunctionTypeFromSignature(); void testPrintSignature(); void testFunctionCreate(); void testFunctionCall(); void testFunctionMatch(); void testCFunctions(); void testCFunctionCF(); void testIRFunctions(); void testSRETFunctions(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionTypes); void TestFunctionTypes::testLLVMTypesFromSignature() { using openvdb::ax::codegen::llvmTypesFromSignature; unittest_util::LLVMState state; llvm::Type* type = nullptr; std::vector<llvm::Type*> types; type = llvmTypesFromSignature<void()>(state.context()); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); type = llvmTypesFromSignature<void()>(state.context(), &types); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); CPPUNIT_ASSERT(types.empty()); type = llvmTypesFromSignature<float()>(state.context(), &types); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); CPPUNIT_ASSERT(types.empty()); type = llvmTypesFromSignature<float(double, int64_t, float(*)[3])>(state.context(), &types); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); CPPUNIT_ASSERT_EQUAL(size_t(3), types.size()); CPPUNIT_ASSERT(types[0]->isDoubleTy()); CPPUNIT_ASSERT(types[1]->isIntegerTy(64)); CPPUNIT_ASSERT(types[2]->isPointerTy()); type = types[2]->getPointerElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isArrayTy()); type = type->getArrayElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); } void TestFunctionTypes::testLLVMFunctionTypeFromSignature() { using openvdb::ax::codegen::llvmFunctionTypeFromSignature; unittest_util::LLVMState state; llvm::FunctionType* ftype = nullptr; std::vector<llvm::Type*> types; ftype = llvmFunctionTypeFromSignature<void()>(state.context()); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(0u, ftype->getNumParams()); ftype = llvmFunctionTypeFromSignature<float(double, int64_t, float(*)[3])>(state.context()); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isFloatTy()); CPPUNIT_ASSERT_EQUAL(3u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isDoubleTy()); CPPUNIT_ASSERT(ftype->getParamType(1)->isIntegerTy(64)); CPPUNIT_ASSERT(ftype->getParamType(2)->isPointerTy()); llvm::Type* type = ftype->getParamType(2)->getPointerElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isArrayTy()); type = type->getArrayElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); } void TestFunctionTypes::testPrintSignature() { using openvdb::ax::codegen::printSignature; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); std::vector<llvm::Type*> types; const llvm::Type* vt = llvm::Type::getVoidTy(C); std::ostringstream os; printSignature(os, types, vt); CPPUNIT_ASSERT(os.str() == "void()"); os.str(""); types.emplace_back(llvm::Type::getInt32Ty(C)); types.emplace_back(llvm::Type::getInt64Ty(C)); printSignature(os, types, vt); CPPUNIT_ASSERT_EQUAL(std::string("void(i32; i64)"), os.str()); os.str(""); printSignature(os, types, vt, "test"); CPPUNIT_ASSERT_EQUAL(std::string("void test(i32; i64)"), os.str()); os.str(""); printSignature(os, types, vt, "", {"one"}, true); CPPUNIT_ASSERT_EQUAL(std::string("void(int32 one; int64)"), os.str()); os.str(""); printSignature(os, types, vt, "", {"one", "two"}, true); CPPUNIT_ASSERT_EQUAL(std::string("void(int32 one; int64 two)"), os.str()); os.str(""); printSignature(os, types, vt, "1", {"one", "two", "three"}, true); CPPUNIT_ASSERT_EQUAL(std::string("void 1(int32 one; int64 two)"), os.str()); os.str(""); printSignature(os, types, vt, "1", {"", "two"}, false); CPPUNIT_ASSERT_EQUAL(std::string("void 1(i32; i64 two)"), os.str()); os.str(""); printSignature(os, types, vt, "1", {"", "two"}, false); CPPUNIT_ASSERT_EQUAL(std::string("void 1(i32; i64 two)"), os.str()); os.str(""); types.emplace_back(llvm::Type::getInt8PtrTy(C)); types.emplace_back(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)); printSignature(os, types, llvm::Type::getInt64Ty(C), "test", {"", "two"}, true); CPPUNIT_ASSERT_EQUAL(std::string("int64 test(int32; int64 two; i8*; vec3i)"), os.str()); os.str(""); types.clear(); printSignature(os, types, llvm::Type::getInt64Ty(C), "test", {"", "two"}); CPPUNIT_ASSERT_EQUAL(std::string("i64 test()"), os.str()); os.str(""); } void TestFunctionTypes::testFunctionCreate() { using openvdb::ax::codegen::Function; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); std::vector<llvm::Type*> types; llvm::Type* type = nullptr; std::ostringstream os; Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)}, llvm::Type::getVoidTy(C), "ax.test")); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(types[0]->isIntegerTy(32)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(1), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(1))); // test create llvm::Function* function = test->create(C); // additional create call should create a new function CPPUNIT_ASSERT(function != test->create(C)); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); llvm::FunctionType* ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(32)); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.test")); function = test->create(M); // additional call should match CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.test")); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(32)); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test print os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("void name(int32)"), os.str()); // // Test empty signature test.reset(new TestFunction({}, llvm::Type::getInt32Ty(C), "ax.empty.test")); types.clear(); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(0), types.size()); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isIntegerTy(32)); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.empty.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(0), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(0), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(0u, ftype->getNumParams()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.empty.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.empty.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.empty.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // test print os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("int32 name()"), os.str()); // // Test scalar types test.reset(new TestFunction({ llvm::Type::getInt1Ty(C), llvm::Type::getInt16Ty(C), llvm::Type::getInt32Ty(C), llvm::Type::getInt64Ty(C), llvm::Type::getFloatTy(C), llvm::Type::getDoubleTy(C), }, llvm::Type::getInt16Ty(C), "ax.scalars.test")); types.clear(); CPPUNIT_ASSERT_EQUAL(std::string("ax.scalars.test"), std::string(test->symbol())); type = test->types(types, state.context()); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isIntegerTy(16)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0]->isIntegerTy(1)); CPPUNIT_ASSERT(types[1]->isIntegerTy(16)); CPPUNIT_ASSERT(types[2]->isIntegerTy(32)); CPPUNIT_ASSERT(types[3]->isIntegerTy(64)); CPPUNIT_ASSERT(types[4]->isFloatTy()); CPPUNIT_ASSERT(types[5]->isDoubleTy()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(16)); CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(1)); CPPUNIT_ASSERT(ftype->getParamType(1)->isIntegerTy(16)); CPPUNIT_ASSERT(ftype->getParamType(2)->isIntegerTy(32)); CPPUNIT_ASSERT(ftype->getParamType(3)->isIntegerTy(64)); CPPUNIT_ASSERT(ftype->getParamType(4)->isFloatTy()); CPPUNIT_ASSERT(ftype->getParamType(5)->isDoubleTy()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.scalars.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.scalars.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.scalars.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // test print os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("int16 name(bool; int16; int32; int64; float; double)"), os.str()); // // Test scalar ptrs types test.reset(new TestFunction({ llvm::Type::getInt1Ty(C)->getPointerTo(), llvm::Type::getInt16Ty(C)->getPointerTo(), llvm::Type::getInt32Ty(C)->getPointerTo(), llvm::Type::getInt64Ty(C)->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo(), llvm::Type::getDoubleTy(C)->getPointerTo() }, llvm::Type::getInt32Ty(C), "ax.scalarptrs.test")); types.clear(); CPPUNIT_ASSERT_EQUAL(std::string("ax.scalarptrs.test"), std::string(test->symbol())); type = test->types(types, C); CPPUNIT_ASSERT(type->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getInt32Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getDoubleTy(C)->getPointerTo()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::Type::getInt1Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::Type::getInt32Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::Type::getInt64Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::Type::getDoubleTy(C)->getPointerTo()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.scalarptrs.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.scalarptrs.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.scalarptrs.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // // Test array ptrs types test.reset(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo(), // vec3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec4i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec4f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo(), // vec4d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo() // mat3d }, llvm::Type::getInt64Ty(C), "ax.arrayptrs.test")); types.clear(); type = test->types(types, C); CPPUNIT_ASSERT(type->isIntegerTy(64)); CPPUNIT_ASSERT_EQUAL(size_t(15), types.size()); CPPUNIT_ASSERT(types[0] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[6] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[7] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[8] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[9] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo()); CPPUNIT_ASSERT(types[10] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(types[11] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(types[12] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo()); CPPUNIT_ASSERT(types[13] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo()); CPPUNIT_ASSERT(types[14] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(15), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(64)); CPPUNIT_ASSERT_EQUAL(15u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(6) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(7) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(8) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(9) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(10) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(11) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(12) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(13) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(14) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.arrayptrs.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.arrayptrs.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.arrayptrs.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // test print - note mat/i types are not ax types os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("int64 name(vec2i; vec2f; vec2d; vec3i; vec3f; vec3d;" " vec4i; vec4f; vec4d; [9 x i32]*; mat3f; mat3d; [16 x i32]*; mat4f; mat4d)"), os.str()); // // Test void ptr arguments test.reset(new TestFunction({ llvm::Type::getVoidTy(C)->getPointerTo(), llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo(), llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo() }, llvm::Type::getVoidTy(C), "ax.vptrs.test")); types.clear(); // Note that C++ bindings will convert void* to i8* but they should be // unmodified in this example where we use the derived TestFunction type = test->types(types, C); CPPUNIT_ASSERT(type->isVoidTy()); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getVoidTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::Type::getVoidTy(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.vptrs.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.vptrs.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.vptrs.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // // Test creation with builder methods // @note These methods may be moved to the constructor in the future CPPUNIT_ASSERT(test->dependencies().empty()); CPPUNIT_ASSERT(!test->hasParamAttribute(0, llvm::Attribute::ReadOnly)); CPPUNIT_ASSERT(!test->hasParamAttribute(-1, llvm::Attribute::ReadOnly)); test->setDependencies({"dep"}); CPPUNIT_ASSERT_EQUAL(size_t(1), test->dependencies().size()); CPPUNIT_ASSERT_EQUAL(std::string("dep"), std::string(test->dependencies().front())); test->setDependencies({}); CPPUNIT_ASSERT(test->dependencies().empty()); test->setFnAttributes({llvm::Attribute::ReadOnly}); test->setRetAttributes({llvm::Attribute::NoAlias}); test->setParamAttributes(1, {llvm::Attribute::WriteOnly}); test->setParamAttributes(-1, {llvm::Attribute::WriteOnly}); CPPUNIT_ASSERT(!test->hasParamAttribute(0, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(!test->hasParamAttribute(2, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(test->hasParamAttribute(1, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(test->hasParamAttribute(-1, llvm::Attribute::WriteOnly)); function = test->create(C); CPPUNIT_ASSERT(function); llvm::AttributeList list = function->getAttributes(); CPPUNIT_ASSERT(!list.isEmpty()); CPPUNIT_ASSERT(!list.hasParamAttrs(0)); CPPUNIT_ASSERT(!list.hasParamAttrs(2)); CPPUNIT_ASSERT(list.hasParamAttr(1, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(list.hasFnAttribute(llvm::Attribute::ReadOnly)); CPPUNIT_ASSERT(list.hasAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NoAlias)); } void TestFunctionTypes::testFunctionCall() { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::LLVMType; using openvdb::ax::AXString; // { unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)}, llvm::Type::getVoidTy(C), "ax.test")); llvm::Function* function = test->create(M); llvm::Value* arg = B.getInt32(1); llvm::Value* result = test->call({arg}, B, /*cast*/false); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(arg, call->getArgOperand(0)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); // add a ret void to the current function and to the created function, // then check the IR is valid (this will check the function arguments // and creation are all correct) finalizeFunction(B); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); } { unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)}, llvm::Type::getVoidTy(C), "ax.test")); // call first, then create llvm::Value* arg = B.getInt32(1); llvm::Value* result = test->call({arg}, B, /*cast*/false); llvm::Function* function = test->create(M); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(arg, call->getArgOperand(0)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); // add a ret void to the current function and to the created function, // then check the IR is valid (this will check the function arguments // and creation are all correct) finalizeFunction(B); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); } // Now test casting/argument mismatching for most argument types unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); Function::Ptr test(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d llvm::Type::getInt32Ty(C), // int llvm::Type::getInt64Ty(C), // int64 llvm::Type::getFloatTy(C) // float }, llvm::Type::getVoidTy(C), "ax.test")); std::vector<llvm::Type*> expected; test->types(expected, C); // default args llvm::Value* f32c0 = LLVMType<float>::get(C, 0.0f); // float llvm::Value* d64c0 = LLVMType<double>::get(C, 0.0); // double llvm::Value* i32c1 = B.getInt32(1); // int llvm::Value* i64c1 = B.getInt64(1); // int64 llvm::Value* vec3i = openvdb::ax::codegen::arrayPack({i32c1,i32c1,i32c1}, B); // vec3i llvm::Value* vec2d = openvdb::ax::codegen::arrayPack({d64c0,d64c0},B); // vec2d llvm::Value* mat3d = openvdb::ax::codegen::arrayPack({ d64c0,d64c0,d64c0, d64c0,d64c0,d64c0, d64c0,d64c0,d64c0 }, B); // mat3d std::vector<llvm::Value*> args{vec3i, vec2d, mat3d, i32c1, i64c1, f32c0}; llvm::Function* function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); // also finalize the current module function, but set the inset point // just above it so we can continue to verify IR during this test llvm::Value* inst = B.CreateRetVoid(); // This specifies that created instructions should be inserted before // the specified instruction. B.SetInsertPoint(llvm::cast<llvm::Instruction>(inst)); // test no casting needed for valid IR llvm::Value* result = test->call(args, B, /*cast*/false); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT_EQUAL(args[3], call->getArgOperand(3)); CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4)); CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5)); VERIFY_MODULE_IR(&M); // test no casting needed for valid IR, even with cast=true result = test->call(args, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT_EQUAL(args[3], call->getArgOperand(3)); CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4)); CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5)); VERIFY_MODULE_IR(&M); // // Test different types of valid casting llvm::Value* i1c0 = LLVMType<bool>::get(C, true); // bool llvm::Value* vec3f = openvdb::ax::codegen::arrayPack({f32c0,f32c0,f32c0}, B); // vec3f llvm::Value* vec3d = openvdb::ax::codegen::arrayPack({d64c0,d64c0,d64c0}, B); // vec3d llvm::Value* vec2f = openvdb::ax::codegen::arrayPack({f32c0,f32c0},B); // vec2f llvm::Value* vec2i = openvdb::ax::codegen::arrayPack({i32c1,i32c1},B); // vecid llvm::Value* mat3f = openvdb::ax::codegen::arrayPack({ f32c0,f32c0,f32c0, f32c0,f32c0,f32c0, f32c0,f32c0,f32c0 }, B); // mat3f // std::vector<llvm::Value*> argsToCast; argsToCast.emplace_back(vec3f); // vec3f argsToCast.emplace_back(vec2f); // vec2f argsToCast.emplace_back(mat3f); // mat3f argsToCast.emplace_back(i1c0); // bool argsToCast.emplace_back(i1c0); // bool argsToCast.emplace_back(i1c0); // bool result = test->call(argsToCast, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT(argsToCast[0] != call->getArgOperand(0)); CPPUNIT_ASSERT(argsToCast[1] != call->getArgOperand(1)); CPPUNIT_ASSERT(argsToCast[2] != call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3)); CPPUNIT_ASSERT(argsToCast[4] != call->getArgOperand(4)); CPPUNIT_ASSERT(argsToCast[5] != call->getArgOperand(5)); CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType()); CPPUNIT_ASSERT(expected[1] == call->getArgOperand(1)->getType()); CPPUNIT_ASSERT(expected[2] == call->getArgOperand(2)->getType()); CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType()); CPPUNIT_ASSERT(expected[4] == call->getArgOperand(4)->getType()); CPPUNIT_ASSERT(expected[5] == call->getArgOperand(5)->getType()); VERIFY_MODULE_IR(&M); // argsToCast.clear(); argsToCast.emplace_back(vec3d); // vec3d argsToCast.emplace_back(vec2i); // vec2i argsToCast.emplace_back(mat3d); // mat3d - no cast required argsToCast.emplace_back(f32c0); // float argsToCast.emplace_back(f32c0); // float argsToCast.emplace_back(f32c0); // float - no cast required result = test->call(argsToCast, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT(argsToCast[0] != call->getArgOperand(0)); CPPUNIT_ASSERT(argsToCast[1] != call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3)); CPPUNIT_ASSERT(argsToCast[4] != call->getArgOperand(4)); CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5)); CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType()); CPPUNIT_ASSERT(expected[1] == call->getArgOperand(1)->getType()); CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType()); CPPUNIT_ASSERT(expected[4] == call->getArgOperand(4)->getType()); VERIFY_MODULE_IR(&M); // argsToCast.clear(); argsToCast.emplace_back(vec3i); // vec3i - no cast required argsToCast.emplace_back(vec2d); // vec2d - no cast required argsToCast.emplace_back(mat3d); // mat3d - no cast required argsToCast.emplace_back(i64c1); // int64 argsToCast.emplace_back(i64c1); // int64 - no cast required argsToCast.emplace_back(i64c1); // int64 result = test->call(argsToCast, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3)); CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4)); CPPUNIT_ASSERT(argsToCast[5] != call->getArgOperand(5)); CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType()); CPPUNIT_ASSERT(expected[5] == call->getArgOperand(5)->getType()); VERIFY_MODULE_IR(&M); // // Test that invalid IR is generated if casting cannot be performed. // This is just to test that call doesn't error or behave unexpectedly // Test called with castable arg but cast is false. Test arg is left // unchanged and IR is invalid due to signature size result = test->call({vec3f}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); // should be the same as cast is false CPPUNIT_ASSERT(vec3f == call->getArgOperand(0)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // Test called with castable arg with cast true. Test IR is invalid // due to signature size result = test->call({vec3f}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); // shouldn't be the same as it should have been cast CPPUNIT_ASSERT(vec3f != call->getArgOperand(0)); CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType()); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // Test called with non castable args, but matchign signature size. // Test IR is invalid due to cast being off result = test->call(argsToCast, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); // no casting, args should match operands CPPUNIT_ASSERT(argsToCast[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(argsToCast[1] == call->getArgOperand(1)); CPPUNIT_ASSERT(argsToCast[2] == call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] == call->getArgOperand(3)); CPPUNIT_ASSERT(argsToCast[4] == call->getArgOperand(4)); CPPUNIT_ASSERT(argsToCast[5] == call->getArgOperand(5)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // // Test strings llvm::Type* axstr = LLVMType<AXString*>::get(C); // str* llvm::Type* chars = LLVMType<char*>::get(C); // char* // build values llvm::Value* chararray = B.CreateGlobalStringPtr("tmp"); // char* llvm::Constant* constLoc = llvm::cast<llvm::Constant>(chararray); llvm::Constant* size = LLVMType<AXString::SizeType>::get(C, static_cast<AXString::SizeType>(3)); llvm::Value* constStr = LLVMType<AXString>::get(C, constLoc, size); llvm::Value* strptr = B.CreateAlloca(LLVMType<AXString>::get(C)); B.CreateStore(constStr, strptr); // void ax.str.test(AXString*, char*) test.reset(new TestFunction({axstr, chars}, llvm::Type::getVoidTy(C), "ax.str.test")); std::vector<llvm::Value*> stringArgs{strptr, chararray}; function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); result = test->call(stringArgs, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1)); // result = test->call(stringArgs, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1)); // Test AXString -> char* stringArgs[0] = strptr; stringArgs[1] = strptr; result = test->call(stringArgs, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] != call->getArgOperand(1)); CPPUNIT_ASSERT(chars == call->getArgOperand(1)->getType()); VERIFY_MODULE_IR(&M); // Test char* does not catch to AXString stringArgs[0] = chararray; stringArgs[1] = chararray; result = test->call(stringArgs, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); // no valid casting CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // // Test ** pointers test.reset(new TestFunction({ llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(), llvm::Type::getDoubleTy(C)->getPointerTo()->getPointerTo() }, llvm::Type::getVoidTy(C), "ax.ptrs.test")); function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); llvm::Value* fptr = B.CreateAlloca(llvm::Type::getFloatTy(C)->getPointerTo()); llvm::Value* dptr = B.CreateAlloca(llvm::Type::getDoubleTy(C)->getPointerTo()); result = test->call({fptr, dptr}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(fptr == call->getArgOperand(0)); CPPUNIT_ASSERT(dptr == call->getArgOperand(1)); VERIFY_MODULE_IR(&M); // result = test->call({fptr, dptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(fptr == call->getArgOperand(0)); CPPUNIT_ASSERT(dptr == call->getArgOperand(1)); VERIFY_MODULE_IR(&M); // switch the points, check no valid casting result = test->call({dptr, fptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); // args unaltered as casting is invalid CPPUNIT_ASSERT(dptr == call->getArgOperand(0)); CPPUNIT_ASSERT(fptr == call->getArgOperand(1)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // // Test void pointers test.reset(new TestFunction({ LLVMType<void*>::get(C), }, llvm::Type::getVoidTy(C), "ax.void.test")); function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); llvm::Value* vptrptr = B.CreateAlloca(LLVMType<void*>::get(C)); llvm::Value* vptr = B.CreateLoad(vptrptr); result = test->call({vptr}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT(vptr == call->getArgOperand(0)); VERIFY_MODULE_IR(&M); // result = test->call({vptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT(vptr == call->getArgOperand(0)); VERIFY_MODULE_IR(&M); // verify no cast from other pointers to void* result = test->call({fptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT(fptr == call->getArgOperand(0)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); } void TestFunctionTypes::testFunctionMatch() { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::LLVMType; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); Function::SignatureMatch match; const std::vector<llvm::Type*> scalars { llvm::Type::getInt1Ty(C), // bool llvm::Type::getInt16Ty(C), // int16 llvm::Type::getInt32Ty(C), // int llvm::Type::getInt64Ty(C), // int64 llvm::Type::getFloatTy(C), // float llvm::Type::getDoubleTy(C) // double }; const std::vector<llvm::Type*> array2 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo() // vec2d }; const std::vector<llvm::Type*> array3 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo() // vec3d }; const std::vector<llvm::Type*> array4 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo() // vec3d }; const std::vector<llvm::Type*> array9 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo() // mat3d }; const std::vector<llvm::Type*> array16 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo() // mat3d }; const std::vector<std::vector<llvm::Type*>> arrays { array2, array3, array4, array9, array16, }; // test empty explicit match Function::Ptr test(new TestFunction({}, llvm::Type::getVoidTy(C), "ax.test")); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // std::vector<llvm::Type*> types; types.insert(types.end(), scalars.begin(), scalars.end()); types.insert(types.end(), array2.begin(), array2.end()); types.insert(types.end(), array3.begin(), array3.end()); types.insert(types.end(), array4.begin(), array4.end()); types.insert(types.end(), array9.begin(), array9.end()); types.insert(types.end(), array16.begin(), array16.end()); types.insert(types.end(), LLVMType<openvdb::ax::AXString*>::get(C)); // check types are unique CPPUNIT_ASSERT_EQUAL(std::set<llvm::Type*>(types.begin(), types.end()).size(), types.size()); // test.reset(new TestFunction({ llvm::Type::getInt1Ty(C), // bool llvm::Type::getInt16Ty(C), // int16 llvm::Type::getInt32Ty(C), // int32 llvm::Type::getInt64Ty(C), // int64 llvm::Type::getFloatTy(C), // float llvm::Type::getDoubleTy(C), // double llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo(), // vec3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec4i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec4f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo(), // vec4d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat4f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo(), // mat4d LLVMType<openvdb::ax::AXString*>::get(C) // string }, llvm::Type::getVoidTy(C), "ax.test")); match = test->match(types, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test size match llvm::Type* i32t = llvm::Type::getInt32Ty(C); test.reset(new TestFunction({i32t}, llvm::Type::getVoidTy(C), "ax.test")); match = test->match({llvm::ArrayType::get(i32t, 1)->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Size); match = test->match({i32t->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Size); // test no match match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(Function::None, match); match = test->match({i32t, i32t}, C); CPPUNIT_ASSERT_EQUAL(Function::None, match); // test scalar matches for (size_t i = 0; i < scalars.size(); ++i) { test.reset(new TestFunction({scalars[i]}, llvm::Type::getVoidTy(C), "ax.test")); std::vector<llvm::Type*> copy(scalars); std::swap(copy[i], copy.back()); copy.pop_back(); CPPUNIT_ASSERT_EQUAL(size_t(5), copy.size()); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({scalars[i]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[0]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[1]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[2]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[3]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[4]}, C)); } // // Test array matches - no implicit cast as operands are not marked as readonly for (const std::vector<llvm::Type*>& types : arrays) { // test these array types for (size_t i = 0; i < types.size(); ++i) { test.reset(new TestFunction({types[i]}, llvm::Type::getVoidTy(C), "ax.test")); std::vector<llvm::Type*> copy(types); std::swap(copy[i], copy.back()); copy.pop_back(); CPPUNIT_ASSERT_EQUAL(size_t(2), copy.size()); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({types[i]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({copy[0]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({copy[1]}, C)); // test non matching size arrays for (const std::vector<llvm::Type*>& inputs : arrays) { if (&types == &inputs) continue; for (size_t i = 0; i < inputs.size(); ++i) { CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({inputs[i]}, C)); } } } } // // Test array matches with readonly marking for (const std::vector<llvm::Type*>& types : arrays) { // test these array types for (size_t i = 0; i < types.size(); ++i) { test.reset(new TestFunction({types[i]}, llvm::Type::getVoidTy(C), "ax.test")); test->setParamAttributes(0, {llvm::Attribute::ReadOnly}); std::vector<llvm::Type*> copy(types); std::swap(copy[i], copy.back()); copy.pop_back(); CPPUNIT_ASSERT_EQUAL(size_t(2), copy.size()); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({types[i]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[0]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[1]}, C)); // test non matching size arrays for (const std::vector<llvm::Type*>& inputs : arrays) { if (&types == &inputs) continue; for (size_t i = 0; i < inputs.size(); ++i) { CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({inputs[i]}, C)); } } } } // test strings test.reset(new TestFunction({LLVMType<char*>::get(C)}, llvm::Type::getVoidTy(C), "ax.test")); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({LLVMType<openvdb::ax::AXString*>::get(C)}, C)); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({LLVMType<char*>::get(C)}, C)); test->setParamAttributes(0, {llvm::Attribute::ReadOnly}); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({LLVMType<openvdb::ax::AXString*>::get(C)}, C)); test.reset(new TestFunction({LLVMType<openvdb::ax::AXString*>::get(C)}, llvm::Type::getVoidTy(C), "ax.test")); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({LLVMType<char*>::get(C)}, C)); // test pointers llvm::Type* fss = llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(); llvm::Type* dss = llvm::Type::getDoubleTy(C)->getPointerTo()->getPointerTo(); test.reset(new TestFunction({fss, dss}, llvm::Type::getVoidTy(C), "ax.ptrs.test")); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({fss, dss}, C)); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({fss, fss}, C)); // Even if pointers are marked as readonly, casting is not supported test->setParamAttributes(0, {llvm::Attribute::ReadOnly}); test->setParamAttributes(1, {llvm::Attribute::ReadOnly}); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({fss, fss}, C)); } void TestFunctionTypes::testCFunctions() { using openvdb::ax::codegen::CFunction; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Type* returnType = nullptr; std::vector<llvm::Type*> types; // test basic creation CFunction<void()> voidfunc("voidfunc", &CBindings::voidfunc); CFunction<int16_t(bool,int16_t,int32_t,int64_t,float,double)> scalars("scalarfunc", &CBindings::scalarfunc); CFunction<int32_t(bool*,int16_t*,int32_t*,int64_t*,float*,double*)> scalarptrs("scalatptsfunc", &CBindings::scalatptsfunc); CFunction<int64_t(bool(*)[1],int16_t(*)[2],int32_t(*)[3],int64_t(*)[4],float(*)[5],double(*)[6])> arrayptrs("arrayfunc", &CBindings::arrayfunc); CFunction<float()> select("tmplfunc", (float(*)())(CBindings::tmplfunc)); CFunction<void(void*, void**, void***, float*, float**, float***)> mindirect("multiptrfunc", &CBindings::multiptrfunc); // test static void function CPPUNIT_ASSERT_EQUAL(size_t(0), voidfunc.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::voidfunc), voidfunc.address()); CPPUNIT_ASSERT_EQUAL(std::string("voidfunc"), std::string(voidfunc.symbol())); // test scalar arguments CPPUNIT_ASSERT_EQUAL(size_t(6), scalars.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::scalarfunc), scalars.address()); CPPUNIT_ASSERT_EQUAL(std::string("scalarfunc"), std::string(scalars.symbol())); // test scalar ptr arguments CPPUNIT_ASSERT_EQUAL(size_t(6), scalarptrs.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::scalatptsfunc), scalarptrs.address()); CPPUNIT_ASSERT_EQUAL(std::string("scalatptsfunc"), std::string(scalarptrs.symbol())); // test array ptr arguments CPPUNIT_ASSERT_EQUAL(size_t(6), arrayptrs.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::arrayfunc), arrayptrs.address()); CPPUNIT_ASSERT_EQUAL(std::string("arrayfunc"), std::string(arrayptrs.symbol())); // test selected template functions CPPUNIT_ASSERT_EQUAL(size_t(0), select.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::tmplfunc<float>), select.address()); CPPUNIT_ASSERT_EQUAL(std::string("tmplfunc"), std::string(select.symbol())); // test multiple indirection layers CPPUNIT_ASSERT_EQUAL(size_t(6), mindirect.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::multiptrfunc), mindirect.address()); CPPUNIT_ASSERT_EQUAL(std::string("multiptrfunc"), std::string(mindirect.symbol())); // // Test types // test scalar arguments returnType = scalars.types(types, C); CPPUNIT_ASSERT(returnType->isIntegerTy(16)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0]->isIntegerTy(1)); CPPUNIT_ASSERT(types[1]->isIntegerTy(16)); CPPUNIT_ASSERT(types[2]->isIntegerTy(32)); CPPUNIT_ASSERT(types[3]->isIntegerTy(64)); CPPUNIT_ASSERT(types[4]->isFloatTy()); CPPUNIT_ASSERT(types[5]->isDoubleTy()); types.clear(); // test scalar ptr arguments returnType = scalarptrs.types(types, C); CPPUNIT_ASSERT(returnType->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getInt32Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getDoubleTy(C)->getPointerTo()); types.clear(); // test array ptr arguments returnType = arrayptrs.types(types, C); CPPUNIT_ASSERT(returnType->isIntegerTy(64)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::ArrayType::get(llvm::Type::getInt16Ty(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 5)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 6)->getPointerTo()); types.clear(); // test void ptr arguments // void* are inferred as int8_t* types returnType = mindirect.types(types, C); CPPUNIT_ASSERT(returnType->isVoidTy()); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt8PtrTy(C)); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt8PtrTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getInt8PtrTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); } void TestFunctionTypes::testCFunctionCF() { using openvdb::ax::codegen::CFunction; using openvdb::ax::codegen::LLVMType; static auto cftest1 = []() -> int32_t { return 10; }; static auto cftest2 = [](float a) -> float { return a; }; // currently unsupported for arrays static auto cftest3 = [](float(*a)[3]) -> float { return (*a)[0]; }; // currently unsupported for return voids static auto cftest4 = [](float* a) -> void { (*a)*=5.0f; }; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::IRBuilder<> B(state.scratchBlock()); // test with no args CFunction<int32_t()> test1("ax.test1", cftest1); // off by default CPPUNIT_ASSERT(!test1.hasConstantFold()); CPPUNIT_ASSERT(test1.fold({B.getInt32(1)}, C) == nullptr); test1.setConstantFold(true); llvm::Value* result = test1.fold({B.getInt32(1)}, C); CPPUNIT_ASSERT(result); llvm::ConstantInt* constant = llvm::dyn_cast<llvm::ConstantInt>(result); CPPUNIT_ASSERT(constant); CPPUNIT_ASSERT_EQUAL(uint64_t(10), constant->getLimitedValue()); // test with scalar arg CFunction<float(float)> test2("ax.test2", cftest2); test2.setConstantFold(true); result = test2.fold({LLVMType<float>::get(C, -3.2f)}, C); CPPUNIT_ASSERT(result); llvm::ConstantFP* constantfp = llvm::dyn_cast<llvm::ConstantFP>(result); CPPUNIT_ASSERT(constantfp); const llvm::APFloat& apf = constantfp->getValueAPF(); CPPUNIT_ASSERT_EQUAL(-3.2f, apf.convertToFloat()); // test unsupported CFunction<float(float(*)[3])> test3("ax.test3", cftest3); test3.setConstantFold(true); // constant arg (verify it would 100% match) // note that this arg is fundamentally the wrong type for this function // and the way in which we support vector types anyway (by ptr) - but because // its impossible to have a constant ptr, use this for now as this will most // likely be the way we support folding for arrays in the future llvm::Value* arg = LLVMType<float[3]>::get(C, {1,2,3}); CPPUNIT_ASSERT(llvm::isa<llvm::Constant>(arg)); // check fold fails CPPUNIT_ASSERT(test3.fold({arg}, C) == nullptr); // CFunction<void(float*)> test4("ax.test4", cftest4); test4.setConstantFold(true); // constant arg (verify it would 100% match) llvm::Value* nullfloat = llvm::ConstantPointerNull::get(LLVMType<float*>::get(C)); std::vector<llvm::Type*> types; test4.types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(nullfloat->getType() == types.front()); CPPUNIT_ASSERT(test4.fold({nullfloat}, C) == nullptr); } void TestFunctionTypes::testIRFunctions() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::IRFunctionBase; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); // Small test to check the templated version of IRFunction::types. // All other checks work with the IRFunctionBase class { using openvdb::ax::codegen::IRFunction; static auto generate = [](const std::vector<llvm::Value*>&, llvm::IRBuilder<>&) -> llvm::Value* { return nullptr; }; IRFunction<double(bool, int16_t*, int32_t(*)[1], int64_t, float*, double(*)[2])> mix("mix", generate); CPPUNIT_ASSERT_EQUAL(std::string("mix"), std::string(mix.symbol())); std::vector<llvm::Type*> types; llvm::Type* returnType = mix.types(types, C); CPPUNIT_ASSERT(returnType->isDoubleTy()); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo()); } llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock("TestFunction")); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); B.SetInsertPoint(finalizeFunction(B)); // Build the following function: // float test(float a, float b) { // float c = a + b; // return c; // } // how to handle the terminating instruction int termMode = 0; std::string expectedName; auto generate = [&B, &M, &termMode, &expectedName] (const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& _B) -> llvm::Value* { // test the builder is pointing to the correct location CPPUNIT_ASSERT(&B != &_B); llvm::BasicBlock* Block = _B.GetInsertBlock(); CPPUNIT_ASSERT(Block); CPPUNIT_ASSERT(Block->empty()); llvm::Function* F = Block->getParent(); CPPUNIT_ASSERT(F); CPPUNIT_ASSERT_EQUAL(expectedName, std::string(F->getName())); llvm::Module* _M = F->getParent(); CPPUNIT_ASSERT_EQUAL(&M, _M); CPPUNIT_ASSERT_EQUAL(size_t(2), args.size()); CPPUNIT_ASSERT(args[0] == llvm::cast<llvm::Value>(F->arg_begin())); CPPUNIT_ASSERT(args[1] == llvm::cast<llvm::Value>(F->arg_begin()+1)); CPPUNIT_ASSERT(args[0]->getType()->isFloatTy()); CPPUNIT_ASSERT(args[1]->getType()->isFloatTy()); llvm::Value* result = _B.CreateFAdd(args[0], args[1]); if (termMode == 0) return _B.CreateRet(result); if (termMode == 1) return result; if (termMode == 2) return nullptr; CPPUNIT_ASSERT(false); return nullptr; }; llvm::Function* function = nullptr; expectedName = "ax.ir.test"; Function::Ptr test(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), expectedName, generate)); // Test function prototype creation CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); function = test->create(C); CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT(function != test->create(C)); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT_EQUAL(size_t(2), function->arg_size()); llvm::FunctionType* ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isFloatTy()); CPPUNIT_ASSERT_EQUAL(2u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isFloatTy()); CPPUNIT_ASSERT(ftype->getParamType(1)->isFloatTy()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // Test function creation with module and IR generation CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.ir.test")); CPPUNIT_ASSERT(!function->empty()); llvm::BasicBlock* BB = &(function->getEntryBlock()); // two instructions - the add and return CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size()); auto iter = BB->begin(); llvm::BinaryOperator* binary = llvm::dyn_cast<llvm::BinaryOperator>(iter); CPPUNIT_ASSERT(binary); CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()), binary->getOperand(0)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1), binary->getOperand(1)); ++iter; llvm::ReturnInst* ret = llvm::dyn_cast<llvm::ReturnInst>(iter); CPPUNIT_ASSERT(ret); llvm::Value* rvalue = ret->getReturnValue(); CPPUNIT_ASSERT(rvalue); CPPUNIT_ASSERT(rvalue->getType()->isFloatTy()); // the return is the result of the bin op CPPUNIT_ASSERT_EQUAL(rvalue, llvm::cast<llvm::Value>(binary)); ++iter; CPPUNIT_ASSERT(BB->end() == iter); // additional call should match CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // verify IR VERIFY_FUNCTION_IR(function); // Test call llvm::Value* fp1 = LLVMType<float>::get(C, 1.0f); llvm::Value* fp2 = LLVMType<float>::get(C, 2.0f); llvm::Value* result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call), llvm::cast<llvm::Value>(--B.GetInsertPoint())); // verify IR VERIFY_FUNCTION_IR(function); VERIFY_FUNCTION_IR(BaseFunction); VERIFY_MODULE_IR(&M); // // Test auto return - the IRFunctionBase should handle the return // also test that calling Function::call correctly creates the // function in the module expectedName = "ax.ir.autoret.test"; termMode = 1; test.reset(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), expectedName, generate)); CPPUNIT_ASSERT(!M.getFunction("ax.ir.autoret.test")); result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); function = M.getFunction("ax.ir.autoret.test"); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1)); CPPUNIT_ASSERT(!function->empty()); BB = &(function->getEntryBlock()); // two instructions - the add and return CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size()); iter = BB->begin(); binary = llvm::dyn_cast<llvm::BinaryOperator>(iter); CPPUNIT_ASSERT(binary); CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()), binary->getOperand(0)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1), binary->getOperand(1)); ++iter; ret = llvm::dyn_cast<llvm::ReturnInst>(iter); CPPUNIT_ASSERT(ret); rvalue = ret->getReturnValue(); CPPUNIT_ASSERT(rvalue); CPPUNIT_ASSERT(rvalue->getType()->isFloatTy()); // the return is the result of the bin op CPPUNIT_ASSERT_EQUAL(rvalue, llvm::cast<llvm::Value>(binary)); ++iter; CPPUNIT_ASSERT(BB->end() == iter); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call), llvm::cast<llvm::Value>(--B.GetInsertPoint())); // verify VERIFY_FUNCTION_IR(function); VERIFY_FUNCTION_IR(BaseFunction); VERIFY_MODULE_IR(&M); // Test invalid return expectedName = "ax.ir.retnull.test"; termMode = 2; test.reset(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), expectedName, generate)); CPPUNIT_ASSERT(!M.getFunction("ax.ir.retnull.test")); // will throw as the function expects a float ret, not void or null // NOTE: The function will still be created, but be in an invaid state CPPUNIT_ASSERT_THROW(test->create(M), openvdb::AXCodeGenError); function = M.getFunction("ax.ir.retnull.test"); CPPUNIT_ASSERT(function); result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1)); BB = &(function->getEntryBlock()); // two instructions - the add and return CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size()); iter = BB->begin(); binary = llvm::dyn_cast<llvm::BinaryOperator>(iter); CPPUNIT_ASSERT(binary); CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()), binary->getOperand(0)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1), binary->getOperand(1)); ++iter; ret = llvm::dyn_cast<llvm::ReturnInst>(iter); CPPUNIT_ASSERT(ret); CPPUNIT_ASSERT(!ret->getReturnValue()); ++iter; CPPUNIT_ASSERT(BB->end() == iter); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call), llvm::cast<llvm::Value>(--B.GetInsertPoint())); // verify - function is invalid as it returns void but the // prototype wants a float VERIFY_FUNCTION_IR_INVALID(function); VERIFY_FUNCTION_IR(BaseFunction); VERIFY_MODULE_IR_INVALID(&M); // // Test embedded IR auto embdedGen = [&B, &M] (const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& _B) -> llvm::Value* { // test the builder is pointing to the correct location // note, for embedded IR, the same builder will be used CPPUNIT_ASSERT_EQUAL(&B, &_B); llvm::BasicBlock* Block = _B.GetInsertBlock(); CPPUNIT_ASSERT(Block); CPPUNIT_ASSERT(!Block->empty()); llvm::Function* F = Block->getParent(); CPPUNIT_ASSERT(F); CPPUNIT_ASSERT_EQUAL(std::string("TestFunction"), std::string(F->getName())); CPPUNIT_ASSERT_EQUAL(&M, F->getParent()); CPPUNIT_ASSERT_EQUAL(size_t(2), args.size()); CPPUNIT_ASSERT(args[0]->getType()->isFloatTy()); CPPUNIT_ASSERT(args[1]->getType()->isFloatTy()); // Can't just do a CreateFAdd as the IR builder won't actually even // write the instruction as its const and unused - so store in a new // alloc llvm::Value* alloc = _B.CreateAlloca(args[0]->getType()); _B.CreateStore(args[0], alloc); return _B.CreateLoad(alloc); }; test.reset(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), "ax.ir.embed.test", embdedGen)); static_cast<IRFunctionBase&>(*test).setEmbedIR(true); // test create does nothing CPPUNIT_ASSERT(test->create(C) == nullptr); CPPUNIT_ASSERT(test->create(M) == nullptr); // test call CPPUNIT_ASSERT(!M.getFunction("ax.ir.embed.test")); result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!M.getFunction("ax.ir.embed.test")); auto IP = B.GetInsertPoint(); // check the prev instructions are as expected CPPUNIT_ASSERT(llvm::isa<llvm::LoadInst>(--IP)); CPPUNIT_ASSERT(llvm::isa<llvm::StoreInst>(--IP)); CPPUNIT_ASSERT(llvm::isa<llvm::AllocaInst>(--IP)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); } void TestFunctionTypes::testSRETFunctions() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::CFunctionSRet; using openvdb::ax::codegen::IRFunctionSRet; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); std::vector<llvm::Type*> types; llvm::Type* type = nullptr; llvm::Value* result = nullptr; llvm::Function* function = nullptr; llvm::FunctionType* ftype = nullptr; Function::SignatureMatch match; std::ostringstream os; B.SetInsertPoint(finalizeFunction(B)); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); // test C SRET static auto csret = [](float(*output)[3]) { (*output)[0] = 1.0f; }; Function::Ptr test(new CFunctionSRet<void(float(*)[3])> ("ax.c.test", (void(*)(float(*)[3]))(csret))); // test types llvm::Type* vec3f = llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3); type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.c.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(1), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); // test printing os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("vec3f name()"), os.str()); // test match match = test->match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); match = test->Function::match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test create CPPUNIT_ASSERT(!M.getFunction("ax.c.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.c.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo()); // test call - sret function do not return the CallInst as the value result = test->call({}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result)); CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo()); CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); // // test sret with two arguments static auto csret2 = [](float(*output)[3], float(*input)[3]) { (*output)[0] = (*input)[0]; }; test.reset(new CFunctionSRet<void(float(*)[3],float(*)[3])> ("ax.c2.test", (void(*)(float(*)[3],float(*)[3]))(csret2))); types.clear(); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(2), types.size()); CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(types[1] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.c2.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(2), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(1))); // test printing os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("vec3f name(vec3f)"), os.str()); // test match match = test->match({vec3f->getPointerTo(),vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->Function::match({vec3f->getPointerTo(),vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test create CPPUNIT_ASSERT(!M.getFunction("ax.c2.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.c2.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(2), function->arg_size()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(2u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == vec3f->getPointerTo()); // test call - sret function do not return the CallInst as the value llvm::Value* f32c0 = LLVMType<float>::get(C, 0.0f); // float llvm::Value* vec3fv = openvdb::ax::codegen::arrayPack({f32c0,f32c0,f32c0}, B); // vec3f result = test->call({vec3fv}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result)); CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo()); CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); // // test IR SRET // Build the following function: // void test(vec3f* a) { // a[0] = 1.0f; // } // which has a front interface of: // vec3f test() { vec3f a; a[0] = 1; return a;}; // auto generate = [&B, &M] (const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& _B) -> llvm::Value* { // test the builder is pointing to the correct location CPPUNIT_ASSERT(&B != &_B); llvm::BasicBlock* Block = _B.GetInsertBlock(); CPPUNIT_ASSERT(Block); CPPUNIT_ASSERT(Block->empty()); llvm::Function* F = Block->getParent(); CPPUNIT_ASSERT(F); CPPUNIT_ASSERT_EQUAL(std::string("ax.ir.test"), std::string(F->getName())); llvm::Module* _M = F->getParent(); CPPUNIT_ASSERT_EQUAL(&M, _M); CPPUNIT_ASSERT_EQUAL(size_t(1), args.size()); CPPUNIT_ASSERT(args[0] == llvm::cast<llvm::Value>(F->arg_begin())); CPPUNIT_ASSERT(args[0]->getType() == llvm::ArrayType::get(llvm::Type::getFloatTy(_B.getContext()), 3)->getPointerTo()); llvm::Value* e0 = _B.CreateConstGEP2_64(args[0], 0, 0); _B.CreateStore(LLVMType<float>::get(_B.getContext(), 1.0f), e0); return nullptr; }; test.reset(new IRFunctionSRet<void(float(*)[3])>("ax.ir.test", generate)); types.clear(); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.ir.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(1), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); // test printing os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("vec3f name()"), os.str()); // test match match = test->match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); match = test->Function::match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test create CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.ir.test")); CPPUNIT_ASSERT(!function->empty()); // test instructions llvm::BasicBlock* BB = &(function->getEntryBlock()); CPPUNIT_ASSERT_EQUAL(size_t(3), BB->size()); auto iter = BB->begin(); CPPUNIT_ASSERT(llvm::isa<llvm::GetElementPtrInst>(iter++)); CPPUNIT_ASSERT(llvm::isa<llvm::StoreInst>(iter++)); CPPUNIT_ASSERT(llvm::isa<llvm::ReturnInst>(iter++)); CPPUNIT_ASSERT(BB->end() == iter); // additional call should match CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // check function type ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo()); // test call - sret function do not return the CallInst as the value result = test->call({}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result)); CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo()); CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); }
90,722
C++
40.014014
129
0.637784
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestTypes.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/Types.h> #include <openvdb/math/Vec2.h> #include <openvdb/math/Vec3.h> #include <openvdb/math/Vec4.h> #include <openvdb/math/Mat3.h> #include <openvdb/math/Mat4.h> #include <cppunit/extensions/HelperMacros.h> class TestTypes : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestTypes); CPPUNIT_TEST(testTypes); CPPUNIT_TEST(testVDBTypes); CPPUNIT_TEST_SUITE_END(); void testTypes(); void testVDBTypes(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestTypes); void TestTypes::testTypes() { using openvdb::ax::codegen::LLVMType; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); // scalar types CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt1Ty(C)), LLVMType<bool>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt8Ty(C)), LLVMType<int8_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt16Ty(C)), LLVMType<int16_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt32Ty(C)), LLVMType<int32_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt64Ty(C)), LLVMType<int64_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getFloatTy(C)), LLVMType<float>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getDoubleTy(C)), LLVMType<double>::get(C)); // scalar values CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt1Ty(C), true)), LLVMType<bool>::get(C, true)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt8Ty(C), int8_t(1))), LLVMType<int8_t>::get(C, int8_t(1))); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt16Ty(C), int16_t(2))), LLVMType<int16_t>::get(C, int16_t(2))); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), int32_t(3))), LLVMType<int32_t>::get(C, int32_t(3))); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt64Ty(C), int64_t(4))), LLVMType<int64_t>::get(C, int64_t(4))); // array types #if LLVM_VERSION_MAJOR > 6 CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1)), LLVMType<bool[1]>::get(C)); #endif CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt8Ty(C), 2)), LLVMType<int8_t[2]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt16Ty(C), 3)), LLVMType<int16_t[3]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)), LLVMType<int32_t[4]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 5)), LLVMType<int64_t[5]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 6)), LLVMType<float[6]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 7)), LLVMType<double[7]>::get(C)); // array values #if LLVM_VERSION_MAJOR > 6 CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get<bool>(C, {true})), LLVMType<bool[1]>::get(C, {true})); #endif const std::vector<uint8_t> veci8{1,2}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci8)), LLVMType<uint8_t[2]>::get(C, {1,2})); const std::vector<uint16_t> veci16{1,2,3}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci16)), LLVMType<uint16_t[3]>::get(C, {1,2,3})); const std::vector<uint32_t> veci32{1,2,3,4}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci32)), LLVMType<uint32_t[4]>::get(C, {1,2,3,4})); const std::vector<uint64_t> veci64{1,2,3,4,5}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci64)), LLVMType<uint64_t[5]>::get(C, {1,2,3,4,5})); const std::vector<float> vecf{.0f,.1f,.2f,.3f,.4f,.5f}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, vecf)), LLVMType<float[6]>::get(C, {.0f,.1f,.2f,.3f,.4f,.5f})); const std::vector<double> vecd{.0,.1,.2,.3,.4,.5,.6}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, vecd)), LLVMType<double[7]>::get(C, {.0,.1,.2,.3,.4,.5,.6})); // void CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getVoidTy(C)), LLVMType<void>::get(C)); // some special cases we alias CPPUNIT_ASSERT_EQUAL(llvm::Type::getInt8PtrTy(C), LLVMType<void*>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt8Ty(C)), LLVMType<char>::get(C)); } void TestTypes::testVDBTypes() { using openvdb::ax::codegen::LLVMType; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)), LLVMType<openvdb::math::Vec2<int32_t>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)), LLVMType<openvdb::math::Vec2<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)), LLVMType<openvdb::math::Vec2<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)), LLVMType<openvdb::math::Vec3<int32_t>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)), LLVMType<openvdb::math::Vec3<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)), LLVMType<openvdb::math::Vec3<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)), LLVMType<openvdb::math::Vec4<int32_t>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)), LLVMType<openvdb::math::Vec4<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)), LLVMType<openvdb::math::Vec4<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)), LLVMType<openvdb::math::Mat3<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)), LLVMType<openvdb::math::Mat3<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)), LLVMType<openvdb::math::Mat4<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)), LLVMType<openvdb::math::Mat4<double>>::get(C)); }
7,308
C++
44.68125
115
0.654762
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/util.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #ifndef OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED #define OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED #include <openvdb_ax/codegen/Types.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/IRBuilder.h> #include <memory> #include <string> namespace unittest_util { struct LLVMState { LLVMState(const std::string& name = "__test_module") : mCtx(new llvm::LLVMContext), mModule(new llvm::Module(name, *mCtx)) {} llvm::LLVMContext& context() { return *mCtx; } llvm::Module& module() { return *mModule; } inline llvm::BasicBlock* scratchBlock(const std::string& functionName = "TestFunction", const std::string& blockName = "TestEntry") { llvm::FunctionType* type = llvm::FunctionType::get(openvdb::ax::codegen::LLVMType<void>::get(this->context()), /**var-args*/false); llvm::Function* dummyFunction = llvm::Function::Create(type, llvm::Function::ExternalLinkage, functionName, &this->module()); return llvm::BasicBlock::Create(this->context(), blockName, dummyFunction); } private: std::unique_ptr<llvm::LLVMContext> mCtx; std::unique_ptr<llvm::Module> mModule; }; } #endif // OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED
1,393
C
28.041666
105
0.671931
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestUnaryOperatorNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "-a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::MINUS)) }, { "+a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::PLUS)) }, { "!a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::NOT)) }, { "~a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::BITNOT)) }, { "~~a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::BITNOT)) }, { "!~a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::NOT)) }, { "+-a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::MINUS), OperatorToken::PLUS)) }, { "-+a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::PLUS), OperatorToken::MINUS)) }, { "!!!a;", Node::Ptr(new UnaryOperator( new UnaryOperator( new UnaryOperator(new Local("a"), OperatorToken::NOT), OperatorToken::NOT ), OperatorToken::NOT )) }, { "~~~a;", Node::Ptr(new UnaryOperator( new UnaryOperator( new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::BITNOT ), OperatorToken::BITNOT )) }, { "-(a+b);", Node::Ptr(new UnaryOperator( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::PLUS ), OperatorToken::MINUS )) }, { "!func();", Node::Ptr(new UnaryOperator(new FunctionCall("func"), OperatorToken::NOT)) }, { "-@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::FLOAT, true), OperatorToken::MINUS)) }, { "!v@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::VEC3F), OperatorToken::NOT)) }, { "~v@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::VEC3F), OperatorToken::BITNOT)) }, { "+int(a);", Node::Ptr(new UnaryOperator(new Cast(new Local("a"), CoreType::INT32), OperatorToken::PLUS)) }, { "-(float(a));", Node::Ptr(new UnaryOperator(new Cast(new Local("a"), CoreType::FLOAT), OperatorToken::MINUS)) }, { "!a.x;", Node::Ptr(new UnaryOperator(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), OperatorToken::NOT)) }, { "-a[0];", Node::Ptr(new UnaryOperator(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), OperatorToken::MINUS)) }, { "-++a;", Node::Ptr(new UnaryOperator(new Crement(new Local("a"), Crement::Operation::Increment, false), OperatorToken::MINUS)) }, { "!{a,b,c};", Node::Ptr(new UnaryOperator( new ArrayPack({ new Local("a"), new Local("b"), new Local("c") }), OperatorToken::NOT )) }, { "!(a,b,c);", Node::Ptr(new UnaryOperator( new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), OperatorToken::NOT )) }, // This is a bit of a weird one - should perhaps look to making this a syntax error // (it will fail at compilation with an lvalue error) { "-a=a;", Node::Ptr(new UnaryOperator( new AssignExpression(new Local("a"), new Local("a")), OperatorToken::MINUS )) } }; } class TestUnaryOperatorNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestUnaryOperatorNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestUnaryOperatorNode); void TestUnaryOperatorNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::UnaryOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Unary Operator code", code) + os.str()); } } }
6,046
C++
44.126865
144
0.523652
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCastNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "bool(a);", Node::Ptr(new Cast(new Local("a"), CoreType::BOOL)) }, { "int(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) }, { "int32(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) }, { "int64(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT64)) }, { "float(a);", Node::Ptr(new Cast(new Local("a"), CoreType::FLOAT)) }, { "double(a);", Node::Ptr(new Cast(new Local("a"), CoreType::DOUBLE)) }, { "int32((a));", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) }, { "int32(1l);", Node::Ptr(new Cast(new Value<int64_t>(1), CoreType::INT32)) }, { "int32(1);", Node::Ptr(new Cast(new Value<int32_t>(1), CoreType::INT32)) }, { "int32(0);", Node::Ptr(new Cast(new Value<int32_t>(0), CoreType::INT32)) }, { "int32(@a);", Node::Ptr(new Cast(new Attribute("a", CoreType::FLOAT, true), CoreType::INT32)) }, { "double(true);", Node::Ptr(new Cast(new Value<bool>(true), CoreType::DOUBLE)) }, { "double(false);", Node::Ptr(new Cast(new Value<bool>(false), CoreType::DOUBLE)) }, { "int32(1.0f);", Node::Ptr(new Cast(new Value<float>(1.0f), CoreType::INT32)) }, { "int64(1.0);", Node::Ptr(new Cast(new Value<double>(1.0), CoreType::INT64)) }, { "float(true);", Node::Ptr(new Cast(new Value<bool>(true), CoreType::FLOAT)) }, { "int32(func());", Node::Ptr(new Cast(new FunctionCall("func"), CoreType::INT32)) }, { "bool(a+b);", Node::Ptr(new Cast(new BinaryOperator(new Local("a"), new Local("b"), OperatorToken::PLUS), CoreType::BOOL)) }, { "int32(~a);", Node::Ptr(new Cast(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), CoreType::INT32)) }, { "int64(~a);", Node::Ptr(new Cast(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), CoreType::INT64)) }, { "float(a = b);", Node::Ptr(new Cast(new AssignExpression(new Local("a"), new Local("b")), CoreType::FLOAT)) }, { "double(a.x);", Node::Ptr(new Cast(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), CoreType::DOUBLE)) }, { "int32(a++);", Node::Ptr(new Cast(new Crement(new Local("a"), Crement::Operation::Increment, true), CoreType::INT32)) }, { "int32({a,b,c});", Node::Ptr(new Cast(new ArrayPack({new Local("a"), new Local("b"), new Local("c")}), CoreType::INT32)) }, { "int32((a,b,c));", Node::Ptr(new Cast(new CommaOperator({new Local("a"), new Local("b"), new Local("c")}), CoreType::INT32)) }, { "float(double(0));", Node::Ptr(new Cast(new Cast(new Value<int32_t>(0), CoreType::DOUBLE), CoreType::FLOAT)) }, }; } class TestCastNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestCastNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCastNode); void TestCastNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::CastNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Cast code", code) + os.str()); } } }
4,581
C++
47.231578
139
0.596158
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCommaOperator.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "(1, 2, (1,2,3));", Node::Ptr( new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) })) }, { "(1.f,2.0,3l);" , Node::Ptr( new CommaOperator({ new Value<float>(1.0f), new Value<double>(2.0), new Value<int64_t>(3) })) }, { "((a,b,c), (d,e,f), (g,h,i));", Node::Ptr( new CommaOperator({ new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new CommaOperator({ new Local("d"), new Local("e"), new Local("f") }), new CommaOperator({ new Local("g"), new Local("h"), new Local("i") }) })) }, { "((a),b+1,-c);", Node::Ptr( new CommaOperator({ new Local("a"), new BinaryOperator(new Local("b"), new Value<int32_t>(1), OperatorToken::PLUS), new UnaryOperator(new Local("c"), OperatorToken::MINUS) })) }, { "(@x,++z,true);", Node::Ptr( new CommaOperator({ new Attribute("x", CoreType::FLOAT, true), new Crement(new Local("z"), Crement::Operation::Increment, false), new Value<bool>(true) })) }, { "(@x,z++,\"bar\");", Node::Ptr( new CommaOperator({ new Attribute("x", CoreType::FLOAT, true), new Crement(new Local("z"), Crement::Operation::Increment, true), new Value<std::string>("bar") })) }, { "(float(x),b=c,c.z);", Node::Ptr( new CommaOperator({ new Cast(new Local("x"), CoreType::FLOAT), new AssignExpression(new Local("b"), new Local("c")), new ArrayUnpack(new Local("c"), new Value<int32_t>(2)) })) }, { "(test(),a[0],b[1,2]);", Node::Ptr( new CommaOperator({ new FunctionCall("test"), new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), new ArrayUnpack(new Local("b"), new Value<int32_t>(1), new Value<int32_t>(2)) })) }, { "(1,2,3,4,5,6,7,8,9);", Node::Ptr( new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9) })) }, { "( 1, 2, 3, 4, \ 5, 6, 7, 8, \ 9,10,11,12, \ 13,14,15,16 );", Node::Ptr( new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9), new Value<int32_t>(10), new Value<int32_t>(11), new Value<int32_t>(12), new Value<int32_t>(13), new Value<int32_t>(14), new Value<int32_t>(15), new Value<int32_t>(16) })) }, }; } class TestCommaOperator : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestCommaOperator); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCommaOperator); void TestCommaOperator::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::CommaOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Comma Operator code", code) + os.str()); } } }
7,752
C++
47.761006
143
0.353715
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestStatementListNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "int32 a = (1,2,3), b=1, c=(b=1);", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a"), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), })), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c"), new AssignExpression( new Local("b"), new Value<int32_t>(1))), })) }, { "int32 a, b;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b")) })) }, { "int32 a, b = 1;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)) })) }, { "int32 a, b = 1, c = 1;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c"), new Value<int32_t>(1)) })) }, { "int32 a, b = 1, c;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c")) })) }, { "int32 a, b = 1, c, d = 1;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c")), new DeclareLocal(CoreType::INT32, new Local("d"), new Value<int32_t>(1)) })) } }; } class TestStatementList : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestStatementList); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestStatementList); void TestStatementList::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::StatementListNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Statement List code", code) + os.str()); } } }
4,873
C++
42.517857
117
0.470962
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCrementNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a++;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Increment, /*post*/true)) }, { "++a;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Increment, /*post*/false)) }, { "a--;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Decrement, /*post*/true)) }, { "--a;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Decrement, /*post*/false)) }, { "s@a--;", Node::Ptr(new Crement(new Attribute("a", CoreType::STRING), Crement::Operation::Decrement, /*post*/true)) }, { "f@a++;", Node::Ptr(new Crement(new Attribute("a", CoreType::FLOAT), Crement::Operation::Increment, /*post*/true)) }, { "++f@a;", Node::Ptr(new Crement(new Attribute("a", CoreType::FLOAT), Crement::Operation::Increment, /*post*/false)) }, { "++mat3f@a;", Node::Ptr(new Crement(new Attribute("a", CoreType::MAT3F), Crement::Operation::Increment, /*post*/false)) } }; } class TestCrementNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestCrementNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests) }; void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCrementNode); void TestCrementNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::CrementNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Crement code", code) + os.str()); } } }
2,855
C++
36.090909
128
0.630823
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestArrayUnpackNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a.x;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0))) }, { "a.y;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1))) }, { "a.z;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2))) }, { "a.r;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0))) }, { "a.g;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1))) }, { "a.b;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2))) }, { "x.x;", Node::Ptr(new ArrayUnpack(new Local("x"), new Value<int32_t>(0))) }, { "@x.x;", Node::Ptr(new ArrayUnpack(new Attribute("x", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@a.x;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@b.y;", Node::Ptr(new ArrayUnpack(new Attribute("b", CoreType::FLOAT, true), new Value<int32_t>(1))) }, { "@c.z;", Node::Ptr(new ArrayUnpack(new Attribute("c", CoreType::FLOAT, true), new Value<int32_t>(2))) }, { "@a.r;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@a.g;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1))) }, { "@a.b;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2))) }, { "@a[0l];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int64_t>(0))) }, { "@a[0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@a[1];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1))) }, { "@a[2];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2))) }, { "@a[0.0f];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<float>(0.0f))) }, { "@a[0.0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<double>(0.0))) }, { "@a[\"str\"];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<std::string>("str"))) }, { "@a[true];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true))) }, { "@a[false];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(false))) }, { "@a[a];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"))) }, { "@a[0,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0), new Value<int32_t>(0))) }, { "@a[1,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1), new Value<int32_t>(0))) }, { "@a[2,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2), new Value<int32_t>(0))) }, { "a[0,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0))) }, { "a[1,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1), new Value<int32_t>(0))) }, { "a[2,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2), new Value<int32_t>(0))) }, { "@a[a,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"), new Value<int32_t>(0))) }, { "@a[b,1];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("b"), new Value<int32_t>(1))) }, { "@a[c,2];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("c"), new Value<int32_t>(2))) }, { "@a[a,d];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"), new Local("d"))) }, { "@a[b,e];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("b"), new Local("e"))) }, { "@a[c,f];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("c"), new Local("f"))) }, // { "a[(a),1+1];", Node::Ptr(new ArrayUnpack(new Local("a"), new Local("a"), new BinaryOperator(new Value<int32_t>(1), new Value<int32_t>(1), OperatorToken::PLUS))) }, { "a[!0,a=b];", Node::Ptr(new ArrayUnpack(new Local("a"), new UnaryOperator(new Value<int32_t>(0), OperatorToken::NOT), new AssignExpression(new Local("a"), new Local("b")))) }, { "a[test(),$A];", Node::Ptr(new ArrayUnpack(new Local("a"), new FunctionCall("test"), new ExternalVariable("A", CoreType::FLOAT))) }, { "a[a++,++a];", Node::Ptr(new ArrayUnpack(new Local("a"), new Crement(new Local("a"), Crement::Operation::Increment, true), new Crement(new Local("a"), Crement::Operation::Increment, false))) }, { "a[a[0,0],0];", Node::Ptr(new ArrayUnpack(new Local("a"), new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0)), new Value<int32_t>(0))) }, { "a[(1,2,3)];", Node::Ptr(new ArrayUnpack(new Local("a"), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) )) }, { "a[(1,2,3),(4,5,6)];", Node::Ptr(new ArrayUnpack(new Local("a"), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), }), new CommaOperator({ new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), }) )) }, { "a[a[0,0],a[0]];", Node::Ptr(new ArrayUnpack(new Local("a"), new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0)), new ArrayUnpack(new Local("a"), new Value<int32_t>(0)))) } // @todo should this be a syntax error // { "@a[{1,2,3},{1,2,3,4}];", } }; } class TestArrayUnpackNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestArrayUnpackNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayUnpackNode); void TestArrayUnpackNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::ArrayUnpackNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Array Unpack code", code) + os.str()); } } }
8,853
C++
56.869281
144
0.521857
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestAssignExpressionNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { unittest_util::CodeTests tests = { // test an attribute type passes for all expression types { "@a = (true);", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true))) }, { "@a = (1,2,3);", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), }) )) }, { "@a = test();", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new FunctionCall("test"))) }, { "@a = 1 + i@b;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new BinaryOperator(new Value<int32_t>(1), new Attribute("b", CoreType::INT32), OperatorToken::PLUS) )) }, { "@a = -int@b;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new UnaryOperator(new Attribute("b", CoreType::INT32), OperatorToken::MINUS) )) }, { "@a = ++float@b;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Crement(new Attribute("b", CoreType::FLOAT), Crement::Operation::Increment, false) )) }, { "@a = bool(2);", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Cast(new Value<int32_t>(2), CoreType::BOOL) )) }, { "@a = {1, 2, 3};", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) )) }, { "@a = [email protected];", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)) )) }, { "@a = \"b\";", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Value<std::string>("b"))) }, { "@a = b;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Local("b"))) }, // test all attribute { "bool@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::BOOL), new Value<bool>(true))) }, { "int16@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT16), new Value<bool>(true))) }, { "i@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) }, { "int@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) }, { "int32@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) }, { "int64@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT64), new Value<bool>(true))) }, { "f@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT), new Value<bool>(true))) }, { "float@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT), new Value<bool>(true))) }, { "double@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::DOUBLE), new Value<bool>(true))) }, { "vec3i@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3I), new Value<bool>(true))) }, { "v@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3F), new Value<bool>(true))) }, { "vec3f@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3F), new Value<bool>(true))) }, { "vec3d@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3D), new Value<bool>(true))) }, { "s@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::STRING), new Value<bool>(true))) }, { "string@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::STRING), new Value<bool>(true))) }, // compound assignments (operation is stored implicitly) { "@a += true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::PLUS )) }, { "@a -= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::MINUS )) }, { "@a *= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::MULTIPLY )) }, { "@a /= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::DIVIDE )) }, { "@a &= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::BITAND )) }, { "@a |= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::BITOR )) }, { "@a ^= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::BITXOR )) }, { "@a %= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::MODULO )) }, { "@a <<= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::SHIFTLEFT )) }, { "@a >>= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::SHIFTRIGHT )) }, // test component assignment { "[email protected] = true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(0) ), new Value<bool>(true) )) }, { "vec3i@a[1] = true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(1) ), new Value<bool>(true) )) }, { "[email protected] = true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(2) ), new Value<bool>(true) )) }, { "[email protected] += true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(0) ), new Value<bool>(true), OperatorToken::PLUS )) }, // test other lhs { "a = true;", Node::Ptr(new AssignExpression(new Local("a"), new Value<bool>(true))) }, { "++a = true;", Node::Ptr(new AssignExpression( new Crement(new Local("a"), Crement::Operation::Increment, false), new Value<bool>(true) )) }, { "++@a = true;", Node::Ptr(new AssignExpression( new Crement(new Attribute("a", CoreType::FLOAT, true), Crement::Operation::Increment, false), new Value<bool>(true) )) }, // chains { "@a = @b += 1;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new Attribute("b", CoreType::FLOAT, true), new Value<int32_t>(1), OperatorToken::PLUS) )) }, { "@a = [email protected] = 1;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)), new Value<int32_t>(1) ) )) }, { "@a += [email protected] = x %= 1;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)), new AssignExpression( new Local("x"), new Value<int32_t>(1), OperatorToken::MODULO ) ), OperatorToken::PLUS )) } }; } class TestAssignExpressionNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestAssignExpressionNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAssignExpressionNode); void TestAssignExpressionNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::AssignExpressionNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Assign Expression code", code) + os.str()); } } }
13,318
C++
47.966912
134
0.443685
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestFunctionCallNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "func();", Node::Ptr(new FunctionCall("func")) }, { "_();", Node::Ptr(new FunctionCall("_")) }, { "_1();", Node::Ptr(new FunctionCall("_1")) }, { "a_();", Node::Ptr(new FunctionCall("a_")) }, { "_a();", Node::Ptr(new FunctionCall("_a")) }, { "A();", Node::Ptr(new FunctionCall("A")) }, { "D1f();", Node::Ptr(new FunctionCall("D1f")) }, { "f(a);", Node::Ptr(new FunctionCall("f", new Local("a"))) }, { "a(a,1);", Node::Ptr(new FunctionCall("a", { new Local("a"), new Value<int32_t>(1) })) }, { "func(1);", Node::Ptr(new FunctionCall("func", new Value<int32_t>(1) )) }, { "func(\"string\");", Node::Ptr(new FunctionCall("func", new Value<std::string>("string") )) }, { "func(true);", Node::Ptr(new FunctionCall("func", new Value<bool>(true) )) }, { "func({a,b,c});", Node::Ptr(new FunctionCall("func", new ArrayPack({ new Local("a"), new Local("b"), new Local("c") }) )) }, { "func((a,b,c));", Node::Ptr(new FunctionCall("func", new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }) )) }, { "func(@a);", Node::Ptr(new FunctionCall("func", new Attribute("a", CoreType::FLOAT, true) )) }, { "func(++a);", Node::Ptr(new FunctionCall("func", new Crement(new Local("a"), Crement::Operation::Increment, false) )) }, { "func(~a);", Node::Ptr(new FunctionCall("func", new UnaryOperator(new Local("a"), OperatorToken::BITNOT) )) }, { "func((a));", Node::Ptr(new FunctionCall("func", new Local("a") )) }, { "func1(func2());", Node::Ptr(new FunctionCall("func1", new FunctionCall("func2") )) }, { "func(a=b);", Node::Ptr(new FunctionCall("func", new AssignExpression(new Local("a"), new Local("b")) )) }, { "func(a==b);", Node::Ptr(new FunctionCall("func", new BinaryOperator(new Local("a"), new Local("b"), OperatorToken::EQUALSEQUALS) )) }, { "func(a.x);", Node::Ptr(new FunctionCall("func", new ArrayUnpack(new Local("a"), new Value<int32_t>(0)) )) }, { "func(bool(a));", Node::Ptr(new FunctionCall("func", new Cast(new Local("a"), CoreType::BOOL) )) }, { "func(a,b,c,d,e,f);", Node::Ptr(new FunctionCall("func", { new Local("a"), new Local("b"), new Local("c"), new Local("d"), new Local("e"), new Local("f") } )) }, { "func((a, b), c);", Node::Ptr(new FunctionCall("func", { new CommaOperator({ new Local("a"), new Local("b") }), new Local("c") })) } }; } class TestFunctionCallNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestFunctionCallNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionCallNode); void TestFunctionCallNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::FunctionCallNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Function Call code", code) + os.str()); } } }
6,011
C++
37.292993
111
0.433539
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestSyntaxFailures.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "test/util.h" #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/Exceptions.h> #include <string> #include <vector> #include <unordered_map> #include <functional> #include <cppunit/extensions/HelperMacros.h> namespace { // mimics std::pair<std::string, null> struct StrWrapper { StrWrapper(const char* str) : first(str) {} const std::string first; }; static const std::vector<StrWrapper> tests { // invalid r-value syntax "@a = @;", "@a = =;", "@a = +;", "@a = -;", "@a = *;", "@a = /;", "@a = %;", "@a = |;", "@a = &;", "@a = ^;", "@a = ~;", "@a = ==;", "@a = !=;", "@a = >;", "@a = <;", "@a = >=;", "@a = <=;", "@a = +=;", "@a = -=;", "@a = *=;", "@a = /=;", "@a = ++;", "@a = --;", "@a = &&;", "@a = ||;", "@a = !;", "@a = ,;", "@a = (;", "@a = );", "@a = {;", "@a =};", "@a = .x;", "@a = .y;", "@a = .z;", "@a = .r;", "@a = .g;", "@a = .b;", "@a = f@;", "@a = i@;", "@a = v@;", "@a = s@;", "@a = if;", "@a = else;", "@a = return;", "@a = ;", "@a = {};", "@a = \"a;", "[email protected] = 0;", "$a = $;", "$a = =;", "$a = +;", "$a = -;", "$a = *;", "$a = /;", "$a = %;", "$a = |;", "$a = &;", "$a = ^;", "$a = ~;", "$a = ==;", "$a = !=;", "$a = >;", "$a = <;", "$a = >=;", "$a = <=;", "$a = +=;", "$a = -=;", "$a = *=;", "$a = /=;", "$a = ++;", "$a = --;", "$a = &&;", "$a = ||;", "$a = !;", "$a = ,;", "$a = (;", "$a = );", "$a = {;", "$a =};", "$a = .x;", "$a = .y;", "$a = .z;", "$a = .r;", "$a = .g;", "$a = .b;", "$a = f$;", "$a = i$;", "$a = v$;", "$a = s$;", "$a = if;", "$a = else;", "$a = return;", "$a = ;", "$a = {};", "$a = {1};", "$a = \"a;", "v$a[0] = 0;", "v$a.a = 0;", // @todo these should probably be valid syntax and the code // generators should handle assignments based on the current // r/lvalues "5 = 5;", "$a = 5;", // invalid l-value // TODO: these should fail syntax tests // {"+@a = 0;", }, // {"-@a = 0;", }, // {"~@a = 0;", }, // {"!@a = 0;", }, // "++@a = 0;", // "--@a = 0;", "=@a;", "*@a;", "/@a;", "%@a;", "|@a;", "&@a;", "^@a;", "==@a;", "!=@a;", ">@a;", "<@a;", ">=@a;", "<=@a;", "+=@a;", "-=@a;", "*=@a;", "/=@a;", "&&@a;", "||@a;", ",@a;", "(@a;", ")@a;", "{@a;", "}@a;", ".x@a;", ".y@a;", ".z@a;", ".r@a;", ".g@a;", ".b@a;", "@@a;", "f@@a;", "i@@a;", "v@@a;", "s@@a;", "if@a;", "else@a;", "return@a;", "{1}@a;", "\"a\"@a;", "b@a;", "sht@a;", "it@a;", "l@a;", "flt@a;", "dbl@a;", "vecint@a;", "vint@a;", "vfloat@a;", "vecflt@a;", "vflt@a;", "vdouble@a;", "vecdbl@a;", "vdbl@a;", "str@a;", "++$a = 0;", "--$a = 0;", "=$a;", "*$a;", "/$a;", "%$a;", "|$a;", "&$a;", "^$a;", "==$a;", "!=$a;", ">$a;", "<$a;", ">=$a;", "<=$a;", "+=$a;", "-=$a;", "*=$a;", "/=$a;", "&&$a;", "||$a;", ",$a;", "($a;", ")$a;", "{$a;", "}$a;", ".x$a;", ".y$a;", ".z$a;", ".r$a;", ".g$a;", ".b$a;", "$$a;", "f$$a;", "i$$a;", "v$$a;", "s$$a;", "if$a;", "else$a;", "return$a;", "{1}$a;", "\"a\"$a;", "b$a;", "sht$a;", "it$a;", "l$a;", "flt$a;", "dbl$a;", "vecint$a;", "vint$a;", "vfloat$a;", "vecflt$a;", "vflt$a;", "vdouble$a;", "vecdbl$a;", "vdbl$a;", "str$a;", "a ! a;", "a ~ a;", "a \\ a;", "a ? a;", "bool + a;", "bool a + a;", "return + a;", "if + a;", "a + if(true) {};", "{} + {};", "~ + !;", "+ + -;", "; + ;", "int();", "int(return);", "int(if(true) {});", "int(;);", "int(bool a;);", "int(bool a);", "int{a};", "int[a];", "string(a);", "vector(a);", "vec3i(a);", "vec3f(a);", "vec3d(a);", // invalid if block "if (a) {b}", "if (a) else ();", "if (); else (a);", "if (a) if(b) {if (c)} else {}", "if (if(a));", "if ();", "if (); else ;", "if (); else ();", "if (); else () {}", "if (); elf {}", "if (a) {} elif (b) {}", "else {}", "else ;", "if a;", "if a {} elif b {}", "if (a); else ; else ;", "else (a); ", "if (a) {}; else {};", "if (a) {b = 1} else {};", "if (a) {} ; else {}", "if () {}; else (a);", // invalid ternary "?;", ":;", "? :;", "? : false;", "true ? :;", "true ? false;", "true ? false :;", "true : 1 ? 2;", "true ? 1 ? 2;", "true : 1 : 2;", "true ?? 1 : 2;", "true (? 1 :) 2;", "true (?:) 2;", "true (? false ? 1 : 2): 3;", "true ? (false ? 1 : 2:) 3;", "(true ? false ? 1 : 2): 3;", // invalid crement "++5;", "5++;", "--5;", "5--;", "++5--;", "++5++;", "--5++;", "--5--;", "{ 1, 1, 1}++;", "++{ 1, 1, 1};", "--{ 1, 1, 1};", "{ 1, 1, 1}--;", "++{ 1, 1, 1}++;", "++{ 1, 1, 1}--;", "--{ 1, 1, 1}--;", "++a-;", //"++a--;", //"++a++;", //"--a++;", //"--a--;", //"----a;", //"++++a;", //"a.x--;", //"-a.y--;", //"++a.z;", //"++@a--;", //"@a.x--;", //"[email protected];", //"[email protected];", "++$a--;", "$a.x--;", "-$a.y--;", "++$a.z;", "--f();", "f()++;", "return++;", "--return;", "true++;", "--false;", "--if;", "if++;", "else++;", "--else;", "--bool;", "short++;", "--int;", "long++;", "--float;", "++double;", "--vector;", "matrix--;", "--();", "()++;", "{}++;", "--{};", "--,;", ",--;", // invalid declare "int;", "int 1;", "string int;", "int bool a;", "int a", "vector a", "vector float a", // invalid function "function(;", "function);", "return();", "function(bool);", "function(bool a);", "function(+);", "function(!);", "function(~);", "function(-);", "function(&&);", "function{};" , "function(,);" , "function(, a);", "function(a, );", "function({,});", "function({});", "function({)};", "function{()};", "function{(});", "function{,};", "function(if(true) {});", "function(return);", "function(return;);", "function(while(true) a);", "function(while(true) {});", "\"function\"();" , "();", "+();", "10();", // invalid keyword return "return", "int return;", "return return;", "return max(1, 2);", "return 1 + a;", "return !a;", "return a = 1;", "return a.x = 1;", "return ++a;", "return int(a);", "return {1, 2, 3};", "return a[1];", "return true;", "return 0;", "return (1);", "return \"a\";", "return int a;", "return a;", "return @a;", // invalid unary "+bool;" , "+bool a;" , "bool -a;" , "-return;" , "!return;" , "+return;" , "~return;" , "~if(a) {};" , "if(a) -{};" , "if(a) {} !else {};", // @todo unary crementation expressions should be parsable but perhaps // not compilable "---a;" , "+++a;" , // invalid value ".0.0;", ".0.0f;", ".f;", "0..0;", "0.0l;", "0.0ls;", "0.0s;", "0.0sf;", "0.a", "0.af", "00ls;", "0ef;", "0f0;", "1.0f.0;", "1.\"1\";", "1.e6f;", "10000000.00000001s;", "1e.6f;", "1Ee6;", "1ee6;", "1eE6f;", "1ee6f;", "1l.0;", "1s.0;", "\"1.\"2;", "a.0", "a.0f", "false.0;", "true.;", // invalid vector "{1,2,3];", "[1,2,3};", "{,,};", "{,2,3};", "{()};", "{(1,)};", "{(,1)};", "{(1});", "({1)};", "{1,};", "{,1};", // invalid vector unpack "5.x;", "foo.2;", "a.w;", "a.X;", "a.Y;", "a.Z;", "@a.X;", "@a.Y;", "@a.Z;", "$a.X;", "$a.Y;", "$a.Z;", "a.xx;", "a++.x", "++a.x", "func().x", "int(y).x", "vector .", "vector .x", "vector foo.x", "(a + b).x", "(a).x;", "(@a).x;", "@.x;", "($a).x;", "$.x;", "true.x;", "a.rx;", "a.rgb;", // other failures (which may be used in the future) "function<>();", "function<true>();", "a[1:1];", "a.a;", "a->a;", "&a;", "a . a;", "a .* a;", "@a();", "$a();", "@a.function();", "@a.member;", "/**/;", "(a,a,a) = (b,b,b);", "(a,a,a) = 1;", "(a) = 1;", "a = (a=a) = a;", // invalid lone characters "£;", "`;", "¬;", "@;", "~;", "+;", "-;", "*;", "/;", "<<;", ">>;", ">;", "<;", "[];", "|;", ",;", "!;", "\\;" }; } class TestSyntaxFailures : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestSyntaxFailures); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST_SUITE_END(); void testSyntax(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestSyntaxFailures); void TestSyntaxFailures::testSyntax() { // Quickly check the above doesn't have multiple occurance // store multiple in a hash map const auto hash = [](const StrWrapper* s) { return std::hash<std::string>()(s->first); }; const auto equal = [](const StrWrapper* s1, const StrWrapper* s2) { return s1->first.compare(s2->first) == 0; }; std::unordered_map<const StrWrapper*, size_t, decltype(hash), decltype(equal)> map(tests.size(), hash, equal); for (const auto& test : tests) { ++map[&test]; } // Print strings that occur more than once for (auto iter : map) { if (iter.second > 1) { std::cout << iter.first->first << " printed x" << iter.second << std::endl; } } TEST_SYNTAX_FAILS(tests); }
10,391
C++
15.87013
87
0.307381
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestTernaryOperatorNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "true ? 1 : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "true ? a : 1.5f;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Local("a"), new Value<float>(1.5f)))}, { "false ? true : false;", Node::Ptr(new TernaryOperator(new Value<bool>(false), new Value<bool>(true), new Value<bool>(false)))}, { "a == b ? 1 : 0;", Node::Ptr(new TernaryOperator( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::EQUALSEQUALS), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "a++ ? 1 : 0;", Node::Ptr(new TernaryOperator( new Crement(new Local("a"), Crement::Operation::Increment, true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "@a ? 1 : 0;", Node::Ptr(new TernaryOperator(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "func() ? 1 : 0;", Node::Ptr(new TernaryOperator(new FunctionCall("func"), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "(true) ? 1 : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "true ? 3 : 2 ? 1 : 0;", Node::Ptr(new TernaryOperator( new Value<bool>(true), new Value<int32_t>(3), new TernaryOperator(new Value<int32_t>(2), new Value<int32_t>(1), new Value<int32_t>(0))))}, { "(true ? 3 : 2) ? 1 : 0;", Node::Ptr(new TernaryOperator( new TernaryOperator(new Value<bool>(true), new Value<int32_t>(3), new Value<int32_t>(2)), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "true ? \"foo\" : \"bar\";", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<std::string>("foo"), new Value<std::string>("bar")))}, { "true ? voidfunc1() : voidfunc2();", Node::Ptr(new TernaryOperator(new Value<bool>(true), new FunctionCall("voidfunc1"), new FunctionCall("voidfunc2")))}, { "true ? {1,1,1} : {0,0,0};", Node::Ptr(new TernaryOperator( new Value<bool>(true), new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(1), new Value<int32_t>(1) }) , new ArrayPack({ new Value<int32_t>(0), new Value<int32_t>(0), new Value<int32_t>(0) }) ))}, { "true ? false ? 3 : 2 : 1;" , Node::Ptr(new TernaryOperator( new Value<bool>(true), new TernaryOperator( new Value<bool>(false), new Value<int32_t>(3), new Value<int32_t>(2)), new Value<int32_t>(1)))}, { "true ? false ? 3 : 2 : (true ? 4 : 5);" , Node::Ptr(new TernaryOperator( new Value<bool>(true), new TernaryOperator( new Value<bool>(false), new Value<int32_t>(3), new Value<int32_t>(2)), new TernaryOperator( new Value<bool>(true), new Value<int32_t>(4), new Value<int32_t>(5))))}, { "true ? : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), nullptr, new Value<int32_t>(0)))}, }; } class TestTernaryOperatorNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestTernaryOperatorNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestTernaryOperatorNode); void TestTernaryOperatorNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::TernaryOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Ternary Operator code", code) + os.str()); } } }
7,769
C++
59.703125
177
0.387051
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestLoopNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "for (int32 i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for(int32 i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0;i < 10;++i) ;", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Local("i"), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (@i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Attribute("i", CoreType::FLOAT, true), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (!i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new UnaryOperator(new Local("i"), OperatorToken::NOT), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new AssignExpression(new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (i+j; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new BinaryOperator(new Local("i"), new Local("j"), OperatorToken::PLUS), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (func(i); i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new FunctionCall("func", new Local("i")), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (1; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Value<int32_t>(1), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (float$ext; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ExternalVariable("ext", CoreType::FLOAT), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (i++; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Crement(new Local("i"), Crement::Operation::Increment, true), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for ({1,2.0,3.0f}; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ArrayPack({new Value<int32_t>(1), new Value<double>(2.0), new Value<float>(3.0f)}), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (1,2.0,3.0f; (i < 10, i > 10); (++i, --i)) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::MORETHAN) }), new Block(), new CommaOperator({ new Value<int32_t>(1), new Value<double>(2.0), new Value<float>(3.0f) }), new CommaOperator({ new Crement(new Local("i"), Crement::Operation::Increment, false), new Crement(new Local("i"), Crement::Operation::Decrement, false), }) )) }, { "for (++i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Crement(new Local("i"), Crement::Operation::Increment, false), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (x[2]; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ArrayUnpack(new Local("x"), new Value<int32_t>(2)), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for ((x[2]); i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ArrayUnpack(new Local("x"), new Value<int32_t>(2)), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), nullptr, new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; i < 10; ++i, ++j) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new CommaOperator({ new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false), new Crement(new Local("j"), Crement::Operation::Increment, /*post*/false) }))) }, { "for (i = 0; i < 10; ++i, ++j) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new AssignExpression(new Local("i"), new Value<int32_t>(0)), new CommaOperator({ new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false), new Crement(new Local("j"), Crement::Operation::Increment, /*post*/false) }))) }, { "for (int32 i = 0; i; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Local("i"), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; func(i); ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new FunctionCall("func", new Local("i")), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; int32 j = func(i); ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new DeclareLocal(CoreType::INT32, new Local("j"),new FunctionCall("func", new Local("i"))), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (; i < 10;) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block())) }, { "for (;;) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Value<bool>(true), new Block())) }, { "for (;;) { 1,2,3 };", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Value<bool>(true), new Block(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "for (;;) { 1,2,3; }", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Value<bool>(true), new Block(new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "for (int32 i = 0, j = 0, k; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new StatementList({new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new DeclareLocal(CoreType::INT32, new Local("j"), new Value<int32_t>(0)), new DeclareLocal( CoreType::INT32, new Local("k"))}), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (i = 0, j = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new CommaOperator({ new AssignExpression(new Local("i"), new Value<int32_t>(0)), new AssignExpression(new Local("j"), new Value<int32_t>(0)) }), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; i < 10, j < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new BinaryOperator(new Local("j"), new Value<int32_t>(10), OperatorToken::LESSTHAN) }), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "while (int32 i = 0) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Block())) }, { "while (i = 0) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new AssignExpression(new Local("i"), new Value<int32_t>(0)), new Block())) }, { "while ((a,b,c)) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new Block())) }, { "while (i < 0, j = 10) ;", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(0), OperatorToken::LESSTHAN), new AssignExpression(new Local("j"), new Value<int32_t>(10)) }), new Block())) }, { "while (i) { 1,2,3 };", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new Local("i"), new Block(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "while (i) { 1,2,3; }", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new Local("i"), new Block(new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "do {} while (i < 0, j = 10)", Node::Ptr(new Loop(tokens::LoopToken::DO, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(0), OperatorToken::LESSTHAN), new AssignExpression(new Local("j"), new Value<int32_t>(10)) }), new Block())) }, { "do ; while (int32 i = 0)", Node::Ptr(new Loop(tokens::LoopToken::DO, new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Block())) }, { "do ; while ((a,b,c))", Node::Ptr(new Loop(tokens::LoopToken::DO, new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new Block())) }, { "do ; while (a,b,c)", Node::Ptr(new Loop(tokens::LoopToken::DO, new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new Block())) }, { "do { 1,2,3 }; while (i) ", Node::Ptr(new Loop(tokens::LoopToken::DO, new Local("i"), new Block(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "do { 1,2,3; } while (i) ", Node::Ptr(new Loop(tokens::LoopToken::DO, new Local("i"), new Block(new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) } }; } class TestLoopNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestLoopNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLoopNode); void TestLoopNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::LoopNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Loop code", code) + os.str()); } } }
21,950
C++
61.008474
144
0.405011
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestAttributeNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "bool@_a;", Node::Ptr(new Attribute("_a", CoreType::BOOL)) }, { "int16@a_;", Node::Ptr(new Attribute("a_", CoreType::INT16)) }, { "i@a1;", Node::Ptr(new Attribute("a1", CoreType::INT32)) }, { "int@abc;", Node::Ptr(new Attribute("abc", CoreType::INT32)) }, { "int32@abc;", Node::Ptr(new Attribute("abc", CoreType::INT32)) }, { "int64@a;", Node::Ptr(new Attribute("a", CoreType::INT64)) }, { "@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT, true)) }, { "f@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT)) }, { "float@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT)) }, { "double@a;", Node::Ptr(new Attribute("a", CoreType::DOUBLE)) }, { "vec2i@a;", Node::Ptr(new Attribute("a", CoreType::VEC2I)) }, { "vec2f@a;", Node::Ptr(new Attribute("a", CoreType::VEC2F)) }, { "vec2d@a;", Node::Ptr(new Attribute("a", CoreType::VEC2D)) }, { "vec3i@a;", Node::Ptr(new Attribute("a", CoreType::VEC3I)) }, { "v@a;", Node::Ptr(new Attribute("a", CoreType::VEC3F)) }, { "vec3f@a;", Node::Ptr(new Attribute("a", CoreType::VEC3F)) }, { "vec3d@a;", Node::Ptr(new Attribute("a", CoreType::VEC3D)) }, { "vec4i@a;", Node::Ptr(new Attribute("a", CoreType::VEC4I)) }, { "vec4f@a;", Node::Ptr(new Attribute("a", CoreType::VEC4F)) }, { "vec4d@a;", Node::Ptr(new Attribute("a", CoreType::VEC4D)) }, { "mat3f@a;", Node::Ptr(new Attribute("a", CoreType::MAT3F)) }, { "mat3d@a;", Node::Ptr(new Attribute("a", CoreType::MAT3D)) }, { "mat4f@a;", Node::Ptr(new Attribute("a", CoreType::MAT4F)) }, { "mat4d@a;", Node::Ptr(new Attribute("a", CoreType::MAT4D)) }, { "string@a;", Node::Ptr(new Attribute("a", CoreType::STRING)) }, { "s@a;", Node::Ptr(new Attribute("a", CoreType::STRING)) }, }; } class TestAttributeNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestAttributeNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAttributeNode); void TestAttributeNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::AttributeNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Attribute code", code) + os.str()); } } }
3,758
C++
38.568421
93
0.601384
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestValueNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> #include <cstdlib> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { using CodeTestMap = std::map<Node::NodeType, unittest_util::CodeTests>; auto converti(const char* c) -> uint64_t { return std::strtoull(c, /*end*/nullptr, /*base*/10); } auto convertf(const char* c) -> float { return std::strtof(c, /*end*/nullptr); } auto convertd(const char* c) -> double { return std::strtod(c, /*end*/nullptr); } template <typename T> std::string fullDecimalValue(const T t) { // 767 is max number of digits necessary to accurately represent base 2 doubles std::ostringstream os; os << std::setprecision(767) << t; return os.str(); } static const CodeTestMap value_tests = { // No limits::lowest, negative values are a unary operator { Node::NodeType::ValueBoolNode, { { "false;", Node::Ptr(new Value<bool>(false)) }, { "true;", Node::Ptr(new Value<bool>(true)) }, } }, { Node::NodeType::ValueInt32Node, { { "00;", Node::Ptr(new Value<int32_t>(converti("0"))) }, { "1000000000000000;", Node::Ptr(new Value<int32_t>(converti("1000000000000000"))) }, // signed int wrap { "0;", Node::Ptr(new Value<int32_t>(converti("0"))) }, { "1234567890;", Node::Ptr(new Value<int32_t>(converti("1234567890"))) }, { "1;", Node::Ptr(new Value<int32_t>(converti("1"))) }, // signed int wrap { std::to_string(std::numeric_limits<int64_t>::max()) + ";", Node::Ptr(new Value<int32_t>(std::numeric_limits<int64_t>::max())) }, // signed int wrap { std::to_string(std::numeric_limits<uint64_t>::max()) + ";", Node::Ptr(new Value<int32_t>(std::numeric_limits<uint64_t>::max())) }, // signed int wrap { std::to_string(std::numeric_limits<int32_t>::max()) + "0;", Node::Ptr(new Value<int32_t>(uint64_t(std::numeric_limits<int32_t>::max()) * 10ul)) } } }, { Node::NodeType::ValueInt64Node, { { "01l;", Node::Ptr(new Value<int64_t>(converti("1"))) }, { "0l;", Node::Ptr(new Value<int64_t>(converti("0"))) }, { "1234567890l;", Node::Ptr(new Value<int64_t>(converti("1234567890l"))) }, // signed int wrap { std::to_string(uint64_t(std::numeric_limits<int64_t>::max()) + 1) + "l;", Node::Ptr(new Value<int64_t>(uint64_t(std::numeric_limits<int64_t>::max()) + 1ul)) } } }, { Node::NodeType::ValueFloatNode, { { ".123456789f;", Node::Ptr(new Value<float>(convertf(".123456789f"))) }, { "0.0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "00.f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "0e+0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "0e-0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "0e0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "1234567890.0987654321f;", Node::Ptr(new Value<float>(convertf("1234567890.0987654321f"))) }, { "1e+6f;", Node::Ptr(new Value<float>(convertf("1e+6f"))) }, { "1E+6f;", Node::Ptr(new Value<float>(convertf("1E+6f"))) }, { "1e-6f;", Node::Ptr(new Value<float>(convertf("1e-6f"))) }, { "1E-6f;", Node::Ptr(new Value<float>(convertf("1E-6f"))) }, { "1e6f;", Node::Ptr(new Value<float>(convertf("1e6f"))) }, { "1E6f;", Node::Ptr(new Value<float>(convertf("1E6f"))) } } }, { Node::NodeType::ValueDoubleNode, { { ".123456789;", Node::Ptr(new Value<double>(convertd(".123456789"))) }, { "0.0;", Node::Ptr(new Value<double>(convertd("0.0"))) }, { "0e0;", Node::Ptr(new Value<double>(convertd("0.0f"))) }, { "1.0;", Node::Ptr(new Value<double>(convertd("1.0"))) }, { "1234567890.00000000;", Node::Ptr(new Value<double>(convertd("1234567890.0"))) }, { "1234567890.0987654321;", Node::Ptr(new Value<double>(convertd("1234567890.0987654321"))) }, { "1234567890.10000000;", Node::Ptr(new Value<double>(convertd("1234567890.1"))) }, { "1234567890e-0;", Node::Ptr(new Value<double>(convertd("1234567890e-0"))) }, { "1e+6;", Node::Ptr(new Value<double>(convertd("1e+6"))) }, { "1e-6;", Node::Ptr(new Value<double>(convertd("1e-6"))) }, { "1e01;", Node::Ptr(new Value<double>(convertd("1e01"))) }, { "1e6;", Node::Ptr(new Value<double>(convertd("1e6"))) }, { "1E6;", Node::Ptr(new Value<double>(convertd("1E6"))) }, { std::to_string(std::numeric_limits<double>::max()) + ";", Node::Ptr(new Value<double>(std::numeric_limits<double>::max())) }, { fullDecimalValue(std::numeric_limits<double>::max()) + ".0;", Node::Ptr(new Value<double>(std::numeric_limits<double>::max())) }, { fullDecimalValue(std::numeric_limits<double>::min()) + ";", Node::Ptr(new Value<double>(std::numeric_limits<double>::min())) } } }, { Node::NodeType::ValueStrNode, { { "\"0.0\";", Node::Ptr(new Value<std::string>("0.0")) }, { "\"0.0f\";", Node::Ptr(new Value<std::string>("0.0f")) }, { "\"0\";", Node::Ptr(new Value<std::string>("0")) }, { "\"1234567890.0987654321\";", Node::Ptr(new Value<std::string>("1234567890.0987654321")) }, { "\"1234567890\";", Node::Ptr(new Value<std::string>("1234567890")) }, { "\"a1b2c3d4.e5f6g7.0\";", Node::Ptr(new Value<std::string>("a1b2c3d4.e5f6g7.0")) }, { "\"literal\";", Node::Ptr(new Value<std::string>("literal")) }, { "\"\";", Node::Ptr(new Value<std::string>("")) }, { "\"" + std::to_string(std::numeric_limits<double>::lowest()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<double>::lowest()))) }, { "\"" + std::to_string(std::numeric_limits<double>::max()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<double>::max()))) }, { "\"" + std::to_string(std::numeric_limits<int64_t>::lowest()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<int64_t>::lowest()))) }, { "\"" + std::to_string(std::numeric_limits<int64_t>::max()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<int64_t>::max()))) } } } }; } class TestValueNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestValueNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { for (const auto& tests : value_tests) { TEST_SYNTAX_PASSES(tests.second); } } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestValueNode); void TestValueNode::testASTNode() { for (const auto& tests : value_tests) { const Node::NodeType nodeType = tests.first; for (const auto& test : tests.second) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), nodeType == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Value (literal) code", code) + os.str()); } } } }
9,562
C++
44.538095
117
0.497804
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestLocalNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a_;", Node::Ptr(new Local("a_")) }, { "_a;", Node::Ptr(new Local("_a")) }, { "_;", Node::Ptr(new Local("_")) }, { "aa;", Node::Ptr(new Local("aa")) }, { "A;", Node::Ptr(new Local("A")) }, { "_A;", Node::Ptr(new Local("_A")) }, { "a1;", Node::Ptr(new Local("a1")) }, { "_1;", Node::Ptr(new Local("_1")) }, { "abc;", Node::Ptr(new Local("abc")) }, { "D1f;", Node::Ptr(new Local("D1f")) }, { "var;", Node::Ptr(new Local("var")) } }; } class TestLocalNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestLocalNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLocalNode); void TestLocalNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::LocalNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Local code", code) + os.str()); } } }
2,395
C++
28.580247
92
0.59666
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestExternalVariableNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) }, { "bool$_a;", Node::Ptr(new ExternalVariable("_a", CoreType::BOOL)) }, { "i$a1;", Node::Ptr(new ExternalVariable("a1", CoreType::INT32)) }, { "int$abc;", Node::Ptr(new ExternalVariable("abc", CoreType::INT32)) }, { "int32$abc;", Node::Ptr(new ExternalVariable("abc", CoreType::INT32)) }, { "int64$a;", Node::Ptr(new ExternalVariable("a", CoreType::INT64)) }, { "f$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) }, { "float$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) }, { "double$a;", Node::Ptr(new ExternalVariable("a", CoreType::DOUBLE)) }, { "vec3i$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3I)) }, { "v$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3F)) }, { "vec3f$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3F)) }, { "vec3d$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3D)) }, { "string$a;", Node::Ptr(new ExternalVariable("a", CoreType::STRING)) }, { "s$a;", Node::Ptr(new ExternalVariable("a", CoreType::STRING)) }, }; } class TestExternalVariableNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestExternalVariableNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestExternalVariableNode); void TestExternalVariableNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::ExternalVariableNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for External Variable code", code) + os.str()); } } }
3,130
C++
36.273809
101
0.630671
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestBinaryOperatorNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a + b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::PLUS ) ) }, { "a - b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MINUS ) ) }, { "a * b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MULTIPLY ) ) }, { "a / b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::DIVIDE ) ) }, { "a % b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MODULO ) ) }, { "a << b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::SHIFTLEFT ) ) }, { "a >> b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::SHIFTRIGHT ) ) }, { "a & b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::BITAND ) ) }, { "a | b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::BITOR ) ) }, { "a ^ b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::BITXOR ) ) }, { "a && b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::AND ) ) }, { "a || b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::OR ) ) }, { "a == b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::EQUALSEQUALS ) ) }, { "a != b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::NOTEQUALS ) ) }, { "a > b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MORETHAN ) ) }, { "a < b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::LESSTHAN ) ) }, { "a >= b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MORETHANOREQUAL ) ) }, { "a <= b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::LESSTHANOREQUAL ) ) }, { "(a) + (a);", Node::Ptr( new BinaryOperator( new Local("a"), new Local("a"), OperatorToken::PLUS ) ) }, { "(a,b,c) + (d,e,f);", Node::Ptr( new BinaryOperator( new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new CommaOperator({ new Local("d"), new Local("e"), new Local("f") }), OperatorToken::PLUS ) ) }, { "func1() + func2();", Node::Ptr( new BinaryOperator( new FunctionCall("func1"), new FunctionCall("func2"), OperatorToken::PLUS ) ) }, { "a + b - c;", Node::Ptr( new BinaryOperator( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::PLUS ), new Local("c"), OperatorToken::MINUS ) ) }, { "~a + !b;", Node::Ptr( new BinaryOperator( new UnaryOperator(new Local("a"), OperatorToken::BITNOT), new UnaryOperator(new Local("b"), OperatorToken::NOT), OperatorToken::PLUS ) ) }, { "++a - --b;", Node::Ptr( new BinaryOperator( new Crement(new Local("a"), Crement::Operation::Increment, false), new Crement(new Local("b"), Crement::Operation::Decrement, false), OperatorToken::MINUS ) ) }, { "a-- + b++;", Node::Ptr( new BinaryOperator( new Crement(new Local("a"), Crement::Operation::Decrement, true), new Crement(new Local("b"), Crement::Operation::Increment, true), OperatorToken::PLUS ) ) }, { "int(a) + float(b);", Node::Ptr( new BinaryOperator( new Cast(new Local("a"), CoreType::INT32), new Cast(new Local("b"), CoreType::FLOAT), OperatorToken::PLUS ) ) }, { "{a,b,c} + {d,e,f};", Node::Ptr( new BinaryOperator( new ArrayPack({ new Local("a"), new Local("b"), new Local("c") }), new ArrayPack({ new Local("d"), new Local("e"), new Local("f") }), OperatorToken::PLUS ) ) }, { "a.x + b.y;", Node::Ptr( new BinaryOperator( new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), new ArrayUnpack(new Local("b"), new Value<int32_t>(1)), OperatorToken::PLUS ) ) }, { "0 + 1;", Node::Ptr( new BinaryOperator( new Value<int32_t>(0), new Value<int32_t>(1), OperatorToken::PLUS ) ) }, { "0.0f + 1.0;", Node::Ptr( new BinaryOperator( new Value<float>(0.0), new Value<double>(1.0), OperatorToken::PLUS ) ) }, { "@a + @b;", Node::Ptr( new BinaryOperator( new Attribute("a", CoreType::FLOAT, true), new Attribute("b", CoreType::FLOAT, true), OperatorToken::PLUS ) ) }, { "\"a\" + \"b\";", Node::Ptr( new BinaryOperator( new Value<std::string>("a"), new Value<std::string>("b"), OperatorToken::PLUS ) ) }, }; } class TestBinaryOperatorNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestBinaryOperatorNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestBinaryOperatorNode); void TestBinaryOperatorNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::BinaryOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Binary Operator code", code) + os.str()); } } }
14,725
C++
42.184751
106
0.267029
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestDeclareLocalNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "bool a_;", Node::Ptr(new DeclareLocal(CoreType::BOOL, new Local("a_"))) }, { "int32 _;", Node::Ptr(new DeclareLocal(CoreType::INT32, new Local("_"))) }, { "int64 aa;", Node::Ptr(new DeclareLocal(CoreType::INT64, new Local("aa"))) }, { "float A;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("A"))) }, { "double _A;", Node::Ptr(new DeclareLocal(CoreType::DOUBLE, new Local("_A"))) }, { "vec2i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC2I, new Local("a1"))) }, { "vec2f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC2F, new Local("_1"))) }, { "vec2d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC2D, new Local("abc"))) }, { "vec3i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC3I, new Local("a1"))) }, { "vec3f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC3F, new Local("_1"))) }, { "vec3d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC3D, new Local("abc"))) }, { "vec4i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC4I, new Local("a1"))) }, { "vec4f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC4F, new Local("_1"))) }, { "vec4d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC4D, new Local("abc"))) }, { "mat3f _1;", Node::Ptr(new DeclareLocal(CoreType::MAT3F, new Local("_1"))) }, { "mat3d abc;", Node::Ptr(new DeclareLocal(CoreType::MAT3D, new Local("abc"))) }, { "mat4f _1;", Node::Ptr(new DeclareLocal(CoreType::MAT4F, new Local("_1"))) }, { "mat4d abc;", Node::Ptr(new DeclareLocal(CoreType::MAT4D, new Local("abc"))) }, { "string D1f;", Node::Ptr(new DeclareLocal(CoreType::STRING, new Local("D1f"))) }, { "float a = 1.0f;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new Value<float>(1.0f))) }, { "float a = 1;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new Value<int32_t>(1))) }, { "float a = a + 1;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new BinaryOperator(new Local("a"), new Value<int32_t>(1), OperatorToken::PLUS))) }, { "float a = v.x;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new ArrayUnpack(new Local("v"), new Value<int32_t>(0)))) }, { "vec3f v = {1, 2, 3};", Node::Ptr(new DeclareLocal(CoreType::VEC3F, new Local("v"), new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), }))) }, { "mat3f m = 1;", Node::Ptr(new DeclareLocal(CoreType::MAT3F, new Local("m"), new Value<int32_t>(1))) }, { "string s = \"foo\";", Node::Ptr(new DeclareLocal(CoreType::STRING, new Local("s"), new Value<std::string>("foo"))) }, { "float a = b = c;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new AssignExpression(new Local("b"), new Local("c")))) }, }; } class TestDeclareLocalNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestDeclareLocalNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestDeclareLocalNode); void TestDeclareLocalNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::DeclareLocalNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Declaration code", code) + os.str()); } } }
5,116
C++
43.112069
113
0.571931
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestAXRun.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ax.h> #include <openvdb_ax/Exceptions.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointConversion.h> #include <cppunit/extensions/HelperMacros.h> class TestAXRun : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestAXRun); CPPUNIT_TEST(singleRun); CPPUNIT_TEST(multiRun); CPPUNIT_TEST_SUITE_END(); void singleRun(); void multiRun(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAXRun); void TestAXRun::singleRun() { openvdb::FloatGrid f; f.setName("a"); f.tree().setValueOn({0,0,0}, 0.0f); openvdb::ax::run("@a = 1.0f;", f); CPPUNIT_ASSERT_EQUAL(1.0f, f.tree().getValue({0,0,0})); openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()}; openvdb::points::PointDataGrid::Ptr points = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); openvdb::ax::run("@a = 1.0f;", *points); const auto leafIter = points->tree().cbeginLeaf(); const auto& descriptor = leafIter->attributeSet().descriptor(); CPPUNIT_ASSERT_EQUAL(size_t(2), descriptor.size()); const size_t idx = descriptor.find("a"); CPPUNIT_ASSERT(idx != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor.valueType(idx) == openvdb::typeNameAsString<float>()); openvdb::points::AttributeHandle<float> handle(leafIter->constAttributeArray(idx)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); } void TestAXRun::multiRun() { { // test error on points and volumes openvdb::FloatGrid::Ptr f(new openvdb::FloatGrid); openvdb::points::PointDataGrid::Ptr p(new openvdb::points::PointDataGrid); std::vector<openvdb::GridBase::Ptr> v1 { f, p }; CPPUNIT_ASSERT_THROW(openvdb::ax::run("@a = 1.0f;", v1), openvdb::AXCompilerError); std::vector<openvdb::GridBase::Ptr> v2 { p, f }; CPPUNIT_ASSERT_THROW(openvdb::ax::run("@a = 1.0f;", v2), openvdb::AXCompilerError); } { // multi volumes openvdb::FloatGrid::Ptr f1(new openvdb::FloatGrid); openvdb::FloatGrid::Ptr f2(new openvdb::FloatGrid); f1->setName("a"); f2->setName("b"); f1->tree().setValueOn({0,0,0}, 0.0f); f2->tree().setValueOn({0,0,0}, 0.0f); std::vector<openvdb::GridBase::Ptr> v { f1, f2 }; openvdb::ax::run("@a = @b = 1;", v); CPPUNIT_ASSERT_EQUAL(1.0f, f1->tree().getValue({0,0,0})); CPPUNIT_ASSERT_EQUAL(1.0f, f2->tree().getValue({0,0,0})); } { // multi points openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()}; openvdb::points::PointDataGrid::Ptr p1 = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); openvdb::points::PointDataGrid::Ptr p2 = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); std::vector<openvdb::GridBase::Ptr> v { p1, p2 }; openvdb::ax::run("@a = @b = 1;", v); const auto leafIter1 = p1->tree().cbeginLeaf(); const auto leafIter2 = p2->tree().cbeginLeaf(); const auto& descriptor1 = leafIter1->attributeSet().descriptor(); const auto& descriptor2 = leafIter1->attributeSet().descriptor(); CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor1.size()); CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor2.size()); const size_t idx1 = descriptor1.find("a"); CPPUNIT_ASSERT_EQUAL(idx1, descriptor2.find("a")); const size_t idx2 = descriptor1.find("b"); CPPUNIT_ASSERT_EQUAL(idx2, descriptor2.find("b")); CPPUNIT_ASSERT(idx1 != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(idx2 != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor1.valueType(idx1) == openvdb::typeNameAsString<float>()); CPPUNIT_ASSERT(descriptor1.valueType(idx2) == openvdb::typeNameAsString<float>()); CPPUNIT_ASSERT(descriptor2.valueType(idx1) == openvdb::typeNameAsString<float>()); CPPUNIT_ASSERT(descriptor2.valueType(idx2) == openvdb::typeNameAsString<float>()); openvdb::points::AttributeHandle<float> handle(leafIter1->constAttributeArray(idx1)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); handle = openvdb::points::AttributeHandle<float>(leafIter1->constAttributeArray(idx2)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); handle = openvdb::points::AttributeHandle<float>(leafIter2->constAttributeArray(idx1)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); handle = openvdb::points::AttributeHandle<float>(leafIter2->constAttributeArray(idx2)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); } }
5,276
C++
39.906976
113
0.65182
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestVolumeExecutable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/compiler/VolumeExecutable.h> #include <cppunit/extensions/HelperMacros.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> class TestVolumeExecutable : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestVolumeExecutable); CPPUNIT_TEST(testConstructionDestruction); CPPUNIT_TEST(testCreateMissingGrids); CPPUNIT_TEST(testTreeExecutionLevel); CPPUNIT_TEST(testCompilerCases); CPPUNIT_TEST_SUITE_END(); void testConstructionDestruction(); void testCreateMissingGrids(); void testTreeExecutionLevel(); void testCompilerCases(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestVolumeExecutable); void TestVolumeExecutable::testConstructionDestruction() { // Test the building and teardown of executable objects. This is primarily to test // the destruction of Context and ExecutionEngine LLVM objects. These must be destructed // in the correct order (ExecutionEngine, then Context) otherwise LLVM will crash // must be initialized, otherwise construction/destruction of llvm objects won't // exhibit correct behaviour CPPUNIT_ASSERT(openvdb::ax::isInitialized()); std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext); std::unique_ptr<llvm::Module> M(new llvm::Module("test_module", *C)); std::shared_ptr<const llvm::ExecutionEngine> E(llvm::EngineBuilder(std::move(M)) .setEngineKind(llvm::EngineKind::JIT) .create()); CPPUNIT_ASSERT(!M); CPPUNIT_ASSERT(E); std::weak_ptr<llvm::LLVMContext> wC = C; std::weak_ptr<const llvm::ExecutionEngine> wE = E; // Basic construction openvdb::ax::ast::Tree tree; openvdb::ax::AttributeRegistry::ConstPtr emptyReg = openvdb::ax::AttributeRegistry::create(tree); openvdb::ax::VolumeExecutable::Ptr volumeExecutable (new openvdb::ax::VolumeExecutable(C, E, emptyReg, nullptr, {})); CPPUNIT_ASSERT_EQUAL(2, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(2, int(wC.use_count())); C.reset(); E.reset(); CPPUNIT_ASSERT_EQUAL(1, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(1, int(wC.use_count())); // test destruction volumeExecutable.reset(); CPPUNIT_ASSERT_EQUAL(0, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(0, int(wC.use_count())); } void TestVolumeExecutable::testCreateMissingGrids() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("@[email protected];"); CPPUNIT_ASSERT(executable); executable->setCreateMissing(false); executable->setValueIterator(openvdb::ax::VolumeExecutable::IterType::ON); openvdb::GridPtrVec grids; CPPUNIT_ASSERT_THROW(executable->execute(grids), openvdb::AXExecutionError); CPPUNIT_ASSERT(grids.empty()); executable->setCreateMissing(true); executable->setValueIterator(openvdb::ax::VolumeExecutable::IterType::ON); executable->execute(grids); openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); CPPUNIT_ASSERT_EQUAL(size_t(2), grids.size()); CPPUNIT_ASSERT(grids[0]->getName() == "b"); CPPUNIT_ASSERT(grids[0]->isType<openvdb::Vec3fGrid>()); CPPUNIT_ASSERT(grids[0]->empty()); CPPUNIT_ASSERT(grids[0]->transform() == *defaultTransform); CPPUNIT_ASSERT(grids[1]->getName() == "a"); CPPUNIT_ASSERT(grids[1]->isType<openvdb::FloatGrid>()); CPPUNIT_ASSERT(grids[1]->empty()); CPPUNIT_ASSERT(grids[1]->transform() == *defaultTransform); } void TestVolumeExecutable::testTreeExecutionLevel() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("f@test = 1.0f;"); CPPUNIT_ASSERT(executable); using NodeT0 = openvdb::FloatGrid::Accessor::NodeT0; using NodeT1 = openvdb::FloatGrid::Accessor::NodeT1; using NodeT2 = openvdb::FloatGrid::Accessor::NodeT2; openvdb::FloatGrid test; test.setName("test"); // NodeT0 tile test.tree().addTile(1, openvdb::Coord(0), -2.0f, /*active*/true); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); // default is leaf nodes, expect no change executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); executable->setTreeExecutionLevel(1); executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0))); // NodeT1 tile test.tree().addTile(2, openvdb::Coord(0), -2.0f, /*active*/true); // level is set to 1, expect no change executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT1::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); executable->setTreeExecutionLevel(2); executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT1::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0))); // NodeT2 tile test.tree().addTile(3, openvdb::Coord(0), -2.0f, /*active*/true); // level is set to 2, expect no change executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT2::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); executable->setTreeExecutionLevel(3); executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT2::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0))); // test higher values throw CPPUNIT_ASSERT_THROW(executable->setTreeExecutionLevel(4), openvdb::RuntimeError); } void TestVolumeExecutable::testCompilerCases() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); CPPUNIT_ASSERT(compiler); { // with string only CPPUNIT_ASSERT(static_cast<bool>(compiler->compile<openvdb::ax::VolumeExecutable>("int i;"))); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>("i;"), openvdb::AXCompilerError); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>("i"), openvdb::AXCompilerError); // with AST only auto ast = openvdb::ax::ast::parse("i;"); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>(*ast), openvdb::AXCompilerError); } openvdb::ax::Logger logger([](const std::string&) {}); // using string and logger { openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("", logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("i;", logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>("i", logger); // expected ; error (parser) CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("int i = 18446744073709551615;", logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); } // using syntax tree and logger logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); CPPUNIT_ASSERT(tree); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable); logger.clear(); // no tree for line col numbers openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable2); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); // no tree for line col numbers openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); logger.clear(); // no tree for line col numbers openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable2); CPPUNIT_ASSERT(logger.hasWarning()); } logger.clear(); // with copied tree { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); } logger.clear(); }
12,216
C++
39.996644
115
0.672561
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestPointExecutable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/compiler/PointExecutable.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointGroup.h> #include <cppunit/extensions/HelperMacros.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> class TestPointExecutable : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestPointExecutable); CPPUNIT_TEST(testConstructionDestruction); CPPUNIT_TEST(testCreateMissingAttributes); CPPUNIT_TEST(testGroupExecution); CPPUNIT_TEST(testCompilerCases); CPPUNIT_TEST_SUITE_END(); void testConstructionDestruction(); void testCreateMissingAttributes(); void testGroupExecution(); void testCompilerCases(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestPointExecutable); void TestPointExecutable::testConstructionDestruction() { // Test the building and teardown of executable objects. This is primarily to test // the destruction of Context and ExecutionEngine LLVM objects. These must be destructed // in the correct order (ExecutionEngine, then Context) otherwise LLVM will crash // must be initialized, otherwise construction/destruction of llvm objects won't // exhibit correct behaviour CPPUNIT_ASSERT(openvdb::ax::isInitialized()); std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext); std::unique_ptr<llvm::Module> M(new llvm::Module("test_module", *C)); std::shared_ptr<const llvm::ExecutionEngine> E(llvm::EngineBuilder(std::move(M)) .setEngineKind(llvm::EngineKind::JIT) .create()); CPPUNIT_ASSERT(!M); CPPUNIT_ASSERT(E); std::weak_ptr<llvm::LLVMContext> wC = C; std::weak_ptr<const llvm::ExecutionEngine> wE = E; // Basic construction openvdb::ax::ast::Tree tree; openvdb::ax::AttributeRegistry::ConstPtr emptyReg = openvdb::ax::AttributeRegistry::create(tree); openvdb::ax::PointExecutable::Ptr pointExecutable (new openvdb::ax::PointExecutable(C, E, emptyReg, nullptr, {})); CPPUNIT_ASSERT_EQUAL(2, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(2, int(wC.use_count())); C.reset(); E.reset(); CPPUNIT_ASSERT_EQUAL(1, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(1, int(wC.use_count())); // test destruction pointExecutable.reset(); CPPUNIT_ASSERT_EQUAL(0, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(0, int(wC.use_count())); } void TestPointExecutable::testCreateMissingAttributes() { openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()}; openvdb::points::PointDataGrid::Ptr grid = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("@[email protected];"); CPPUNIT_ASSERT(executable); executable->setCreateMissing(false); CPPUNIT_ASSERT_THROW(executable->execute(*grid), openvdb::AXExecutionError); executable->setCreateMissing(true); executable->execute(*grid); const auto leafIter = grid->tree().cbeginLeaf(); const auto& descriptor = leafIter->attributeSet().descriptor(); CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor.size()); const size_t bIdx = descriptor.find("b"); CPPUNIT_ASSERT(bIdx != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor.valueType(bIdx) == openvdb::typeNameAsString<openvdb::Vec3f>()); openvdb::points::AttributeHandle<openvdb::Vec3f>::Ptr bHandle = openvdb::points::AttributeHandle<openvdb::Vec3f>::create(leafIter->constAttributeArray(bIdx)); CPPUNIT_ASSERT(bHandle->get(0) == openvdb::Vec3f::zero()); const size_t aIdx = descriptor.find("a"); CPPUNIT_ASSERT(aIdx != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor.valueType(aIdx) == openvdb::typeNameAsString<float>()); openvdb::points::AttributeHandle<float>::Ptr aHandle = openvdb::points::AttributeHandle<float>::create(leafIter->constAttributeArray(aIdx)); CPPUNIT_ASSERT(aHandle->get(0) == 0.0f); } void TestPointExecutable::testGroupExecution() { openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(0.1); // 4 points in 4 leaf nodes const std::vector<openvdb::Vec3d> positions = { {0,0,0}, {1,1,1}, {2,2,2}, {3,3,3}, }; openvdb::points::PointDataGrid::Ptr grid = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid> (positions, *defaultTransform); // check the values of "a" auto checkValues = [&](const int expected) { auto leafIter = grid->tree().cbeginLeaf(); CPPUNIT_ASSERT(leafIter); const auto& descriptor = leafIter->attributeSet().descriptor(); const size_t aIdx = descriptor.find("a"); CPPUNIT_ASSERT(aIdx != openvdb::points::AttributeSet::INVALID_POS); for (; leafIter; ++leafIter) { openvdb::points::AttributeHandle<int> handle(leafIter->constAttributeArray(aIdx)); CPPUNIT_ASSERT(handle.size() == 1); CPPUNIT_ASSERT_EQUAL(expected, handle.get(0)); } }; openvdb::points::appendAttribute<int>(grid->tree(), "a", 0); openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("i@a=1;"); CPPUNIT_ASSERT(executable); const std::string group = "test"; // non existent group executable->setGroupExecution(group); CPPUNIT_ASSERT_THROW(executable->execute(*grid), openvdb::LookupError); checkValues(0); openvdb::points::appendGroup(grid->tree(), group); // false group executable->execute(*grid); checkValues(0); openvdb::points::setGroup(grid->tree(), group, true); // true group executable->execute(*grid); checkValues(1); } void TestPointExecutable::testCompilerCases() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); CPPUNIT_ASSERT(compiler); { // with string only CPPUNIT_ASSERT(static_cast<bool>(compiler->compile<openvdb::ax::PointExecutable>("int i;"))); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>("i;"), openvdb::AXCompilerError); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>("i"), openvdb::AXCompilerError); // with AST only auto ast = openvdb::ax::ast::parse("i;"); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>(*ast), openvdb::AXCompilerError); } openvdb::ax::Logger logger([](const std::string&) {}); // using string and logger { openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("", logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("i;", logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>("i", logger); // expected ; error (parser) CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("int i = 18446744073709551615;", logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); } // using syntax tree and logger logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); CPPUNIT_ASSERT(tree); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable); logger.clear(); // no tree for line col numbers openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable2); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); // no tree for line col numbers openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); logger.clear(); // no tree for line col numbers openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable2); CPPUNIT_ASSERT(logger.hasWarning()); } logger.clear(); // with copied tree { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // undeclared variable error CPPUNIT_ASSERT(!executable); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // warning CPPUNIT_ASSERT(executable); } logger.clear(); }
11,201
C++
36.590604
114
0.660923
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/ast/TestScanners.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { // No dependencies // - use @a once (read), no other variables const std::vector<std::string> none = { "@a;", "@a+1;", "@a=1;", "@a=func(5);", "-@a;", "@a[0]=1;", "if(true) @a = 1;", "if(@a) a=1;", "if (@e) if (@b) if (@c) @a;", "@b = c ? : @a;", "@a ? : c = 1;", "for (@a; @b; @c) ;", "while (@a) ;", "for(;true;) @a = 1;" }; // Self dependencies // - use @a potentially multiple times (read/write), no other variables const std::vector<std::string> self = { "@a=@a;", "@a+=1;", "++@a;", "@a--;", "func(@a);", "--@a + 1;", "if(@a) @a = 1;", "if(@a) ; else @a = 1;", "@a ? : @a = 2;", "for (@b;@a;@c) @a = 0;", "while(@a) @a = 1;" }; // Code where @a should have a direct dependency on @b only // - use @a once (read/write), use @b once const std::vector<std::string> direct = { "@a=@b;", "@a=-@b;", "@a=@b;", "@a=1+@b;", "@a=func(@b);", "@a=++@b;", "if(@b) @a=1;", "if(@b) {} else { @a=1; }", "@b ? @a = 1 : 0;", "@b ? : @a = 1;", "for (;@b;) @a = 1;", "while (@b) @a = 1;" }; // Code where @a should have a direct dependency on @b only // - use @a once (read/write), use @b once, b a vector const std::vector<std::string> directvec = { "@[email protected];", "@a=v@b[0];", "@[email protected] + 1;", "@a=v@b[0] * 3;", "if (v@b[0]) @a = 3;", }; // Code where @a should have dependencies on @b and c (c always first) const std::vector<std::string> indirect = { "c=@b; @a=c;", "c=@b; @a=c[0];", "c = {@b,1,2}; @a=c;", "int c=@b; @a=c;", "int c; c=@b; @a=c;", "if (c = @b) @a = c;", "(c = @b) ? @a=c : 0;", "(c = @b) ? : @a=c;", "for(int c = @b; true; e) @a = c;", "for(int c = @b;; @a = c) ;", "for(int c = @b; c; e) @a = c;", "for(c = @b; c; e) @a = c;", "int c; for(c = @b; c; e) @a = c;", "for(; c = @b;) @a = c;", "while(int c = @b) @a = c;", }; } class TestScanners : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestScanners); CPPUNIT_TEST(testVisitNodeType); CPPUNIT_TEST(testFirstLastLocation); CPPUNIT_TEST(testAttributeDependencyTokens); // CPPUNIT_TEST(testVariableDependencies); CPPUNIT_TEST_SUITE_END(); void testVisitNodeType(); void testFirstLastLocation(); void testAttributeDependencyTokens(); // void testVariableDependencies(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestScanners); void TestScanners::testVisitNodeType() { size_t count = 0; auto counter = [&](const Node&) -> bool { ++count; return true; }; // "int64@a;" Node::Ptr node(new Attribute("a", CoreType::INT64)); visitNodeType<Node>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Local>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(0), count); count = 0; visitNodeType<Variable>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Attribute>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); // "{1.0f, 2.0, 3};" node.reset(new ArrayPack( { new Value<float>(1.0f), new Value<double>(2.0), new Value<int64_t>(3) })); count = 0; visitNodeType<Node>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(4), count); count = 0; visitNodeType<Local>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(0), count); count = 0; visitNodeType<ValueBase>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(3), count); count = 0; visitNodeType<ArrayPack>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Expression>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(4), count); count = 0; visitNodeType<Statement>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(4), count); // "@a += [email protected] = x %= 1;" // @note 9 explicit nodes node.reset(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new ArrayUnpack( new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0) ), new AssignExpression( new Local("x"), new Value<int32_t>(1), OperatorToken::MODULO ) ), OperatorToken::PLUS )); count = 0; visitNodeType<Node>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(9), count); count = 0; visitNodeType<Local>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Attribute>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(2), count); count = 0; visitNodeType<Value<int>>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(2), count); count = 0; visitNodeType<ArrayUnpack>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<AssignExpression>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(3), count); count = 0; visitNodeType<Expression>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(9), count); } void TestScanners::testFirstLastLocation() { // The list of above code sets which are expected to have the same // first and last use of @a. const std::vector<const std::vector<std::string>*> snippets { &none, &direct, &indirect }; for (const auto& samples : snippets) { for (const std::string& code : *samples) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* first = firstUse(*tree, "@a"); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to locate first @a AST node", code), first); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to locate last @a AST node", code), last); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid first/last AST node comparison", code), first == last); } } // Test some common edge cases // @a = @a; Node::Ptr node(new AssignExpression( new Attribute("a", CoreType::FLOAT), new Attribute("a", CoreType::FLOAT))); const Node* expectedFirst = static_cast<AssignExpression*>(node.get())->lhs(); const Node* expectedLast = static_cast<AssignExpression*>(node.get())->rhs(); CPPUNIT_ASSERT(expectedFirst != expectedLast); const Node* first = firstUse(*node, "@a"); const Node* last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "@a=@a"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "@a=@a"), last, expectedLast); // for(@a;@a;@a) { @a; } node.reset(new Loop( tokens::FOR, new Attribute("a", CoreType::FLOAT), new Block(new Attribute("a", CoreType::FLOAT)), new Attribute("a", CoreType::FLOAT), new Attribute("a", CoreType::FLOAT) )); expectedFirst = static_cast<Loop*>(node.get())->initial(); expectedLast = static_cast<Loop*>(node.get())->body()->child(0); CPPUNIT_ASSERT(expectedFirst != expectedLast); first = firstUse(*node, "@a"); last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "for(@a;@a;@a) { @a; }"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "for(@a;@a;@a) { @a; }"), last, expectedLast); // do { @a; } while(@a); node.reset(new Loop( tokens::DO, new Attribute("a", CoreType::FLOAT), new Block(new Attribute("a", CoreType::FLOAT)), nullptr, nullptr )); expectedFirst = static_cast<Loop*>(node.get())->body()->child(0); expectedLast = static_cast<Loop*>(node.get())->condition(); CPPUNIT_ASSERT(expectedFirst != expectedLast); first = firstUse(*node, "@a"); last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "do { @a; } while(@a);"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "do { @a; } while(@a);"), last, expectedLast); // if (@a) {} else if (@a) {} else { @a; } node.reset(new ConditionalStatement( new Attribute("a", CoreType::FLOAT), new Block(), new Block( new ConditionalStatement( new Attribute("a", CoreType::FLOAT), new Block(), new Block(new Attribute("a", CoreType::FLOAT)) ) ) )); expectedFirst = static_cast<ConditionalStatement*>(node.get())->condition(); expectedLast = static_cast<const ConditionalStatement*>( static_cast<ConditionalStatement*>(node.get()) ->falseBranch()->child(0)) ->falseBranch()->child(0); CPPUNIT_ASSERT(expectedFirst != expectedLast); first = firstUse(*node, "@a"); last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "if (@a) {} else if (1) {} else { @a; }"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "if (@a) {} else if (1) {} else { @a; }"), last, expectedLast); } void TestScanners::testAttributeDependencyTokens() { for (const std::string& code : none) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected 0 deps", code), dependencies.empty()); } for (const std::string& code : self) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("float@a")); } for (const std::string& code : direct) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("float@b")); } for (const std::string& code : directvec) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("vec3f@b")); } for (const std::string& code : indirect) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("float@b")); } // Test a more complicated code snippet. Note that this also checks the // order which isn't strictly necessary const std::string complex = "int a = func(1,@e);" "pow(@d, a);" "mat3f m = 0;" "scale(m, v@v);" "" "float f1 = 0;" "float f2 = 0;" "float f3 = 0;" "" "f3 = @f;" "f2 = f3;" "f1 = f2;" "if (@a - @e > f1) {" " @b = func(m);" " if (true) {" " ++@c[0] = a;" " }" "}"; const Tree::ConstPtr tree = parse(complex.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "b", tokens::CoreType::FLOAT, dependencies); // @b should depend on: @a, @e, @f, v@v CPPUNIT_ASSERT_EQUAL(4ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@a")); CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@e")); CPPUNIT_ASSERT_EQUAL(dependencies[2], std::string("float@f")); CPPUNIT_ASSERT_EQUAL(dependencies[3], std::string("vec3f@v")); // @c should depend on: @a, @c, @d, @e, @f dependencies.clear(); attributeDependencyTokens(*tree, "c", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_EQUAL(5ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@a")); CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@c")); CPPUNIT_ASSERT_EQUAL(dependencies[2], std::string("float@d")); CPPUNIT_ASSERT_EQUAL(dependencies[3], std::string("float@e")); CPPUNIT_ASSERT_EQUAL(dependencies[4], std::string("float@f")); // @d should depend on: @d, @e dependencies.clear(); attributeDependencyTokens(*tree, "d", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_EQUAL(2ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@d")); CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@e")); // @e should depend on itself dependencies.clear(); attributeDependencyTokens(*tree, "e", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_EQUAL(1ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@e")); // @f should depend on nothing dependencies.clear(); attributeDependencyTokens(*tree, "f", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(dependencies.empty()); // @v should depend on: v@v dependencies.clear(); attributeDependencyTokens(*tree, "v", tokens::CoreType::VEC3F, dependencies); CPPUNIT_ASSERT_EQUAL(1ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("vec3f@v")); } /* void TestScanners::testVariableDependencies() { for (const std::string& code : none) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected 0 deps", code), vars.empty()); } for (const std::string& code : self) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); const Variable* var = vars.front(); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Attribute>()); const Attribute* attrib = static_cast<const Attribute*>(var); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("float@a"), attrib->tokenname()); } for (const std::string& code : direct) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); const Variable* var = vars.front(); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Attribute>()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("b"), var->name()); } for (const std::string& code : indirect) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); // check c const Variable* var = vars[0]; CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Local>()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("c"), var->name()); // check @b var = vars[1]; CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Attribute>()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("b"), var->name()); } // Test a more complicated code snippet. Note that this also checks the // order which isn't strictly necessary const std::string complex = "int a = func(1,@e);" "pow(@d, a);" "mat3f m = 0;" "scale(m, v@v);" "" "float f1 = 0;" "float f2 = 0;" "float f3 = 0;" "" "f3 = @f;" "f2 = f3;" "f1 = f2;" "if (@a - @e > f1) {" " @b = func(m);" " if (true) {" " ++@c[0] = a;" " }" "}"; const Tree::ConstPtr tree = parse(complex.c_str()); CPPUNIT_ASSERT(tree); const Variable* lasta = lastUse(*tree, "@a"); const Variable* lastb = lastUse(*tree, "@b"); const Variable* lastc = lastUse(*tree, "@c"); const Variable* lastd = lastUse(*tree, "@d"); const Variable* laste = lastUse(*tree, "@e"); const Variable* lastf = lastUse(*tree, "@f"); const Variable* lastv = lastUse(*tree, "vec3f@v"); CPPUNIT_ASSERT(lasta); CPPUNIT_ASSERT(lastb); CPPUNIT_ASSERT(lastc); CPPUNIT_ASSERT(lastd); CPPUNIT_ASSERT(laste); CPPUNIT_ASSERT(lastf); CPPUNIT_ASSERT(lastv); std::vector<const Variable*> vars; variableDependencies(*lasta, vars); CPPUNIT_ASSERT(vars.empty()); // @b should depend on: m, m, v@v, @a, @e, @e, f1, f2, f3, @f variableDependencies(*lastb, vars); CPPUNIT_ASSERT_EQUAL(10ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Local>()); CPPUNIT_ASSERT(vars[0]->name() == "m"); CPPUNIT_ASSERT(vars[1]->isType<Local>()); CPPUNIT_ASSERT(vars[1]->name() == "m"); CPPUNIT_ASSERT(vars[2]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "vec3f@v"); CPPUNIT_ASSERT(vars[3]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[3])->tokenname() == "float@a"); CPPUNIT_ASSERT(vars[4]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[4])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[5]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[5])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[6]->isType<Local>()); CPPUNIT_ASSERT(vars[6]->name() == "f1"); CPPUNIT_ASSERT(vars[7]->isType<Local>()); CPPUNIT_ASSERT(vars[7]->name() == "f2"); CPPUNIT_ASSERT(vars[8]->isType<Local>()); CPPUNIT_ASSERT(vars[8]->name() == "f3"); CPPUNIT_ASSERT(vars[9]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[9])->tokenname() == "float@f"); // @c should depend on: @c, a, @e, @d, a, @e, @a, @e, f1, f2, f3, @f vars.clear(); variableDependencies(*lastc, vars); CPPUNIT_ASSERT_EQUAL(11ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@c"); CPPUNIT_ASSERT(vars[1]->isType<Local>()); CPPUNIT_ASSERT(vars[1]->name() == "a"); CPPUNIT_ASSERT(vars[2]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[3]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[3])->tokenname() == "float@d"); CPPUNIT_ASSERT(vars[4]->isType<Local>()); CPPUNIT_ASSERT(vars[4]->name() == "a"); CPPUNIT_ASSERT(vars[5]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[5])->tokenname() == "float@a"); CPPUNIT_ASSERT(vars[6]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[6])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[7]->isType<Local>()); CPPUNIT_ASSERT(vars[7]->name() == "f1"); CPPUNIT_ASSERT(vars[8]->isType<Local>()); CPPUNIT_ASSERT(vars[8]->name() == "f2"); CPPUNIT_ASSERT(vars[9]->isType<Local>()); CPPUNIT_ASSERT(vars[9]->name() == "f3"); CPPUNIT_ASSERT(vars[10]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[10])->tokenname() == "float@f"); // @d should depend on: @d, a, @e vars.clear(); variableDependencies(*lastd, vars); CPPUNIT_ASSERT_EQUAL(3ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@d"); CPPUNIT_ASSERT(vars[1]->isType<Local>()); CPPUNIT_ASSERT(vars[1]->name() == "a"); CPPUNIT_ASSERT(vars[2]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "float@e"); // @e should depend on itself vars.clear(); variableDependencies(*laste, vars); CPPUNIT_ASSERT_EQUAL(1ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@e"); // @f should depend on nothing vars.clear(); variableDependencies(*lastf, vars); CPPUNIT_ASSERT(vars.empty()); // @v should depend on: m, v@v vars.clear(); variableDependencies(*lastv, vars); CPPUNIT_ASSERT_EQUAL(2ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Local>()); CPPUNIT_ASSERT(vars[0]->name() == "m"); CPPUNIT_ASSERT(vars[1]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[1])->tokenname() == "vec3f@v"); } */
22,773
C++
33.453858
97
0.585957
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/ast/TestPrinters.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Parse.h> #include <openvdb_ax/ast/PrintTree.h> #include <cppunit/extensions/HelperMacros.h> #include <string> #include <ostream> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; class TestPrinters : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestPrinters); CPPUNIT_TEST(testReprint); CPPUNIT_TEST_SUITE_END(); void testReprint(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestPrinters); void TestPrinters::testReprint() { // Small function providing more verbose output on failures auto check = [](const std::string& in, const std::string& expected) { const size_t min = std::min(in.size(), expected.size()); for (size_t i = 0; i < min; ++i) { if (in[i] != expected[i]) { std::ostringstream msg; msg << "TestReprint failed at character " << i << '.' << '[' << in[i] << "] vs [" << expected[i] << "]\n" << "Got:\n" << in << "Expected:\n" << expected; CPPUNIT_FAIL(msg.str()); } } if (in.size() != expected.size()) { std::ostringstream msg; msg << "TestReprint failed at end character.\n" << "Got:\n" << in << "Expected:\n" << expected ; CPPUNIT_FAIL(msg.str()); } }; std::ostringstream os; // Test binary ops std::string in = "a + b * c / d % e << f >> g = h & i | j ^ k && l || m;"; std::string expected = "(((a + (((b * c) / d) % e)) << f) >> g = ((((h & i) | (j ^ k)) && l) || m));\n"; Tree::ConstPtr tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test binary ops paren os.str(""); in = "(a + b) * (c / d) % e << (f) >> g = (((h & i) | j) ^ k) && l || m;"; expected = "(((((a + b) * (c / d)) % e) << f) >> g = (((((h & i) | j) ^ k) && l) || m));\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test relational os.str(""); in = "a <= b; c >= d; e == f; g != h; i < j; k > l;"; expected = "(a <= b);\n(c >= d);\n(e == f);\n(g != h);\n(i < j);\n(k > l);\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test assignments os.str(""); in = "a = b; b += c; c -= d; d /= e; e *= f; f %= 1; g &= 2; h |= 3; i ^= 4; j <<= 5; k >>= 6;"; expected = "a = b;\nb += c;\nc -= d;\nd /= e;\ne *= f;\nf %= 1;\ng &= 2;\nh |= 3;\ni ^= 4;\nj <<= 5;\nk >>= 6;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test crement os.str(""); in = "++++a; ----b; a++; b--;"; expected = "++++a;\n----b;\na++;\nb--;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test comma os.str(""); in = "a,b,(c,d),(e,(f,(g,h,i)));"; expected = "(a, b, (c, d), (e, (f, (g, h, i))));\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test array unpack os.str(""); in = "a.x; b.y; c.z; d[0]; d[1,2]; e[(a.r, c.b), b.g];"; expected = "a[0];\nb[1];\nc[2];\nd[0];\nd[1, 2];\ne[(a[0], c[2]), b[1]];\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test array pack os.str(""); in = "a = {0,1}; b = {2,3,4}; c = {a,(b,c), d};"; expected = "a = {0, 1};\nb = {2, 3, 4};\nc = {a, (b, c), d};\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test declarations os.str(""); in = "bool a; int b,c; int32 d=0, e; int64 f; float g; double h, i=0;"; expected = "bool a;\nint32 b, c;\nint32 d = 0, e;\nint64 f;\nfloat g;\ndouble h, i = 0;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test conditionals os.str(""); in = "if (a) b; else if (c) d; else e; if (a) if (b) { c,d; } else { e,f; }"; expected = "if (a)\n{\nb;\n}\nelse\n{\nif (c)\n{\nd;\n}\nelse\n{\ne;\n}\n}\nif (a)\n{\nif (b)\n{\n(c, d);\n}\nelse\n{\n(e, f);\n}\n}\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test keywords os.str(""); in = "return; break; continue; true; false;"; expected = "return;\nbreak;\ncontinue;\ntrue;\nfalse;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test attributes/externals os.str(""); in = "@a; $a; v@b; v$b; f@a; f$a; i@c; i$c; s@d; s$d;"; expected = "float@a;\nfloat$a;\nvec3f@b;\nvec3f$b;\nfloat@a;\nfloat$a;\nint32@c;\nint32$c;\nstring@d;\nstring$d;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test ternary os.str(""); in = "a ? b : c; a ? b ? c ? : d : e : f;"; expected = "a ? b : c;\na ? b ? c ?: d : e : f;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test loops os.str(""); in = "while (a) for (int32 b, c;;) do { d; } while (e)"; expected = "while (a)\n{\nfor (int32 b, c; true; )\n{\ndo\n{\nd;\n}\nwhile (e)\n}\n}\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test loops with indents os.str(""); in = "while (a) for (int32 b, c;;) do { d; } while (e)"; expected = " while (a)\n {\n for (int32 b, c; true; )\n {\n do\n {\n d;\n }\n while (e)\n }\n }\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, " "); check(os.str(), ("{\n" + expected + "}\n")); }
6,566
C++
33.382199
142
0.465885
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/cmd/openvdb_ax.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file cmd/openvdb_ax.cc /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief The command line vdb_ax binary which provides tools to /// run and analyze AX code. /// #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/codegen/Functions.h> #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/compiler/AttributeRegistry.h> #include <openvdb_ax/compiler/CompilerOptions.h> #include <openvdb_ax/compiler/PointExecutable.h> #include <openvdb_ax/compiler/VolumeExecutable.h> #include <openvdb_ax/compiler/Logger.h> #include <openvdb/openvdb.h> #include <openvdb/version.h> #include <openvdb/util/logging.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/points/PointDelete.h> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> const char* gProgName = ""; void usage [[noreturn]] (int exitStatus = EXIT_FAILURE) { std::cerr << "Usage: " << gProgName << " [input.vdb [output.vdb] | analyze] [-s \"string\" | -f file.txt] [OPTIONS]\n" << "Which: executes a string or file containing a code snippet on an input.vdb file\n\n" << "Options:\n" << " -s snippet execute code snippet on the input.vdb file\n" << " -f file.txt execute text file containing a code snippet on the input.vdb file\n" << " -v verbose (print timing and diagnostics)\n" << " --opt level set an optimization level on the generated IR [NONE, O0, O1, O2, Os, Oz, O3]\n" << " --werror set warnings as errors\n" << " --max-errors n sets the maximum number of error messages to n, a value of 0 (default) allows all error messages\n" << " analyze parse the provided code and enter analysis mode\n" << " --ast-print descriptive print the abstract syntax tree generated\n" << " --re-print re-interpret print of the provided code after ast traversal\n" << " --reg-print print the attribute registry (name, types, access, dependencies)\n" << " --try-compile [points|volumes] \n" << " attempt to compile the provided code for points or volumes, or both if no\n" << " additional option is provided, reporting any failures or success.\n" << " functions enter function mode to query available function information\n" << " --list [name] list all available functions, their documentation and their signatures.\n" << " optionally only list functions which whose name includes a provided string.\n" << " --list-names list all available functions names only\n" << "Warning:\n" << " Providing the same file-path to both input.vdb and output.vdb arguments will overwrite\n" << " the file. If no output file is provided, the input.vdb will be processed but will remain\n" << " unchanged on disk (this is useful for testing the success status of code).\n"; exit(exitStatus); } struct ProgOptions { enum Mode { Execute, Analyze, Functions }; enum Compilation { All, Points, Volumes }; Mode mMode = Execute; // Compilation options size_t mMaxErrors = 0; bool mWarningsAsErrors = false; // Execute options std::unique_ptr<std::string> mInputCode = nullptr; std::string mInputVDBFile = ""; std::string mOutputVDBFile = ""; bool mVerbose = false; openvdb::ax::CompilerOptions::OptLevel mOptLevel = openvdb::ax::CompilerOptions::OptLevel::O3; // Analyze options bool mPrintAST = false; bool mReprint = false; bool mAttribRegPrint = false; bool mInitCompile = false; Compilation mCompileFor = All; // Function Options bool mFunctionList = false; bool mFunctionNamesOnly = false; std::string mFunctionSearch = ""; }; inline std::string modeString(const ProgOptions::Mode mode) { switch (mode) { case ProgOptions::Execute : return "execute"; case ProgOptions::Analyze : return "analyze"; case ProgOptions::Functions : return "functions"; default : return ""; } } ProgOptions::Compilation tryCompileStringToCompilation(const std::string& str) { if (str == "points") return ProgOptions::Points; if (str == "volumes") return ProgOptions::Volumes; OPENVDB_LOG_FATAL("invalid option given for --try-compile level"); usage(); } openvdb::ax::CompilerOptions::OptLevel optStringToLevel(const std::string& str) { if (str == "NONE") return openvdb::ax::CompilerOptions::OptLevel::NONE; if (str == "O0") return openvdb::ax::CompilerOptions::OptLevel::O0; if (str == "O1") return openvdb::ax::CompilerOptions::OptLevel::O1; if (str == "O2") return openvdb::ax::CompilerOptions::OptLevel::O2; if (str == "Os") return openvdb::ax::CompilerOptions::OptLevel::Os; if (str == "Oz") return openvdb::ax::CompilerOptions::OptLevel::Oz; if (str == "O3") return openvdb::ax::CompilerOptions::OptLevel::O3; OPENVDB_LOG_FATAL("invalid option given for --opt level"); usage(); } inline std::string optLevelToString(const openvdb::ax::CompilerOptions::OptLevel level) { switch (level) { case openvdb::ax::CompilerOptions::OptLevel::NONE : return "NONE"; case openvdb::ax::CompilerOptions::OptLevel::O1 : return "O1"; case openvdb::ax::CompilerOptions::OptLevel::O2 : return "O2"; case openvdb::ax::CompilerOptions::OptLevel::Os : return "Os"; case openvdb::ax::CompilerOptions::OptLevel::Oz : return "Oz"; case openvdb::ax::CompilerOptions::OptLevel::O3 : return "O3"; default : return ""; } } void loadSnippetFile(const std::string& fileName, std::string& textString) { std::ifstream in(fileName.c_str(), std::ios::in | std::ios::binary); if (!in) { OPENVDB_LOG_FATAL("File Load Error: " << fileName); usage(); } textString = std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()); } struct OptParse { int argc; char** argv; OptParse(int argc_, char* argv_[]): argc(argc_), argv(argv_) {} bool check(int idx, const std::string& name, int numArgs = 1) const { if (argv[idx] == name) { if (idx + numArgs >= argc) { OPENVDB_LOG_FATAL("option " << name << " requires " << numArgs << " argument" << (numArgs == 1 ? "" : "s")); usage(); } return true; } return false; } }; struct ScopedInitialize { ScopedInitialize(int argc, char *argv[]) { openvdb::logging::initialize(argc, argv); openvdb::initialize(); } ~ScopedInitialize() { if (openvdb::ax::isInitialized()) { openvdb::ax::uninitialize(); } openvdb::uninitialize(); } inline void initializeCompiler() const { openvdb::ax::initialize(); } inline bool isInitialized() const { return openvdb::ax::isInitialized(); } }; void printFunctions(const bool namesOnly, const std::string& search, std::ostream& os) { static const size_t maxHelpTextWidth = 100; openvdb::ax::FunctionOptions opts; opts.mLazyFunctions = false; const openvdb::ax::codegen::FunctionRegistry::UniquePtr registry = openvdb::ax::codegen::createDefaultRegistry(&opts); // convert to ordered map for alphabetical sorting // only include non internal functions and apply any search // criteria std::map<std::string, const openvdb::ax::codegen::FunctionGroup*> functionMap; for (const auto& iter : registry->map()) { if (iter.second.isInternal()) continue; if (!search.empty() && iter.first.find(search) == std::string::npos) { continue; } functionMap[iter.first] = iter.second.function(); } if (functionMap.empty()) return; if (namesOnly) { const size_t size = functionMap.size(); size_t pos = 0, count = 0; auto iter = functionMap.cbegin(); for (; iter != functionMap.cend(); ++iter) { if (count == size - 1) break; const std::string& name = iter->first; if (count != 0 && pos > maxHelpTextWidth) { os << '\n'; pos = 0; } pos += name.size() + 2; // 2=", " os << name << ',' << ' '; ++count; } os << iter->first << '\n'; } else { llvm::LLVMContext C; for (const auto& iter : functionMap) { const openvdb::ax::codegen::FunctionGroup* const function = iter.second; const char* cdocs = function->doc(); if (!cdocs || cdocs[0] == '\0') { cdocs = "<No documentation exists for this function>"; } // do some basic formatting on the help text std::string docs(cdocs); size_t pos = maxHelpTextWidth; while (pos < docs.size()) { while (docs[pos] != ' ' && pos != 0) --pos; if (pos == 0) break; docs.insert(pos, "\n| "); pos += maxHelpTextWidth; } os << iter.first << '\n' << '|' << '\n'; os << "| - " << docs << '\n' << '|' << '\n'; const auto& list = function->list(); for (const openvdb::ax::codegen::Function::Ptr& decl : list) { os << "| - "; decl->print(C, os); os << '\n'; } os << '\n'; } } } int main(int argc, char *argv[]) { OPENVDB_START_THREADSAFE_STATIC_WRITE gProgName = argv[0]; const char* ptr = ::strrchr(gProgName, '/'); if (ptr != nullptr) gProgName = ptr + 1; OPENVDB_FINISH_THREADSAFE_STATIC_WRITE if (argc == 1) usage(); OptParse parser(argc, argv); ProgOptions opts; openvdb::util::CpuTimer timer; auto getTime = [&timer]() -> std::string { const double msec = timer.milliseconds(); std::ostringstream os; openvdb::util::printTime(os, msec, "", "", 1, 1, 0); return os.str(); }; auto& os = std::cout; #define axlog(message) \ { if (opts.mVerbose) os << message; } #define axtimer() timer.restart() #define axtime() getTime() bool multiSnippet = false; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg[0] == '-') { if (parser.check(i, "-s")) { ++i; multiSnippet |= static_cast<bool>(opts.mInputCode); opts.mInputCode.reset(new std::string(argv[i])); } else if (parser.check(i, "-f")) { ++i; multiSnippet |= static_cast<bool>(opts.mInputCode); opts.mInputCode.reset(new std::string()); loadSnippetFile(argv[i], *opts.mInputCode); } else if (parser.check(i, "-v", 0)) { opts.mVerbose = true; } else if (parser.check(i, "--max-errors")) { opts.mMaxErrors = atoi(argv[++i]); } else if (parser.check(i, "--werror", 0)) { opts.mWarningsAsErrors = true; } else if (parser.check(i, "--list", 0)) { opts.mFunctionList = true; opts.mInitCompile = true; // need to intialize llvm opts.mFunctionNamesOnly = false; if (i + 1 >= argc) continue; if (argv[i+1][0] == '-') continue; ++i; opts.mFunctionSearch = std::string(argv[i]); } else if (parser.check(i, "--list-names", 0)) { opts.mFunctionList = true; opts.mFunctionNamesOnly = true; } else if (parser.check(i, "--ast-print", 0)) { opts.mPrintAST = true; } else if (parser.check(i, "--re-print", 0)) { opts.mReprint = true; } else if (parser.check(i, "--reg-print", 0)) { opts.mAttribRegPrint = true; } else if (parser.check(i, "--try-compile", 0)) { opts.mInitCompile = true; if (i + 1 >= argc) continue; if (argv[i+1][0] == '-') continue; ++i; opts.mCompileFor = tryCompileStringToCompilation(argv[i]); } else if (parser.check(i, "--opt")) { ++i; opts.mOptLevel = optStringToLevel(argv[i]); } else if (arg == "-h" || arg == "-help" || arg == "--help") { usage(EXIT_SUCCESS); } else { OPENVDB_LOG_FATAL("\"" + arg + "\" is not a valid option"); usage(); } } else if (!arg.empty()) { // if mode has already been set, no more positional arguments are expected // (except for execute which takes in and out) if (opts.mMode != ProgOptions::Mode::Execute) { OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\""); usage(); } if (arg == "analyze") opts.mMode = ProgOptions::Analyze; else if (arg == "functions") opts.mMode = ProgOptions::Functions; if (opts.mMode == ProgOptions::Mode::Execute) { opts.mInitCompile = true; // execute positional argument setup if (opts.mInputVDBFile.empty()) { opts.mInputVDBFile = arg; } else if (opts.mOutputVDBFile.empty()) { opts.mOutputVDBFile = arg; } else { OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\""); usage(); } } else if (!opts.mInputVDBFile.empty() || !opts.mOutputVDBFile.empty()) { OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\""); usage(); } } else { usage(); } } if (opts.mVerbose) { axlog("OpenVDB AX " << openvdb::getLibraryVersionString() << '\n'); axlog("----------------\n"); axlog("Inputs\n"); axlog(" mode : " << modeString(opts.mMode)); if (opts.mMode == ProgOptions::Analyze) { axlog(" ("); if (opts.mPrintAST) axlog("|ast out"); if (opts.mReprint) axlog("|reprint out"); if (opts.mAttribRegPrint) axlog("|registry out"); if (opts.mInitCompile) axlog("|compilation"); axlog("|)"); } axlog('\n'); if (opts.mMode == ProgOptions::Execute) { axlog(" vdb in : \"" << opts.mInputVDBFile << "\"\n"); axlog(" vdb out : \"" << opts.mOutputVDBFile << "\"\n"); } if (opts.mMode == ProgOptions::Execute || opts.mMode == ProgOptions::Analyze) { axlog(" ax code : "); if (opts.mInputCode && !opts.mInputCode->empty()) { const bool containsnl = opts.mInputCode->find('\n') != std::string::npos; if (containsnl) axlog("\n "); // indent output const char* c = opts.mInputCode->c_str(); while (*c != '\0') { axlog(*c); if (*c == '\n') axlog(" "); ++c; } } else { axlog("\"\""); } axlog('\n'); axlog('\n'); } axlog(std::flush); } if (opts.mMode != ProgOptions::Functions) { if (!opts.mInputCode) { OPENVDB_LOG_FATAL("expected at least one AX file or a code snippet"); usage(); } if (multiSnippet) { OPENVDB_LOG_WARN("multiple code snippets provided, only using last input."); } } if (opts.mMode == ProgOptions::Execute) { if (opts.mInputVDBFile.empty()) { OPENVDB_LOG_FATAL("expected at least one VDB file or analysis mode"); usage(); } if (opts.mOutputVDBFile.empty()) { OPENVDB_LOG_WARN("no output VDB File specified - nothing will be written to disk"); } } axtimer(); axlog("[INFO] Initializing OpenVDB" << std::flush); ScopedInitialize initializer(argc, argv); axlog(": " << axtime() << '\n'); // read vdb file data for openvdb::GridPtrVecPtr grids; openvdb::MetaMap::Ptr meta; if (opts.mMode == ProgOptions::Execute) { openvdb::io::File file(opts.mInputVDBFile); try { axtimer(); axlog("[INFO] Reading VDB data" << (openvdb::io::Archive::isDelayedLoadingEnabled() ? " (delay-load)" : "") << std::flush); file.open(); grids = file.getGrids(); meta = file.getMetadata(); file.close(); axlog(": " << axtime() << '\n'); } catch (openvdb::Exception& e) { OPENVDB_LOG_ERROR(e.what() << " (" << opts.mInputVDBFile << ")"); return EXIT_FAILURE; } } if (opts.mInitCompile) { axtimer(); axlog("[INFO] Initializing AX/LLVM" << std::flush); initializer.initializeCompiler(); axlog(": " << axtime() << '\n'); } if (opts.mMode == ProgOptions::Functions) { if (opts.mFunctionList) { axlog("Querying available functions\n" << std::flush); assert(opts.mFunctionNamesOnly || initializer.isInitialized()); printFunctions(opts.mFunctionNamesOnly, opts.mFunctionSearch, std::cout); } return EXIT_SUCCESS; } // set up logger openvdb::ax::Logger logs([](const std::string& msg) { std::cerr << msg << std::endl; }, [](const std::string& msg) { std::cerr << msg << std::endl; }); logs.setMaxErrors(opts.mMaxErrors); logs.setWarningsAsErrors(opts.mWarningsAsErrors); logs.setPrintLines(true); logs.setNumberedOutput(true); // parse axtimer(); axlog("[INFO] Parsing input code" << std::flush); const openvdb::ax::ast::Tree::ConstPtr syntaxTree = openvdb::ax::ast::parse(opts.mInputCode->c_str(), logs); axlog(": " << axtime() << '\n'); if (!syntaxTree) { return EXIT_FAILURE; } if (opts.mMode == ProgOptions::Analyze) { axlog("[INFO] Running analysis options\n" << std::flush); if (opts.mPrintAST) { axlog("[INFO] | Printing AST\n" << std::flush); openvdb::ax::ast::print(*syntaxTree, true, std::cout); } if (opts.mReprint) { axlog("[INFO] | Reprinting code\n" << std::flush); openvdb::ax::ast::reprint(*syntaxTree, std::cout); } if (opts.mAttribRegPrint) { axlog("[INFO] | Printing Attribute Registry\n" << std::flush); const openvdb::ax::AttributeRegistry::ConstPtr reg = openvdb::ax::AttributeRegistry::create(*syntaxTree); reg->print(std::cout); std::cout << std::flush; } if (!opts.mInitCompile) { return EXIT_SUCCESS; } } assert(opts.mInitCompile); axtimer(); axlog("[INFO] Creating Compiler\n"); axlog("[INFO] | Optimization Level [" << optLevelToString(opts.mOptLevel) << "]\n" << std::flush); openvdb::ax::CompilerOptions compOpts; compOpts.mOptLevel = opts.mOptLevel; openvdb::ax::Compiler::Ptr compiler = openvdb::ax::Compiler::create(compOpts); openvdb::ax::CustomData::Ptr customData = openvdb::ax::CustomData::create(); axlog("[INFO] | " << axtime() << '\n' << std::flush); // Check what we need to compile for if performing execution if (opts.mMode == ProgOptions::Execute) { assert(meta); assert(grids); bool points = false; bool volumes = false; for (auto grid : *grids) { points |= grid->isType<openvdb::points::PointDataGrid>(); volumes |= !points; if (points && volumes) break; } if (points && volumes) opts.mCompileFor = ProgOptions::Compilation::All; else if (points) opts.mCompileFor = ProgOptions::Compilation::Points; else if (volumes) opts.mCompileFor = ProgOptions::Compilation::Volumes; } if (opts.mMode == ProgOptions::Analyze) { bool psuccess = true; if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Points) { axtimer(); axlog("[INFO] Compiling for VDB Points\n" << std::flush); try { compiler->compile<openvdb::ax::PointExecutable>(*syntaxTree, logs, customData); if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); psuccess = false; } } catch (std::exception& e) { psuccess = false; axlog("[INFO] Fatal error!\n"); OPENVDB_LOG_ERROR(e.what()); } const bool hasWarning = logs.hasWarning(); if (psuccess) { axlog("[INFO] | Compilation successful"); if (hasWarning) axlog(" with warning(s)\n"); } axlog("[INFO] | " << axtime() << '\n' << std::flush); } bool vsuccess = true; if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Volumes) { axtimer(); axlog("[INFO] Compiling for VDB Volumes\n" << std::flush); try { compiler->compile<openvdb::ax::VolumeExecutable>(*syntaxTree, logs, customData); if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); vsuccess = false; } } catch (std::exception& e) { vsuccess = false; axlog("[INFO] Fatal error!\n"); OPENVDB_LOG_ERROR(e.what()); } const bool hasWarning = logs.hasWarning(); if (vsuccess) { axlog("[INFO] | Compilation successful"); if (hasWarning) axlog(" with warning(s)\n"); } axlog("[INFO] | " << axtime() << '\n' << std::flush); } return ((vsuccess && psuccess) ? EXIT_SUCCESS : EXIT_FAILURE); } // Execute points if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Points) { axlog("[INFO] VDB PointDataGrids Found\n" << std::flush); openvdb::ax::PointExecutable::Ptr pointExe; axtimer(); try { axlog("[INFO] Compiling for VDB Points\n" << std::flush); pointExe = compiler->compile<openvdb::ax::PointExecutable>(*syntaxTree, logs, customData); } catch (std::exception& e) { OPENVDB_LOG_FATAL("Fatal error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } if (pointExe) { axlog("[INFO] | Compilation successful"); if (logs.hasWarning()) { axlog(" with warning(s)\n"); } } else { if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); } return EXIT_FAILURE; } axlog("[INFO] | " << axtime() << '\n' << std::flush); size_t total = 0, count = 1; if (opts.mVerbose) { for (auto grid : *grids) { if (!grid->isType<openvdb::points::PointDataGrid>()) continue; ++total; } } for (auto grid : *grids) { if (!grid->isType<openvdb::points::PointDataGrid>()) continue; openvdb::points::PointDataGrid::Ptr points = openvdb::gridPtrCast<openvdb::points::PointDataGrid>(grid); axtimer(); axlog("[INFO] Executing on \"" << points->getName() << "\" " << count << " of " << total << '\n' << std::flush); ++count; try { pointExe->execute(*points); if (openvdb::ax::ast::callsFunction(*syntaxTree, "deletepoint")) { openvdb::points::deleteFromGroup(points->tree(), "dead", false, false); } } catch (std::exception& e) { OPENVDB_LOG_FATAL("Execution error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } axlog("[INFO] | Execution success.\n"); axlog("[INFO] | " << axtime() << '\n' << std::flush); } } // Execute volumes if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Volumes) { axlog("[INFO] VDB Volumes Found\n" << std::flush); openvdb::ax::VolumeExecutable::Ptr volumeExe; try { axlog("[INFO] Compiling for VDB Points\n" << std::flush); volumeExe = compiler->compile<openvdb::ax::VolumeExecutable>(*syntaxTree, logs, customData); } catch (std::exception& e) { OPENVDB_LOG_FATAL("Fatal error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } if (volumeExe) { axlog("[INFO] | Compilation successful"); if (logs.hasWarning()) { axlog(" with warning(s)\n"); } } else { if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); } return EXIT_FAILURE; } axlog("[INFO] | " << axtime() << '\n' << std::flush); if (opts.mVerbose) { std::vector<const std::string*> names; axlog("[INFO] Executing using:\n"); for (auto grid : *grids) { if (grid->isType<openvdb::points::PointDataGrid>()) continue; axlog(" " << grid->getName() << '\n'); axlog(" " << grid->valueType() << '\n'); axlog(" " << grid->gridClassToString(grid->getGridClass()) << '\n'); } axlog(std::flush); } try { volumeExe->execute(*grids); } catch (std::exception& e) { OPENVDB_LOG_FATAL("Execution error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } axlog("[INFO] | Execution success.\n"); axlog("[INFO] | " << axtime() << '\n' << std::flush); } if (!opts.mOutputVDBFile.empty()) { axtimer(); axlog("[INFO] Writing results" << std::flush); openvdb::io::File out(opts.mOutputVDBFile); try { out.write(*grids, *meta); } catch (openvdb::Exception& e) { OPENVDB_LOG_ERROR(e.what() << " (" << out.filename() << ")"); return EXIT_FAILURE; } axlog("[INFO] | " << axtime() << '\n' << std::flush); } return EXIT_SUCCESS; }
27,537
C++
34.71725
128
0.525584
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionTypes.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/FunctionTypes.h /// /// @authors Nick Avramoussis /// /// @brief Contains frameworks for creating custom AX functions which can /// be registered within the FunctionRegistry and used during code /// generation. The intended and safest way to build a function is to /// use the FunctionBuilder struct with its addSignature methods. Note /// that the derived Function classes provided can also be subclassed /// for more granular control, however may be subject to more substantial /// API changes. /// /// @details There are a variety of different ways to build a function /// which are tailored towards different function types. The two currently /// supported function implementations are C Bindings and IR generation. /// Additionally, depending on the return type of the function, you may /// need to declare your function an SRET (structural return) function. /// /// C Bindings: /// As the name suggests, the CFunction class infrastructure provides /// the quickest and easiest way to bind to methods in your host /// application. The most important thing to consider when choosing /// this approach is performance. LLVM will have no knowledge of the /// function body during optimization passes. Depending on the /// implementation of your method and the user's usage from AX, C /// bindings may be subject to limited optimizations in comparison to /// IR functions. For example, a static function which is called from /// within a loop cannot be unrolled. See the CFunction templated /// class. /// /// IR Functions: /// IR Functions expect implementations to generate the body of the /// function directly into IR during code generation. This ensures /// optimal performance during optimization passes however can be /// trickier to design. Note that, in the future, AX functions will /// be internally supported to provide a better solution for /// IR generated functions. See the IRFunction templated class. /// /// SRET Functions: /// Both C Bindings and IR Functions can be marked as SRET methods. /// SRET methods, in AX, are any function which returns a value which /// is not a scalar (e.g. vectors, matrices). This follows the same /// optimization logic as clang which will rebuild function signatures /// with their return type as the first argument if the return type is /// greater than a given size. You should never attempt to return /// alloca's directly from functions (unless malloced). /// /// Some other things to consider: /// - Ensure C Binding dependencies have been correctly mapped. /// - Avoid calling B.CreateAlloca inside of IR functions - instead /// rely on the utility method insertStaticAlloca() where possible. /// - Ensure both floating point and integer argument signatures are /// provided if you wish to avoid floats truncating. /// - Array arguments (vectors/matrices) are always passed by pointer. /// Scalar arguments are always passed by copy. /// - Ensure array arguments which will not be modified are marked as /// readonly. Currently, only array arguments can be passed by /// "reference". /// - Ensure function bodies, return types and parameters and marked /// with desirable llvm attributes. /// #ifndef OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED #include "Types.h" #include "Utils.h" // isValidCast #include "ConstantFolding.h" #include <openvdb/version.h> #include <llvm/IR/Constants.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/Module.h> #include <algorithm> #include <functional> #include <memory> #include <stack> #include <type_traits> #include <unordered_map> #include <vector> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief Object to array conversion methods to allow functions to return /// vector types. These containers provided an interface for automatic /// conversion of C++ objects to LLVM types as array types. template <typename T, size_t _SIZE = 1> struct ArgType { using Type = T; static const size_t SIZE = _SIZE; using ArrayType = Type[SIZE]; ArrayType mData; }; template <typename T, size_t S> struct LLVMType<ArgType<T,S>> : public AliasTypeMap<ArgType<T,S>, T[S]> {}; using V2D = ArgType<double, 2>; using V2F = ArgType<float, 2>; using V2I = ArgType<int32_t, 2>; using V3D = ArgType<double, 3>; using V3F = ArgType<float, 3>; using V3I = ArgType<int32_t, 3>; using V4D = ArgType<double, 4>; using V4F = ArgType<float, 4>; using V4I = ArgType<int32_t, 4>; using M3D = ArgType<double, 9>; using M3F = ArgType<float, 9>; using M4D = ArgType<double, 16>; using M4F = ArgType<float, 16>; //////////////////////////////////////////////////////////////////////////////// /// @brief Type to symbol conversions - these characters are used to build each /// functions unique signature. They differ from standard AX or LLVM /// syntax to be as short as possible i.e. vec4d, [4 x double] = d4 template <typename T> struct TypeToSymbol { static inline std::string s() { return "?"; } }; template <> struct TypeToSymbol<void> { static inline std::string s() { return "v"; } }; template <> struct TypeToSymbol<char> { static inline std::string s() { return "c"; } }; template <> struct TypeToSymbol<int16_t> { static inline std::string s() { return "s"; } }; template <> struct TypeToSymbol<int32_t> { static inline std::string s() { return "i"; } }; template <> struct TypeToSymbol<int64_t> { static inline std::string s() { return "l"; } }; template <> struct TypeToSymbol<float> { static inline std::string s() { return "f"; } }; template <> struct TypeToSymbol<double> { static inline std::string s() { return "d"; } }; template <> struct TypeToSymbol<AXString> { static inline std::string s() { return "a"; } }; template <typename T> struct TypeToSymbol<T*> { static inline std::string s() { return TypeToSymbol<T>::s() + "*"; } }; template <typename T, size_t S> struct TypeToSymbol<T[S]> { static inline std::string s() { return TypeToSymbol<T>::s() + std::to_string(S); } }; template <typename T, size_t S> struct TypeToSymbol<ArgType<T,S>> : public TypeToSymbol<T[S]> {}; template <typename T> struct TypeToSymbol<math::Vec2<T>> : public TypeToSymbol<T[2]> {}; template <typename T> struct TypeToSymbol<math::Vec3<T>> : public TypeToSymbol<T[3]> {}; template <typename T> struct TypeToSymbol<math::Vec4<T>> : public TypeToSymbol<T[4]> {}; template <typename T> struct TypeToSymbol<math::Mat3<T>> : public TypeToSymbol<T[9]> {}; template <typename T> struct TypeToSymbol<math::Mat4<T>> : public TypeToSymbol<T[16]> {}; template <typename T> struct TypeToSymbol<const T> : public TypeToSymbol<T> {}; template <typename T> struct TypeToSymbol<const T*> : public TypeToSymbol<T*> {}; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief Templated argument iterator which implements various small functions /// per argument type, resolved at compile time. /// template <typename SignatureT, size_t I = FunctionTraits<SignatureT>::N_ARGS> struct ArgumentIterator { using ArgT = typename FunctionTraits<SignatureT>::template Arg<I-1>; using ArgumentValueType = typename ArgT::Type; template <typename OpT> static void apply(const OpT& op, const bool forwards) { if (forwards) { ArgumentIterator<SignatureT, I-1>::apply(op, forwards); op(ArgumentValueType()); } else { op(ArgumentValueType()); ArgumentIterator<SignatureT, I-1>::apply(op, forwards); } } }; template <typename SignatureT> struct ArgumentIterator<SignatureT, 0> { template <typename OpT> static void apply(const OpT&, const bool) {} }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief Populate a vector of llvm types from a function signature declaration. /// /// @param C The llvm context /// @param types A vector of types to populate /// template <typename SignatureT> inline llvm::Type* llvmTypesFromSignature(llvm::LLVMContext& C, std::vector<llvm::Type*>* types = nullptr) { using Traits = FunctionTraits<SignatureT>; using ArgumentIteratorT = ArgumentIterator<SignatureT, Traits::N_ARGS>; if (types) { types->reserve(Traits::N_ARGS); auto callback = [&types, &C](auto type) { using Type = decltype(type); types->emplace_back(LLVMType<Type>::get(C)); }; ArgumentIteratorT::apply(callback, /*forwards*/true); } return LLVMType<typename Traits::ReturnType>::get(C); } /// @brief Generate an LLVM FunctionType from a function signature /// /// @param C The llvm context /// template <typename SignatureT> inline llvm::FunctionType* llvmFunctionTypeFromSignature(llvm::LLVMContext& C) { std::vector<llvm::Type*> types; llvm::Type* returnType = llvmTypesFromSignature<SignatureT>(C, &types); return llvm::FunctionType::get(/*Result=*/returnType, /*Params=*/llvm::ArrayRef<llvm::Type*>(types), /*isVarArg=*/false); } /// @brief Print a function signature to the provided ostream. /// /// @param os The stream to print to /// @param types The function argument types /// @param returnType The return type of the function. Must not be a nullptr /// @param name The name of the function. If not provided, the return type /// neighbours the first parenthesis /// @param names Names of the function parameters. If a name is nullptr, it /// skipped /// @param axTypes Whether to try and convert the llvm::Types provided to /// AX types. If false, the llvm types are used. void printSignature(std::ostream& os, const std::vector<llvm::Type*>& types, const llvm::Type* returnType, const char* name = nullptr, const std::vector<const char*>& names = {}, const bool axTypes = false); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief The base/abstract representation of an AX function. Derived classes /// must implement the Function::types call to describe their signature. struct Function { using Ptr = std::shared_ptr<Function>; Function(const size_t size, const std::string& symbol) : mSize(size) , mSymbol(symbol) , mAttributes(nullptr) , mNames() , mDeps() { // symbol must be a valid string assert(!symbol.empty()); } virtual ~Function() = default; /// @brief Populate a vector of llvm::Types which describe this function /// signature. This method is used by Function::create, /// Function::print and Function::match. virtual llvm::Type* types(std::vector<llvm::Type*>&, llvm::LLVMContext&) const = 0; /// @brief Converts and creates this AX function into a llvm Function. /// @details This method uses the result from Function::types() to construct /// a llvm::FunctionType and a subsequent a llvm::Function. Any /// parameter, return or function attributes are also added to the /// function. If a module is provided, the module if first checked /// to see if the function already exists. If it does, it is /// immediately returned. If the function doesn't exist in the /// module, its prototype is created and also inserted into the end /// of the modules function list. If no module is provided, the /// function is left detached and must be added to a valid Module /// to be callable. /// @note The body of the function is left to derived classes to /// implement. As you need a Module to generate the prototype/body, /// this function serves two purposes. The first is to return the /// detached function signature if only a context is provided. /// The second is to ensure the function prototype and body (if /// required) is inserted into the module prior to returning. /// @note It is possible to end up with function symbol collisions if you /// do not have unique function symbols in your module /// /// @param C The LLVM Context /// @param M The Module to write the function to virtual llvm::Function* create(llvm::LLVMContext& C, llvm::Module* M = nullptr) const; /// @brief Convenience method which always uses the provided module to find /// the function or insert it if necessary. /// @param M The llvm::Module to use llvm::Function* create(llvm::Module& M) const { return this->create(M.getContext(), &M); } /// @brief Uses the IRBuilder to create a call to this function with the /// given arguments, creating the function and inserting it into the /// IRBuilder's Module if necessary (through Function::create). /// @note The IRBuilder must have a valid llvm Module/Function/Block /// attached /// @note If the number of provided arguments do not match the size of the /// current function, invalid IR will be generated. /// @note If the provided argument types do not match the current function /// and cast is false, invalid IR will be generated. Additionally, /// invalid IR will be generated if cast is true but no valid cast /// exists for a given argument. /// @note When casting arguments, the readonly flags of the function are /// not checked (unlike Function::match). Casting an argument will /// cause a new copy of the argument to be created and passed to the /// function. These new values do not propagate back any changes to /// the original argument. Separate functions for all writable /// argument types must be created. /// /// @param args The llvm Value arguments to call this function with /// @param B The llvm IRBuilder /// @param cast Whether to allow implicit casting of arguments virtual llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast = false) const; /// @brief The result type from calls to Function::match enum SignatureMatch { None = 0, Size, Implicit, Explicit }; /// @brief The base implementation for determining how a vector of llvm /// arguments translates to this functions signature. Returns an /// enum which represents the available mapping. /// @details This method calls types() to figure out the function signature, /// then compares each argument type to the type in the input /// vector. If the types match exactly, an Explicit match is found. /// If the sizes of the inputs and signature differ, no match is /// found and None is returned. If however, the sizes match and /// there exists a valid implicit cast from the input type to the /// signature type for every input, an Implicit match is returned. /// Finally, if the sizes match but there is no implicit cast /// mapping, Size is returned. /// i8 -> i32 : Implicit /// i32 -> i32 : Explicit /// str -> i32 : Size /// (i32,i32) -> i32 : None /// @note Due to the way CFunctionSRet is implemented, the LLVM Context /// must be provided in case we have a zero arg function signature /// with a SRET. /// @param inputs The input types /// @param C The LLVM Context virtual SignatureMatch match(const std::vector<llvm::Type*>& inputs, llvm::LLVMContext& C) const; /// @brief The number of arguments that this function has inline size_t size() const { return mSize; } /// @brief The function symbol name. /// @details This will be used as its identifier in IR and must be unique. inline const char* symbol() const { return mSymbol.c_str(); } /// @brief Returns the descriptive name of the given argument index /// @details If the index is greater than the number of arguments, an empty /// string is returned. /// /// @param idx The index of the argument inline const char* argName(const size_t idx) const { return idx < mNames.size() ? mNames[idx] : ""; } /// @brief Print this function's signature to the provided ostream. /// @details This is intended to return a descriptive front end user string /// rather than the function's IR representation. This function is /// virtual so that derived classes can customize how they present /// frontend information. /// @sa printSignature /// /// @param C The llvm context /// @param os The ostream to print to /// @param name The name to insert into the description. /// @param axTypes Whether to print llvm IR or AX Types. virtual void print(llvm::LLVMContext& C, std::ostream& os, const char* name = nullptr, const bool axTypes = true) const; /// Builder methods inline bool hasParamAttribute(const size_t i, const llvm::Attribute::AttrKind& kind) const { if (!mAttributes) return false; const auto iter = mAttributes->mParamAttrs.find(i); if (iter == mAttributes->mParamAttrs.end()) return false; const auto& vec = iter->second; return std::find(vec.begin(), vec.end(), kind) != vec.end(); } inline void setArgumentNames(std::vector<const char*> names) { mNames = names; } const std::vector<const char*>& dependencies() const { return mDeps; } inline void setDependencies(std::vector<const char*> deps) { mDeps = deps; } inline void setFnAttributes(const std::vector<llvm::Attribute::AttrKind>& in) { this->attrs().mFnAttrs = in; } inline void setRetAttributes(const std::vector<llvm::Attribute::AttrKind>& in) { this->attrs().mRetAttrs = in; } inline void setParamAttributes(const size_t i, const std::vector<llvm::Attribute::AttrKind>& in) { this->attrs().mParamAttrs[i] = in; } protected: /// @brief Cast the provided arguments to the given type as supported by /// implicit casting of function types. If the types already match /// OR if a cast cannot be performed, nothing is done to the argument. /// @todo This should really be generalized out for Function::call and /// Function::match to both use. However, due to SRET functions, /// this logic must be performed somewhere in the Function class /// hierarchy and not in FunctionGroup static void cast(std::vector<llvm::Value*>& args, const std::vector<llvm::Type*>& types, llvm::IRBuilder<>& B); private: struct Attributes { std::vector<llvm::Attribute::AttrKind> mFnAttrs, mRetAttrs; std::map<size_t, std::vector<llvm::Attribute::AttrKind>> mParamAttrs; }; inline Attributes& attrs() { if (!mAttributes) mAttributes.reset(new Attributes()); return *mAttributes; } llvm::AttributeList flattenAttrs(llvm::LLVMContext& C) const; const size_t mSize; const std::string mSymbol; std::unique_ptr<Attributes> mAttributes; std::vector<const char*> mNames; std::vector<const char*> mDeps; }; /// @brief Templated interface class for SRET functions. This struct provides /// the interface for functions that wish to return arrays (vectors or /// matrices) by internally remapping the first argument for the user. /// As far as LLVM and any bindings are concerned, the function /// signature remains unchanged - however the first argument becomes /// "invisible" to the user and is instead allocated by LLVM before the /// function is executed. Importantly, the argument has no impact on /// the user facing AX signature and doesn't affect declaration selection. /// @note This class is not intended to be instantiated directly, but instead /// used by derived implementation which hold a valid implementations /// of member functions required to create a llvm::Function (such as /// Function::types and Function::call). This exists as an interface to /// avoid virtual inheritance. /// template <typename SignatureT, typename DerivedFunction> struct SRetFunction : public DerivedFunction { using Ptr = std::shared_ptr<SRetFunction<SignatureT, DerivedFunction>>; using Traits = FunctionTraits<SignatureT>; // check there actually are arguments static_assert(Traits::N_ARGS > 0, "SRET Function object has been setup with the first argument as the return " "value, however the provided signature is empty."); // check no return value exists static_assert(std::is_same<typename Traits::ReturnType, void>::value, "SRET Function object has been setup with the first argument as the return " "value and a non void return type."); private: using FirstArgument = typename Traits::template Arg<0>::Type; static_assert(std::is_pointer<FirstArgument>::value, "SRET Function object has been setup with the first argument as the return " "value, but this argument it is not a pointer type."); using SRetType = typename std::remove_pointer<FirstArgument>::type; public: /// @brief Override of match which inserts the SRET type such that the base /// class methods ignore it. Function::SignatureMatch match(const std::vector<llvm::Type*>& args, llvm::LLVMContext& C) const override { // append return type and right rotate std::vector<llvm::Type*> inputs(args); inputs.emplace_back(LLVMType<SRetType*>::get(C)); std::rotate(inputs.rbegin(), inputs.rbegin() + 1, inputs.rend()); return DerivedFunction::match(inputs, C); } /// @brief Override of call which allocates the required SRET llvm::Value /// for this function. /// @note Unlike other function where the returned llvm::Value* is a /// llvm::CallInst (which also represents the return value), /// SRET functions return the allocated 1st argument i.e. not a /// llvm::CallInst llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const override { // append return value and right rotate std::vector<llvm::Value*> inputs(args); llvm::Type* sret = LLVMType<SRetType>::get(B.getContext()); inputs.emplace_back(insertStaticAlloca(B, sret)); std::rotate(inputs.rbegin(), inputs.rbegin() + 1, inputs.rend()); DerivedFunction::call(inputs, B, cast); return inputs.front(); } /// @brief Override of print to avoid printing out the SRET type void print(llvm::LLVMContext& C, std::ostream& os, const char* name = nullptr, const bool axTypes = true) const override { std::vector<llvm::Type*> current; llvm::Type* ret = this->types(current, C); // left rotate std::rotate(current.begin(), current.begin() + 1, current.end()); ret = current.back(); current.pop_back(); std::vector<const char*> names; names.reserve(this->size()); for (size_t i = 0; i < this->size()-1; ++i) { names.emplace_back(this->argName(i)); } printSignature(os, current, ret, name, names, axTypes); } protected: /// @brief Forward all arguments to the derived class template <typename ...Args> SRetFunction(Args&&... ts) : DerivedFunction(ts...) {} }; /// @brief The base class for all C bindings. struct CFunctionBase : public Function { using Ptr = std::shared_ptr<CFunctionBase>; ~CFunctionBase() override = default; /// @brief Returns the global address of this function. /// @note This is only required for C bindings. virtual uint64_t address() const = 0; inline void setConstantFold(bool on) { mConstantFold = on; } inline bool hasConstantFold() const { return mConstantFold; } inline virtual llvm::Value* fold(const std::vector<llvm::Value*>&, llvm::LLVMContext&) const { return nullptr; } protected: CFunctionBase(const size_t size, const std::string& symbol) : Function(size, symbol) , mConstantFold(false) {} private: bool mConstantFold; }; /// @brief Represents a concrete C function binding. /// /// @note This struct is templated on the signature to allow for evaluation of /// the arguments to llvm types from any llvm context. /// template <typename SignatureT> struct CFunction : public CFunctionBase { using CFunctionT = CFunction<SignatureT>; using Ptr = std::shared_ptr<CFunctionT>; using Traits = FunctionTraits<SignatureT>; // Assert that the return argument is not a pointer. Note that this is // relaxed for IR functions where it's allowed if the function is embedded. static_assert(!std::is_pointer<typename Traits::ReturnType>::value, "CFunction object has been setup with a pointer return argument. C bindings " "cannot return memory locations to LLVM - Consider using a CFunctionSRet."); CFunction(const std::string& symbol, const SignatureT function) : CFunctionBase(Traits::N_ARGS, symbol) , mFunction(function) {} ~CFunction() override = default; inline llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override { return llvmTypesFromSignature<SignatureT>(C, &types); } inline uint64_t address() const override final { return reinterpret_cast<uint64_t>(mFunction); } llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const override { llvm::Value* result = this->fold(args, B.getContext()); if (result) return result; return Function::call(args, B, cast); } llvm::Value* fold(const std::vector<llvm::Value*>& args, llvm::LLVMContext& C) const override final { auto allconst = [](const std::vector<llvm::Value*>& vals) -> bool { for (auto& value : vals) { if (!llvm::isa<llvm::Constant>(value)) return false; } return true; }; if (!this->hasConstantFold()) return nullptr; if (!allconst(args)) return nullptr; std::vector<llvm::Constant*> constants; constants.reserve(args.size()); for (auto& value : args) { constants.emplace_back(llvm::cast<llvm::Constant>(value)); } // no guarantee that fold() will be able to cast all arguments return ConstantFolder<SignatureT>::fold(constants, *mFunction, C); } private: const SignatureT* mFunction; }; /// @brief The base/abstract definition for an IR function. struct IRFunctionBase : public Function { using Ptr = std::shared_ptr<IRFunctionBase>; /// @brief The IR callback function which will write the LLVM IR for this /// function's body. /// @details The first argument is the vector of functional arguments. i.e. /// a representation of the value that the callback has been invoked /// with. /// The last argument is the IR builder which should be used to /// generate the function body IR. /// @note You can return a nullptr from this method which will represent /// a ret void, a ret void instruction, or an actual value using GeneratorCb = std::function<llvm::Value* (const std::vector<llvm::Value*>&, llvm::IRBuilder<>&)>; llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override = 0; /// @brief Enable or disable the embedding of IR. Embedded IR is currently /// required for function which use parent function parameters. inline void setEmbedIR(bool on) { mEmbedIR = on; } inline bool hasEmbedIR() const { return mEmbedIR; } /// @brief Override for the creation of an IR function. This ensures that /// the body and prototype of the function are generated if a Module /// is provided. /// @note A nullptr is returned if mEmbedIR is true and no action is /// performed. /// @note Throws if this function has been initialized with a nullptr /// generator callback. In this case, the function prototype will /// be created, but not the function body. /// @note Throws if the return type of the generator callback does not /// match the function prototype. In this case, both the prototype /// and the function body will be created and inserted, but the IR /// will be invalid. llvm::Function* create(llvm::LLVMContext& C, llvm::Module* M) const override; /// @brief Override for call, which is only necessary if mEmbedIR is true, /// as the IR generation for embedded functions is delayed until /// the function is called. If mEmbedIR is false, this simply calls /// Function::call llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const override; protected: // @todo This should ideally live in FunctionGroup::execute, but the return // type is allowed to differ for sret C bindings. inline void verifyResultType(const llvm::Type* result, const llvm::Type* expected) const { if (result == expected) return; std::string source, target; if (result) llvmTypeToString(result, source); llvmTypeToString(expected, target); OPENVDB_THROW(AXCodeGenError, "Function \"" + std::string(this->symbol()) + "\" has been invoked with a mismatching return type. Expected: \"" + target + "\", got \"" + source + "\"."); } IRFunctionBase(const std::string& symbol, const GeneratorCb& gen, const size_t size) : Function(size, symbol) , mGen(gen) , mEmbedIR(false) {} ~IRFunctionBase() override = default; const GeneratorCb mGen; bool mEmbedIR; }; /// @brief Represents a concrete IR function. template <typename SignatureT> struct IRFunction : public IRFunctionBase { using Traits = FunctionTraits<SignatureT>; using Ptr = std::shared_ptr<IRFunction>; IRFunction(const std::string& symbol, const GeneratorCb& gen) : IRFunctionBase(symbol, gen, Traits::N_ARGS) {} inline llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override { return llvmTypesFromSignature<SignatureT>(C, &types); } }; /// @brief Represents a concrete C function binding with the first argument as /// its return type. template <typename SignatureT> struct CFunctionSRet : public SRetFunction<SignatureT, CFunction<SignatureT>> { using BaseT = SRetFunction<SignatureT, CFunction<SignatureT>>; CFunctionSRet(const std::string& symbol, const SignatureT function) : BaseT(symbol, function) {} ~CFunctionSRet() override = default; }; /// @brief Represents a concrete IR function with the first argument as /// its return type. template <typename SignatureT> struct IRFunctionSRet : public SRetFunction<SignatureT, IRFunction<SignatureT>> { using BaseT = SRetFunction<SignatureT, IRFunction<SignatureT>>; IRFunctionSRet(const std::string& symbol, const IRFunctionBase::GeneratorCb& gen) : BaseT(symbol, gen) {} ~IRFunctionSRet() override = default; }; /// @brief todo struct FunctionGroup { using Ptr = std::shared_ptr<FunctionGroup>; using UniquePtr = std::unique_ptr<FunctionGroup>; using FunctionList = std::vector<Function::Ptr>; FunctionGroup(const char* name, const char* doc, const FunctionList& list) : mName(name) , mDoc(doc) , mFunctionList(list) {} ~FunctionGroup() = default; /// @brief Given a vector of llvm types, automatically returns the best /// possible function declaration from the stored function list. The /// 'best' declaration is determined by the provided types /// compatibility to each functions signature. /// @note If multiple implicit matches are found, the first match is /// returned. /// @note Returns a nullptr if no compatible match was found or if the /// function list is empty. A compatible match is defined as an /// Explicit or Implicit match. /// /// @param types A vector of types representing the function argument types /// @param C The llvm context /// @param type If provided, type is set to the type of match that occurred /// Function::Ptr match(const std::vector<llvm::Type*>& types, llvm::LLVMContext& C, Function::SignatureMatch* type = nullptr) const; /// @brief Given a vector of llvm values provided by the user, find the /// best possible function signature, generate and execute the /// function body. Returns the return value of the function (can be /// void). /// @note This function will throw if not compatible match is found or if /// no valid return is provided by the matched declarations /// implementation. /// /// @param args A vector of values representing the function arguments /// @param B The current llvm IRBuilder /// llvm::Value* execute(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) const; /// @brief Accessor to the underlying function signature list /// inline const FunctionList& list() const { return mFunctionList; } const char* name() const { return mName; } const char* doc() const { return mDoc; } private: const char* mName; const char* mDoc; const FunctionList mFunctionList; }; /// @brief The FunctionBuilder class provides a builder pattern framework to /// allow easy and valid construction of AX functions. There are a /// number of complex tasks which may need to be performed during /// construction of C or IR function which are delegated to this /// builder, whilst ensuring that the constructed functions are /// guaranteed to be valid. /// @details Use the FunctionBuilder::addSignature methods to append function /// signatures. Finalize the group of functions with /// FunctionBuilder::get. struct FunctionBuilder { enum DeclPreferrence { C, IR, Any }; struct Settings { using Ptr = std::shared_ptr<Settings>; inline bool isDefault() const { if (mNames) return false; if (!mDeps.empty()) return false; if (mConstantFold || mEmbedIR) return false; if (!mFnAttrs.empty()) return false; if (!mRetAttrs.empty()) return false; if (!mParamAttrs.empty()) return false; return true; } std::shared_ptr<std::vector<const char*>> mNames = nullptr; std::vector<const char*> mDeps = {}; bool mConstantFold = false; bool mEmbedIR = false; std::vector<llvm::Attribute::AttrKind> mFnAttrs = {}; std::vector<llvm::Attribute::AttrKind> mRetAttrs = {}; std::map<size_t, std::vector<llvm::Attribute::AttrKind>> mParamAttrs = {}; }; FunctionBuilder(const char* name) : mName(name) , mCurrentSettings(new Settings()) {} template <typename Signature, bool SRet = false> inline FunctionBuilder& addSignature(const IRFunctionBase::GeneratorCb& cb, const char* symbol = nullptr) { using IRFType = typename std::conditional <!SRet, IRFunction<Signature>, IRFunctionSRet<Signature>>::type; using IRPtr = typename IRFType::Ptr; Settings::Ptr settings = mCurrentSettings; if (!mCurrentSettings->isDefault()) { settings.reset(new Settings()); } std::string s; if (symbol) s = std::string(symbol); else s = this->genSymbol<Signature>(); auto ir = IRPtr(new IRFType(s, cb)); mIRFunctions.emplace_back(ir); mSettings[ir.get()] = settings; mCurrentSettings = settings; return *this; } template <typename Signature, bool SRet = false> inline FunctionBuilder& addSignature(const Signature* ptr, const char* symbol = nullptr) { using CFType = typename std::conditional <!SRet, CFunction<Signature>, CFunctionSRet<Signature>>::type; using CPtr = typename CFType::Ptr; Settings::Ptr settings = mCurrentSettings; if (!mCurrentSettings->isDefault()) { settings.reset(new Settings()); } std::string s; if (symbol) s = std::string(symbol); else s = this->genSymbol<Signature>(); auto c = CPtr(new CFType(s, ptr)); mCFunctions.emplace_back(c); mSettings[c.get()] = settings; mCurrentSettings = settings; return *this; } template <typename Signature, bool SRet = false> inline FunctionBuilder& addSignature(const IRFunctionBase::GeneratorCb& cb, const Signature* ptr, const char* symbol = nullptr) { this->addSignature<Signature, SRet>(cb, symbol); this->addSignature<Signature, SRet>(ptr, symbol); return *this; } inline FunctionBuilder& addDependency(const char* name) { mCurrentSettings->mDeps.emplace_back(name); return *this; } inline FunctionBuilder& setEmbedIR(bool on) { mCurrentSettings->mEmbedIR = on; return *this; } inline FunctionBuilder& setConstantFold(bool on) { mCurrentSettings->mConstantFold = on; return *this; } inline FunctionBuilder& setArgumentNames(const std::vector<const char*>& names) { mCurrentSettings->mNames.reset(new std::vector<const char*>(names)); return *this; } /// @details Parameter and Function Attributes. When designing a C binding, /// llvm will be unable to assign parameter markings to the return /// type, function body or parameter attributes due to there not /// being any visibility on the function itself during codegen. /// The best way to ensure performant C bindings is to ensure /// that the function is marked with the required llvm parameters. /// Some of the heavy hitters (which can have the most impact) /// are below: /// /// Functions: /// - norecurse /// This function attribute indicates that the function does /// not call itself either directly or indirectly down any /// possible call path. /// /// - willreturn /// This function attribute indicates that a call of this /// function will either exhibit undefined behavior or comes /// back and continues execution at a point in the existing /// call stack that includes the current invocation. /// /// - nounwind /// This function attribute indicates that the function never /// raises an exception. /// /// - readnone /// On a function, this attribute indicates that the function /// computes its result (or decides to unwind an exception) based /// strictly on its arguments, without dereferencing any pointer /// arguments or otherwise accessing any mutable state (e.g. memory, /// control registers, etc) visible to caller functions. /// /// - readonly /// On a function, this attribute indicates that the function /// does not write through any pointer arguments (including byval /// arguments) or otherwise modify any state (e.g. memory, control /// registers, etc) visible to caller functions. /// control registers, etc) visible to caller functions. /// /// - writeonly /// On a function, this attribute indicates that the function may /// write to but does not read from memory. /// /// Parameters: /// - noalias /// This indicates that objects accessed via pointer values based /// on the argument or return value are not also accessed, during /// the execution of the function, via pointer values not based on /// the argument or return value. /// /// - nonnull /// This indicates that the parameter or return pointer is not null. /// /// - readonly /// Indicates that the function does not write through this pointer /// argument, even though it may write to the memory that the pointer /// points to. /// /// - writeonly /// Indicates that the function may write to but does not read through /// this pointer argument (even though it may read from the memory /// that the pointer points to). /// inline FunctionBuilder& addParameterAttribute(const size_t idx, const llvm::Attribute::AttrKind attr) { mCurrentSettings->mParamAttrs[idx].emplace_back(attr); return *this; } inline FunctionBuilder& addReturnAttribute(const llvm::Attribute::AttrKind attr) { mCurrentSettings->mRetAttrs.emplace_back(attr); return *this; } inline FunctionBuilder& addFunctionAttribute(const llvm::Attribute::AttrKind attr) { mCurrentSettings->mFnAttrs.emplace_back(attr); return *this; } inline FunctionBuilder& setDocumentation(const char* doc) { mDoc = doc; return *this; } inline FunctionBuilder& setPreferredImpl(DeclPreferrence pref) { mDeclPref = pref; return *this; } inline FunctionGroup::UniquePtr get() const { for (auto& decl : mCFunctions) { const auto& s = mSettings.at(decl.get()); decl->setDependencies(s->mDeps); decl->setConstantFold(s->mConstantFold); if (!s->mFnAttrs.empty()) decl->setFnAttributes(s->mFnAttrs); if (!s->mRetAttrs.empty()) decl->setRetAttributes(s->mRetAttrs); if (!s->mParamAttrs.empty()) { for (auto& idxAttrs : s->mParamAttrs) { if (idxAttrs.first > decl->size()) continue; decl->setParamAttributes(idxAttrs.first, idxAttrs.second); } } if (s->mNames) decl->setArgumentNames(*s->mNames); } for (auto& decl : mIRFunctions) { const auto& s = mSettings.at(decl.get()); decl->setDependencies(s->mDeps); decl->setEmbedIR(s->mEmbedIR); if (!s->mFnAttrs.empty()) decl->setFnAttributes(s->mFnAttrs); if (!s->mRetAttrs.empty()) decl->setRetAttributes(s->mRetAttrs); if (!s->mParamAttrs.empty()) { for (auto& idxAttrs : s->mParamAttrs) { if (idxAttrs.first > decl->size()) continue; decl->setParamAttributes(idxAttrs.first, idxAttrs.second); } } if (s->mNames) decl->setArgumentNames(*s->mNames); } std::vector<Function::Ptr> functions; if (mDeclPref == DeclPreferrence::IR) { functions.insert(functions.end(), mIRFunctions.begin(), mIRFunctions.end()); } if (mDeclPref == DeclPreferrence::C) { functions.insert(functions.end(), mCFunctions.begin(), mCFunctions.end()); } if (functions.empty()) { functions.insert(functions.end(), mIRFunctions.begin(), mIRFunctions.end()); functions.insert(functions.end(), mCFunctions.begin(), mCFunctions.end()); } FunctionGroup::UniquePtr group(new FunctionGroup(mName, mDoc, functions)); return group; } private: template <typename Signature> std::string genSymbol() const { using Traits = FunctionTraits<Signature>; std::string args; auto callback = [&args](auto type) { using Type = decltype(type); args += TypeToSymbol<Type>::s(); }; ArgumentIterator<Signature>::apply(callback, /*forwards*/true); /// @note important to prefix all symbols with "ax." so that /// they will never conflict with internal llvm symbol /// names (such as standard library methods e.g, cos, cosh // assemble the symbol return "ax." + std::string(this->mName) + "." + TypeToSymbol<typename Traits::ReturnType>::s() + args; } const char* mName = ""; const char* mDoc = ""; DeclPreferrence mDeclPref = IR; std::vector<CFunctionBase::Ptr> mCFunctions = {}; std::vector<IRFunctionBase::Ptr> mIRFunctions = {}; std::map<const Function*, Settings::Ptr> mSettings = {}; Settings::Ptr mCurrentSettings = nullptr; }; } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED
46,940
C
40.799644
108
0.623647
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointComputeGenerator.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/PointComputeGenerator.h /// /// @authors Nick Avramoussis, Matt Warner, Francisco Gochez, Richard Jones /// /// @brief The visitor framework and function definition for point data /// grid code generation /// #ifndef OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #define OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #include "ComputeGenerator.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../compiler/AttributeRegistry.h" #include <openvdb/version.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief The function definition and signature which is built by the /// PointComputeGenerator. /// /// The argument structure is as follows: /// /// 1) - A void pointer to the CustomData /// 2) - A void pointer to the leaf AttributeSet /// 3) - An unsigned integer, representing the leaf relative point /// id being executed /// 4) - A void pointer to a vector of void pointers, representing an /// array of attribute handles /// 5) - A void pointer to a vector of void pointers, representing an /// array of group handles /// 6) - A void pointer to a LeafLocalData object, used to track newly /// initialized attributes and arrays /// struct PointKernel { /// The signature of the generated function using Signature = void(const void* const, const void* const, uint64_t, void**, void**, void*); using FunctionTraitsT = codegen::FunctionTraits<Signature>; static const size_t N_ARGS = FunctionTraitsT::N_ARGS; /// The argument key names available during code generation static const std::array<std::string, N_ARGS>& argumentKeys(); static std::string getDefaultName(); }; /// @brief An additonal function built by the PointComputeGenerator. /// Currently both compute and compute range functions have the same /// signature struct PointRangeKernel : public PointKernel { static std::string getDefaultName(); }; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// namespace codegen_internal { /// @brief Visitor object which will generate llvm IR for a syntax tree which has been generated from /// AX that targets point grids. The IR will represent 2 functions : one that executes over /// single points and one that executes over a collection of points. This is primarily used by the /// Compiler class. struct PointComputeGenerator : public ComputeGenerator { /// @brief Constructor /// @param module llvm Module for generating IR /// @param options Options for the function registry behaviour /// @param functionRegistry Function registry object which will be used when generating IR /// for function calls /// @param logger Logger for collecting logical errors and warnings PointComputeGenerator(llvm::Module& module, const FunctionOptions& options, FunctionRegistry& functionRegistry, Logger& logger); ~PointComputeGenerator() override = default; using ComputeGenerator::traverse; using ComputeGenerator::visit; AttributeRegistry::Ptr generate(const ast::Tree& node); bool visit(const ast::Attribute*) override; private: llvm::Value* attributeHandleFromToken(const std::string&); void getAttributeValue(const std::string& globalName, llvm::Value* location); }; } // namespace namespace codegen_internal } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
4,032
C
32.890756
106
0.653522
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Utils.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/Utils.h /// /// @authors Nick Avramoussis /// /// @brief Utility code generation methods for performing various llvm /// operations /// #ifndef OPENVDB_AX_CODEGEN_UTILS_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_UTILS_HAS_BEEN_INCLUDED #include "Types.h" #include "../ast/Tokens.h" #include "../Exceptions.h" #include <openvdb/version.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> // Note: As of LLVM 5.0, the llvm::Type::dump() method isn't being // picked up correctly by the linker. dump() is internally implemented // using Type::print(llvm::errs()) which is being used in place. See: // // https://stackoverflow.com/questions/43723127/llvm-5-0-makefile-undefined-reference-fail // #include <llvm/Support/raw_ostream.h> // llvm::errs() namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @note Function definitions for some types returned from automatic token to /// llvm IR operations. See llvmArithmeticConversion and llvmBianryConversion using CastFunction = std::function<llvm::Value* (llvm::IRBuilder<>&, llvm::Value*, llvm::Type*)>; using BinaryFunction = std::function<llvm::Value* (llvm::IRBuilder<>&, llvm::Value*, llvm::Value*)>; /// @brief Populate a vector of llvm Types from a vector of llvm values /// /// @param values A vector of llvm values to retrieve types from /// @param types A vector of llvm types to populate /// inline void valuesToTypes(const std::vector<llvm::Value*>& values, std::vector<llvm::Type*>& types) { types.reserve(values.size()); for (const auto& v : values) { types.emplace_back(v->getType()); } } /// @brief Prints an llvm type to a std string /// /// @param type The llvm type to convert /// @param str The string to store the type info to /// inline void llvmTypeToString(const llvm::Type* const type, std::string& str) { llvm::raw_string_ostream os(str); type->print(os); os.flush(); } /// @brief Return the base llvm value which is being pointed to through /// any number of layered pointers. /// @note This function does not check for cyclical pointer dependencies /// /// @param type A llvm pointer type to traverse /// inline llvm::Type* getBaseContainedType(llvm::Type* const type) { llvm::Type* elementType = type; while (elementType->isPointerTy()) { elementType = elementType->getContainedType(0); } return elementType; } /// @brief Return an llvm value representing a pointer to the provided ptr builtin /// ValueT. /// @note This is probably not a suitable solution for anything other than POD /// types and should be used with caution. /// /// @param ptr A pointer to a type of ValueT whose address will be computed and /// returned /// @param builder The current llvm IRBuilder /// template <typename ValueT> inline llvm::Value* llvmPointerFromAddress(const ValueT* const& ptr, llvm::IRBuilder<>& builder) { llvm::Value* address = llvm::ConstantInt::get(llvm::Type::getIntNTy(builder.getContext(), sizeof(uintptr_t)*8), reinterpret_cast<uintptr_t>(ptr)); return builder.CreateIntToPtr(address, LLVMType<ValueT*>::get(builder.getContext())); } /// @brief Insert a stack allocation at the beginning of the current function /// of the provided type and size. The IRBuilder's insertion point must /// be set to a BasicBlock with a valid Function parent. /// @note If a size is provided, the size must not depend on any other /// instructions. If it does, invalid LLVM IR will bb generated. /// /// @param B The IRBuilder /// @param type The type to allocate /// @param size Optional count of allocations. If nullptr, runs a single allocation inline llvm::Value* insertStaticAlloca(llvm::IRBuilder<>& B, llvm::Type* type, llvm::Value* size = nullptr) { // Create the allocation at the start of the function block llvm::Function* parent = B.GetInsertBlock()->getParent(); assert(parent && !parent->empty()); auto IP = B.saveIP(); llvm::BasicBlock& block = parent->front(); if (block.empty()) B.SetInsertPoint(&block); else B.SetInsertPoint(&(block.front())); llvm::Value* result = B.CreateAlloca(type, size); B.restoreIP(IP); return result; } inline llvm::Argument* extractArgument(llvm::Function* F, const size_t idx) { if (!F) return nullptr; if (idx >= F->arg_size()) return nullptr; return llvm::cast<llvm::Argument>(F->arg_begin() + idx); } inline llvm::Argument* extractArgument(llvm::Function* F, const std::string& name) { if (!F) return nullptr; for (auto iter = F->arg_begin(); iter != F->arg_end(); ++iter) { llvm::Argument* arg = llvm::cast<llvm::Argument>(iter); if (arg->getName() == name) return arg; } return nullptr; } /// @brief Returns the highest order type from two LLVM Scalar types /// /// @param typeA The first scalar llvm type /// @param typeB The second scalar llvm type /// inline llvm::Type* typePrecedence(llvm::Type* const typeA, llvm::Type* const typeB) { assert(typeA && (typeA->isIntegerTy() || typeA->isFloatingPointTy()) && "First Type in typePrecedence is not a scalar type"); assert(typeB && (typeB->isIntegerTy() || typeB->isFloatingPointTy()) && "Second Type in typePrecedence is not a scalar type"); // handle implicit arithmetic conversion // (http://osr507doc.sco.com/en/tools/clang_conv_implicit.html) if (typeA->isDoubleTy()) return typeA; if (typeB->isDoubleTy()) return typeB; if (typeA->isFloatTy()) return typeA; if (typeB->isFloatTy()) return typeB; if (typeA->isIntegerTy(64)) return typeA; if (typeB->isIntegerTy(64)) return typeB; if (typeA->isIntegerTy(32)) return typeA; if (typeB->isIntegerTy(32)) return typeB; if (typeA->isIntegerTy(16)) return typeA; if (typeB->isIntegerTy(16)) return typeB; if (typeA->isIntegerTy(8)) return typeA; if (typeB->isIntegerTy(8)) return typeB; if (typeA->isIntegerTy(1)) return typeA; if (typeB->isIntegerTy(1)) return typeB; assert(false && "invalid LLVM type precedence"); return nullptr; } /// @brief Returns a CastFunction which represents the corresponding instruction /// to convert a source llvm Type to a target llvm Type. If the conversion /// is unsupported, throws an error. /// /// @param sourceType The source type to cast /// @param targetType The target type to cast to /// @param twine An optional string description of the cast function. This can /// be used for for more verbose llvm information on IR compilation /// failure inline CastFunction llvmArithmeticConversion(const llvm::Type* const sourceType, const llvm::Type* const targetType, const std::string& twine = "") { #define BIND_ARITHMETIC_CAST_OP(Function, Twine) \ std::bind(&Function, \ std::placeholders::_1, \ std::placeholders::_2, \ std::placeholders::_3, \ Twine) if (targetType->isDoubleTy()) { if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPExt, twine); else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateUIToFP, twine); } else if (targetType->isFloatTy()) { if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPTrunc, twine); else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSIToFP, twine); else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateUIToFP, twine); } else if (targetType->isIntegerTy(64)) { if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine); else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine); else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine); else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine); } else if (targetType->isIntegerTy(32)) { if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine); else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine); else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine); } else if (targetType->isIntegerTy(16)) { if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateSExt, twine); else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine); } else if (targetType->isIntegerTy(8)) { if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToSI, twine); else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(1)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateZExt, twine); } else if (targetType->isIntegerTy(1)) { if (sourceType->isDoubleTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToUI, twine); else if (sourceType->isFloatTy()) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateFPToUI, twine); else if (sourceType->isIntegerTy(64)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(32)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(16)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); else if (sourceType->isIntegerTy(8)) return BIND_ARITHMETIC_CAST_OP(llvm::IRBuilder<>::CreateTrunc, twine); } #undef BIND_ARITHMETIC_CAST_OP assert(false && "invalid LLVM type conversion"); return CastFunction(); } /// @brief Returns a BinaryFunction representing the corresponding instruction to /// peform on two scalar values, relative to a provided operator token. Note that /// not all operations are supported on floating point types! If the token is not /// supported, or the llvm type is not a scalar type, throws an error. /// @note Various default arguments are bound to provide a simple function call /// signature. For floating point operations, this includes a null pointer to /// the optional metadata node. For integer operations, this includes disabling /// all overflow/rounding optimisations /// /// @param type The type defining the precision of the binary operation /// @param token The token used to create the relative binary operation /// @param twine An optional string description of the binary function. This can /// be used for for more verbose llvm information on IR compilation /// failure inline BinaryFunction llvmBinaryConversion(const llvm::Type* const type, const ast::tokens::OperatorToken& token, const std::string& twine = "") { #define BIND_BINARY_OP(Function) \ [twine](llvm::IRBuilder<>& B, llvm::Value* L, llvm::Value* R) \ -> llvm::Value* { return B.Function(L, R, twine); } // NOTE: Binary % and / ops always take sign into account (CreateSDiv vs CreateUDiv, CreateSRem vs CreateURem). // See http://stackoverflow.com/questions/5346160/llvm-irbuildercreateudiv-createsdiv-createexactudiv // a%b in AX is implemented as a floored modulo op and is handled explicitly in binaryExpression if (type->isFloatingPointTy()) { assert(!(ast::tokens::operatorType(token) == ast::tokens::LOGICAL || ast::tokens::operatorType(token) == ast::tokens::BITWISE) && "unable to perform logical or bitwise operation on floating point values"); if (token == ast::tokens::PLUS) return BIND_BINARY_OP(CreateFAdd); else if (token == ast::tokens::MINUS) return BIND_BINARY_OP(CreateFSub); else if (token == ast::tokens::MULTIPLY) return BIND_BINARY_OP(CreateFMul); else if (token == ast::tokens::DIVIDE) return BIND_BINARY_OP(CreateFDiv); else if (token == ast::tokens::MODULO) return BIND_BINARY_OP(CreateFRem); // Note this is NOT a%b in AX. else if (token == ast::tokens::EQUALSEQUALS) return BIND_BINARY_OP(CreateFCmpOEQ); else if (token == ast::tokens::NOTEQUALS) return BIND_BINARY_OP(CreateFCmpONE); else if (token == ast::tokens::MORETHAN) return BIND_BINARY_OP(CreateFCmpOGT); else if (token == ast::tokens::LESSTHAN) return BIND_BINARY_OP(CreateFCmpOLT); else if (token == ast::tokens::MORETHANOREQUAL) return BIND_BINARY_OP(CreateFCmpOGE); else if (token == ast::tokens::LESSTHANOREQUAL) return BIND_BINARY_OP(CreateFCmpOLE); assert(false && "unrecognised binary operator"); } else if (type->isIntegerTy()) { if (token == ast::tokens::PLUS) return BIND_BINARY_OP(CreateAdd); // No Unsigned/Signed Wrap else if (token == ast::tokens::MINUS) return BIND_BINARY_OP(CreateSub); // No Unsigned/Signed Wrap else if (token == ast::tokens::MULTIPLY) return BIND_BINARY_OP(CreateMul); // No Unsigned/Signed Wrap else if (token == ast::tokens::DIVIDE) return BIND_BINARY_OP(CreateSDiv); // IsExact = false - when true, poison value if the reuslt is rounded else if (token == ast::tokens::MODULO) return BIND_BINARY_OP(CreateSRem); // Note this is NOT a%b in AX. else if (token == ast::tokens::EQUALSEQUALS) return BIND_BINARY_OP(CreateICmpEQ); else if (token == ast::tokens::NOTEQUALS) return BIND_BINARY_OP(CreateICmpNE); else if (token == ast::tokens::MORETHAN) return BIND_BINARY_OP(CreateICmpSGT); else if (token == ast::tokens::LESSTHAN) return BIND_BINARY_OP(CreateICmpSLT); else if (token == ast::tokens::MORETHANOREQUAL) return BIND_BINARY_OP(CreateICmpSGE); else if (token == ast::tokens::LESSTHANOREQUAL) return BIND_BINARY_OP(CreateICmpSLE); else if (token == ast::tokens::AND) return BIND_BINARY_OP(CreateAnd); else if (token == ast::tokens::OR) return BIND_BINARY_OP(CreateOr); else if (token == ast::tokens::SHIFTLEFT) return BIND_BINARY_OP(CreateShl); // No Unsigned/Signed Wrap else if (token == ast::tokens::SHIFTRIGHT) return BIND_BINARY_OP(CreateAShr); // IsExact = false - poison value if any of the bits shifted out are non-zero. else if (token == ast::tokens::BITAND) return BIND_BINARY_OP(CreateAnd); else if (token == ast::tokens::BITOR) return BIND_BINARY_OP(CreateOr); else if (token == ast::tokens::BITXOR) return BIND_BINARY_OP(CreateXor); assert(false && "unrecognised binary operator"); } #undef BIND_BINARY_OP assert(false && "invalid LLVM type for binary operation"); return BinaryFunction(); } /// @brief Returns true if the llvm Type 'from' can be safely cast to the llvm /// Type 'to'. inline bool isValidCast(llvm::Type* from, llvm::Type* to) { assert(from && "llvm Type 'from' is null in isValidCast"); assert(to && "llvm Type 'to' is null in isValidCast"); if ((from->isIntegerTy() || from->isFloatingPointTy()) && (to->isIntegerTy() || to->isFloatingPointTy())) { return true; } if (from->isArrayTy() && to->isArrayTy()) { llvm::ArrayType* af = llvm::cast<llvm::ArrayType>(from); llvm::ArrayType* at = llvm::cast<llvm::ArrayType>(to); if (af->getArrayNumElements() == at->getArrayNumElements()) { return isValidCast(af->getArrayElementType(), at->getArrayElementType()); } } return false; } /// @brief Casts a scalar llvm Value to a target scalar llvm Type. Returns /// the cast scalar value of type targetType. /// /// @param value A llvm scalar value to convert /// @param targetType The target llvm scalar type to convert to /// @param builder The current llvm IRBuilder /// inline llvm::Value* arithmeticConversion(llvm::Value* value, llvm::Type* targetType, llvm::IRBuilder<>& builder) { assert(value && (value->getType()->isIntegerTy() || value->getType()->isFloatingPointTy()) && "First Value in arithmeticConversion is not a scalar type"); assert(targetType && (targetType->isIntegerTy() || targetType->isFloatingPointTy()) && "Target Type in arithmeticConversion is not a scalar type"); const llvm::Type* const valueType = value->getType(); if (valueType == targetType) return value; CastFunction llvmCastFunction = llvmArithmeticConversion(valueType, targetType); return llvmCastFunction(builder, value, targetType); } /// @brief Casts an array to another array of equal size but of a different element /// type. Both source and target array element types must be scalar types. /// The source array llvm Value should be a pointer to the array to cast. /// /// @param ptrToArray A llvm value which is a pointer to a llvm array /// @param targetElementType The target llvm scalar type to convert each element /// of the input array /// @param builder The current llvm IRBuilder /// inline llvm::Value* arrayCast(llvm::Value* ptrToArray, llvm::Type* targetElementType, llvm::IRBuilder<>& builder) { assert(targetElementType && (targetElementType->isIntegerTy() || targetElementType->isFloatingPointTy()) && "Target element type is not a scalar type"); assert(ptrToArray && ptrToArray->getType()->isPointerTy() && "Input to arrayCast is not a pointer type."); llvm::Type* arrayType = ptrToArray->getType()->getContainedType(0); assert(arrayType && llvm::isa<llvm::ArrayType>(arrayType)); // getArrayElementType() calls getContainedType(0) llvm::Type* sourceElementType = arrayType->getArrayElementType(); assert(sourceElementType && (sourceElementType->isIntegerTy() || sourceElementType->isFloatingPointTy()) && "Source element type is not a scalar type"); if (sourceElementType == targetElementType) return ptrToArray; CastFunction llvmCastFunction = llvmArithmeticConversion(sourceElementType, targetElementType); const size_t elementSize = arrayType->getArrayNumElements(); llvm::Value* targetArray = insertStaticAlloca(builder, llvm::ArrayType::get(targetElementType, elementSize)); for (size_t i = 0; i < elementSize; ++i) { llvm::Value* target = builder.CreateConstGEP2_64(targetArray, 0, i); llvm::Value* source = builder.CreateConstGEP2_64(ptrToArray, 0, i); source = builder.CreateLoad(source); source = llvmCastFunction(builder, source, targetElementType); builder.CreateStore(source, target); } return targetArray; } /// @brief Converts a vector of loaded llvm scalar values of the same type to a /// target scalar type. Each value is converted individually and the loaded result /// stored in the same location within values. /// /// @param values A vector of llvm scalar values to convert /// @param targetElementType The target llvm scalar type to convert each value /// of the input vector /// @param builder The current llvm IRBuilder /// inline void arithmeticConversion(std::vector<llvm::Value*>& values, llvm::Type* targetElementType, llvm::IRBuilder<>& builder) { assert(targetElementType && (targetElementType->isIntegerTy() || targetElementType->isFloatingPointTy()) && "Target element type is not a scalar type"); llvm::Type* sourceElementType = values.front()->getType(); assert(sourceElementType && (sourceElementType->isIntegerTy() || sourceElementType->isFloatingPointTy()) && "Source element type is not a scalar type"); if (sourceElementType == targetElementType) return; CastFunction llvmCastFunction = llvmArithmeticConversion(sourceElementType, targetElementType); for (llvm::Value*& value : values) { value = llvmCastFunction(builder, value, targetElementType); } } /// @brief Converts a vector of loaded llvm scalar values to the highest precision /// type stored amongst them. Any values which are not scalar types are ignored /// /// @param values A vector of llvm scalar values to convert /// @param builder The current llvm IRBuilder /// inline void arithmeticConversion(std::vector<llvm::Value*>& values, llvm::IRBuilder<>& builder) { llvm::Type* typeCast = LLVMType<bool>::get(builder.getContext()); for (llvm::Value*& value : values) { llvm::Type* type = value->getType(); if (type->isIntegerTy() || type->isFloatingPointTy()) { typeCast = typePrecedence(typeCast, type); } } arithmeticConversion(values, typeCast, builder); } /// @brief Chooses the highest order llvm Type as defined by typePrecedence /// from either of the two incoming values and casts the other value to /// the choosen type if it is not already. The types of valueA and valueB /// are guaranteed to match. Both values must be scalar LLVM types /// /// @param valueA The first llvm value /// @param valueB The second llvm value /// @param builder The current llvm IRBuilder /// inline void arithmeticConversion(llvm::Value*& valueA, llvm::Value*& valueB, llvm::IRBuilder<>& builder) { llvm::Type* type = typePrecedence(valueA->getType(), valueB->getType()); valueA = arithmeticConversion(valueA, type, builder); valueB = arithmeticConversion(valueB, type, builder); } /// @brief Performs a C style boolean comparison from a given scalar LLVM value /// /// @param value The scalar llvm value to convert to a boolean /// @param builder The current llvm IRBuilder /// inline llvm::Value* boolComparison(llvm::Value* value, llvm::IRBuilder<>& builder) { llvm::Type* type = value->getType(); if (type->isFloatingPointTy()) return builder.CreateFCmpONE(value, llvm::ConstantFP::get(type, 0.0)); else if (type->isIntegerTy(1)) return builder.CreateICmpNE(value, llvm::ConstantInt::get(type, 0)); else if (type->isIntegerTy()) return builder.CreateICmpNE(value, llvm::ConstantInt::getSigned(type, 0)); assert(false && "Invalid type for bool conversion"); return nullptr; } /// @ brief Performs a binary operation on two loaded llvm scalar values of the same type. /// The type of operation performed is defined by the token (see the list of supported /// tokens in ast/Tokens.h. Returns a loaded llvm scalar result /// /// @param lhs The left hand side value of the binary operation /// @param rhs The right hand side value of the binary operation /// @param token The token representing the binary operation to perform /// @param builder The current llvm IRBuilder inline llvm::Value* binaryOperator(llvm::Value* lhs, llvm::Value* rhs, const ast::tokens::OperatorToken& token, llvm::IRBuilder<>& builder) { llvm::Type* lhsType = lhs->getType(); assert(lhsType == rhs->getType()); const ast::tokens::OperatorType opType = ast::tokens::operatorType(token); if (opType == ast::tokens::LOGICAL) { lhs = boolComparison(lhs, builder); rhs = boolComparison(rhs, builder); lhsType = lhs->getType(); // now bool type } const BinaryFunction llvmBinaryFunction = llvmBinaryConversion(lhsType, token); return llvmBinaryFunction(builder, lhs, rhs); } /// @brief Unpack a particular element of an array and return a pointer to that element /// The provided llvm Value is expected to be a pointer to an array /// /// @param ptrToArray A llvm value which is a pointer to a llvm array /// @param index The index at which to access the array /// @param builder The current llvm IRBuilder /// inline llvm::Value* arrayIndexUnpack(llvm::Value* ptrToArray, const int16_t index, llvm::IRBuilder<>& builder) { return builder.CreateConstGEP2_64(ptrToArray, 0, index); } /// @brief Unpack an array type into llvm Values which represent all its elements /// The provided llvm Value is expected to be a pointer to an array /// If loadElements is true, values will store loaded llvm values instead /// of pointers to the array elements /// /// @param ptrToArray A llvm value which is a pointer to a llvm array /// @param values A vector of llvm values where to store the array elements /// @param builder The current llvm IRBuilder /// @param loadElements Whether or not to load each array element into a register /// inline void arrayUnpack(llvm::Value* ptrToArray, std::vector<llvm::Value*>& values, llvm::IRBuilder<>& builder, const bool loadElements = false) { const size_t elements = ptrToArray->getType()->getContainedType(0)->getArrayNumElements(); values.reserve(elements); for (size_t i = 0; i < elements; ++i) { llvm::Value* value = builder.CreateConstGEP2_64(ptrToArray, 0, i); if (loadElements) value = builder.CreateLoad(value); values.push_back(value); } } /// @brief Unpack the first three elements of an array. /// The provided llvm Value is expected to be a pointer to an array /// @note The elements are note loaded /// /// @param ptrToArray A llvm value which is a pointer to a llvm array /// @param value1 The first array value /// @param value2 The second array value /// @param value3 The third array value /// @param builder The current llvm IRBuilder /// inline void array3Unpack(llvm::Value* ptrToArray, llvm::Value*& value1, llvm::Value*& value2, llvm::Value*& value3, llvm::IRBuilder<>& builder) { assert(ptrToArray && ptrToArray->getType()->isPointerTy() && "Input to array3Unpack is not a pointer type."); value1 = builder.CreateConstGEP2_64(ptrToArray, 0, 0); value2 = builder.CreateConstGEP2_64(ptrToArray, 0, 1); value3 = builder.CreateConstGEP2_64(ptrToArray, 0, 2); } /// @brief Pack three values into a new array and return a pointer to the /// newly allocated array. If the values are of a mismatching type, /// the highets order type is uses, as defined by typePrecedence. All /// llvm values are expected to a be a loaded scalar type /// /// @param value1 The first array value /// @param value2 The second array value /// @param value3 The third array value /// @param builder The current llvm IRBuilder /// inline llvm::Value* array3Pack(llvm::Value* value1, llvm::Value* value2, llvm::Value* value3, llvm::IRBuilder<>& builder) { llvm::Type* type = typePrecedence(value1->getType(), value2->getType()); type = typePrecedence(type, value3->getType()); value1 = arithmeticConversion(value1, type, builder); value2 = arithmeticConversion(value2, type, builder); value3 = arithmeticConversion(value3, type, builder); llvm::Type* vectorType = llvm::ArrayType::get(type, 3); llvm::Value* vector = insertStaticAlloca(builder, vectorType); llvm::Value* e1 = builder.CreateConstGEP2_64(vector, 0, 0); llvm::Value* e2 = builder.CreateConstGEP2_64(vector, 0, 1); llvm::Value* e3 = builder.CreateConstGEP2_64(vector, 0, 2); builder.CreateStore(value1, e1); builder.CreateStore(value2, e2); builder.CreateStore(value3, e3); return vector; } /// @brief Pack a loaded llvm scalar value into a new array of a specified /// size and return a pointer to the newly allocated array. Each element /// of the new array will have the value of the given scalar /// /// @param value The uniform scalar llvm value to pack into the array /// @param builder The current llvm IRBuilder /// @param size The size of the newly allocated array /// inline llvm::Value* arrayPack(llvm::Value* value, llvm::IRBuilder<>& builder, const size_t size = 3) { assert(value && (value->getType()->isIntegerTy() || value->getType()->isFloatingPointTy()) && "value type is not a scalar type"); llvm::Type* type = value->getType(); llvm::Value* array = insertStaticAlloca(builder, llvm::ArrayType::get(type, size)); for (size_t i = 0; i < size; ++i) { llvm::Value* element = builder.CreateConstGEP2_64(array, 0, i); builder.CreateStore(value, element); } return array; } /// @brief Pack a vector of loaded llvm scalar values into a new array of /// equal size and return a pointer to the newly allocated array. /// /// @param values A vector of loaded llvm scalar values to pack /// @param builder The current llvm IRBuilder /// inline llvm::Value* arrayPack(const std::vector<llvm::Value*>& values, llvm::IRBuilder<>& builder) { llvm::Type* type = values.front()->getType(); llvm::Value* array = insertStaticAlloca(builder, llvm::ArrayType::get(type, values.size())); size_t idx = 0; for (llvm::Value* const& value : values) { llvm::Value* element = builder.CreateConstGEP2_64(array, 0, idx++); builder.CreateStore(value, element); } return array; } /// @brief Pack a vector of loaded llvm scalar values into a new array of /// equal size and return a pointer to the newly allocated array. /// arrayPackCast first checks all the contained types in values /// and casts all types to the highest order type present. All llvm /// values in values are expected to be loaded scalar types /// /// @param values A vector of loaded llvm scalar values to pack /// @param builder The current llvm IRBuilder /// inline llvm::Value* arrayPackCast(std::vector<llvm::Value*>& values, llvm::IRBuilder<>& builder) { // get the highest order type present llvm::Type* type = LLVMType<bool>::get(builder.getContext()); for (llvm::Value* const& value : values) { type = typePrecedence(type, value->getType()); } // convert all to this type for (llvm::Value*& value : values) { value = arithmeticConversion(value, type, builder); } return arrayPack(values, builder); } inline llvm::Value* scalarToMatrix(llvm::Value* scalar, llvm::IRBuilder<>& builder, const size_t dim = 3) { assert(scalar && (scalar->getType()->isIntegerTy() || scalar->getType()->isFloatingPointTy()) && "value type is not a scalar type"); llvm::Type* type = scalar->getType(); llvm::Value* array = insertStaticAlloca(builder, llvm::ArrayType::get(type, dim*dim)); llvm::Value* zero = llvm::ConstantFP::get(type, 0.0); for (size_t i = 0; i < dim*dim; ++i) { llvm::Value* m = ((i % (dim+1) == 0) ? scalar : zero); llvm::Value* element = builder.CreateConstGEP2_64(array, 0, i); builder.CreateStore(m, element); } return array; } } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_UTILS_HAS_BEEN_INCLUDED
34,561
C
42.860406
170
0.660716
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/VolumeComputeGenerator.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/VolumeComputeGenerator.h /// /// @authors Nick Avramoussis /// /// @brief The visitor framework and function definition for volume grid /// code generation /// #ifndef OPENVDB_AX_VOLUME_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #define OPENVDB_AX_VOLUME_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #include "ComputeGenerator.h" #include "FunctionTypes.h" #include "../compiler/AttributeRegistry.h" #include <openvdb/version.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief The function definition and signature which is built by the /// VolumeComputeGenerator. /// /// The argument structure is as follows: /// /// 1) - A void pointer to the CustomData /// 2) - A pointer to an array of three ints representing the /// current voxel coord being accessed /// 3) - An pointer to an array of three floats representing the /// current voxel world space coord being accessed /// 4) - A void pointer to a vector of void pointers, representing /// an array of grid accessors /// 5) - A void pointer to a vector of void pointers, representing /// an array of grid transforms /// struct VolumeKernel { // The signature of the generated function using Signature = void(const void* const, const int32_t (*)[3], const float (*)[3], void**, void**, int64_t, void*); using FunctionTraitsT = codegen::FunctionTraits<Signature>; static const size_t N_ARGS = FunctionTraitsT::N_ARGS; static const std::array<std::string, N_ARGS>& argumentKeys(); static std::string getDefaultName(); }; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// namespace codegen_internal { /// @brief Visitor object which will generate llvm IR for a syntax tree which has been generated /// from AX that targets volumes. The IR will represent a single function. It is mainly /// used by the Compiler class. struct VolumeComputeGenerator : public ComputeGenerator { /// @brief Constructor /// @param module llvm Module for generating IR /// @param options Options for the function registry behaviour /// @param functionRegistry Function registry object which will be used when generating IR /// for function calls /// @param logger Logger for collecting logical errors and warnings VolumeComputeGenerator(llvm::Module& module, const FunctionOptions& options, FunctionRegistry& functionRegistry, Logger& logger); ~VolumeComputeGenerator() override = default; using ComputeGenerator::traverse; using ComputeGenerator::visit; AttributeRegistry::Ptr generate(const ast::Tree& node); bool visit(const ast::Attribute*) override; private: llvm::Value* accessorHandleFromToken(const std::string&); void getAccessorValue(const std::string&, llvm::Value*); }; } // namespace codegen_internal } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_VOLUME_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
3,505
C
31.766355
96
0.635378
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Types.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/Types.h /// /// @authors Nick Avramoussis /// /// @brief Consolidated llvm types for most supported types /// #ifndef OPENVDB_AX_CODEGEN_TYPES_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_TYPES_HAS_BEEN_INCLUDED #include "../ast/Tokens.h" #include "../Exceptions.h" #include "../compiler/CustomData.h" // for AXString #include <openvdb/version.h> #include <openvdb/Types.h> #include <openvdb/math/Mat3.h> #include <openvdb/math/Mat4.h> #include <openvdb/math/Vec3.h> #include <llvm/IR/Constants.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <type_traits> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { template <size_t Bits> struct int_t; template <> struct int_t<8> { using type = int8_t; }; template <> struct int_t<16> { using type = int16_t; }; template <> struct int_t<32> { using type = int32_t; }; template <> struct int_t<64> { using type = int64_t; }; /// @brief LLVM type mapping from pod types /// @note LLVM Types do not store information about the value sign, only meta /// information about the primitive type (i.e. float, int, pointer) and /// the precision width. LLVMType<uint64_t>::get(C) will provide the same /// type as LLVMType<int64_t>::get(C), however sign is taken into account /// during construction of LLVM constants. /// @note LLVMType classes are importantly used to provided automatic external /// function mapping. Note that references are not supported, pointers /// should be used instead. /// @note Provide your own custom class mapping by specializing the below. template <typename T> struct LLVMType { static_assert(!std::is_reference<T>::value, "Reference types/arguments are not supported for automatic " "LLVM Type conversion. Use pointers instead."); static_assert(!std::is_class<T>::value, "Object types/arguments are not supported for automatic " "LLVM Type conversion."); /// @brief Return an LLVM type which represents T /// @param C The LLVMContext to request the Type from. static inline llvm::Type* get(llvm::LLVMContext& C) { // @note bools always treated as i1 values as the constants // true and false from the IRBuilder are i1 if (std::is_same<T, bool>::value) { return llvm::Type::getInt1Ty(C); } #if LLVM_VERSION_MAJOR > 6 return llvm::Type::getScalarTy<T>(C); #else int bits = sizeof(T) * CHAR_BIT; if (std::is_integral<T>::value) { return llvm::Type::getIntNTy(C, bits); } else if (std::is_floating_point<T>::value) { switch (bits) { case 32: return llvm::Type::getFloatTy(C); case 64: return llvm::Type::getDoubleTy(C); } } OPENVDB_THROW(AXCodeGenError, "LLVMType called with an unsupported type \"" + std::string(typeNameAsString<T>()) + "\"."); #endif } /// @brief Return an LLVM constant Value which represents T value /// @param C The LLVMContext /// @param V The value to convert to an LLVM constant /// @return If successful, returns a pointer to an LLVM constant which /// holds the value T. static inline llvm::Constant* get(llvm::LLVMContext& C, const T V) { llvm::Type* type = LLVMType<T>::get(C); llvm::Constant* constant = nullptr; if (std::is_floating_point<T>::value) { assert(llvm::ConstantFP::isValueValidForType(type, llvm::APFloat(static_cast<typename std::conditional <std::is_floating_point<T>::value, T, double>::type>(V)))); constant = llvm::ConstantFP::get(type, static_cast<double>(V)); } else if (std::is_integral<T>::value) { const constexpr bool isSigned = std::is_signed<T>::value; assert((isSigned && llvm::ConstantInt::isValueValidForType(type, static_cast<int64_t>(V))) || (!isSigned && llvm::ConstantInt::isValueValidForType(type, static_cast<uint64_t>(V)))); constant = llvm::ConstantInt::get(type, static_cast<uint64_t>(V), isSigned); } assert(constant); return constant; } /// @brief Return an LLVM constant which holds an uintptr_t, representing /// the current address of the given value. /// @param C The LLVMContext /// @param V The address of a given type to convert to an LLVM constant static inline llvm::Constant* get(llvm::LLVMContext& C, const T* const V) { return LLVMType<uintptr_t>::get(C, reinterpret_cast<uintptr_t>(V)); } }; template <typename T, size_t S> struct LLVMType<T[S]> { static_assert(S != 0, "Zero size array types are not supported for automatic LLVM " "Type conversion"); static inline llvm::Type* get(llvm::LLVMContext& C) { return llvm::ArrayType::get(LLVMType<T>::get(C), S); } static inline llvm::Constant* get(llvm::LLVMContext& C, const T(&array)[S]) { return llvm::ConstantDataArray::get(C, array); } static inline llvm::Constant* get(llvm::LLVMContext& C, const T(*array)[S]) { return LLVMType<uintptr_t>::get(C, reinterpret_cast<uintptr_t>(array)); } }; template <typename T> struct LLVMType<T*> { static inline llvm::PointerType* get(llvm::LLVMContext& C) { return LLVMType<T>::get(C)->getPointerTo(0); } }; template <> struct LLVMType<char> : public LLVMType<uint8_t> { static_assert(std::is_same<uint8_t, unsigned char>::value, "This library requires std::uint8_t to be implemented as unsigned char."); }; template <> struct LLVMType<AXString> { static inline llvm::StructType* get(llvm::LLVMContext& C) { const std::vector<llvm::Type*> types { LLVMType<char*>::get(C), // array LLVMType<AXString::SizeType>::get(C) // size }; return llvm::StructType::get(C, types); } static inline llvm::Value* get(llvm::LLVMContext& C, llvm::Constant* string, llvm::Constant* size) { return llvm::ConstantStruct::get(LLVMType<AXString>::get(C), {string, size}); } /// @note Creating strings from a literal requires a GEP instruction to /// store the string ptr on the struct. /// @note Usually you should be using s = builder.CreateGlobalStringPtr() /// followed by LLVMType<AXString>::get(C, s) rather than allocating /// a non global string static inline llvm::Value* get(llvm::LLVMContext& C, const std::string& string, llvm::IRBuilder<>& builder) { llvm::Constant* constant = llvm::ConstantDataArray::getString(C, string, /*terminator*/true); llvm::Constant* size = llvm::cast<llvm::Constant> (LLVMType<AXString::SizeType>::get(C, static_cast<AXString::SizeType>(string.size()))); llvm::Value* zero = LLVMType<int32_t>::get(C, 0); llvm::Value* args[] = { zero, zero }; constant = llvm::cast<llvm::Constant> (builder.CreateInBoundsGEP(constant->getType(), constant, args)); return LLVMType<AXString>::get(C, constant, size); } static inline llvm::Constant* get(llvm::LLVMContext& C, const AXString* const string) { return LLVMType<uintptr_t>::get(C, reinterpret_cast<uintptr_t>(string)); } }; template <> struct LLVMType<void> { static inline llvm::Type* get(llvm::LLVMContext& C) { return llvm::Type::getVoidTy(C); } }; /// @note void* implemented as signed int_t* to match clang IR generation template <> struct LLVMType<void*> : public LLVMType<int_t<sizeof(void*)>::type*> {}; template <typename T> struct LLVMType<const T> : public LLVMType<T> {}; template <typename T> struct LLVMType<const T*> : public LLVMType<T*> {}; /// @brief Alias mapping between two types, a frontend type T1 and a backend /// type T2. This class is the intended interface for binding objects /// which implement supported backend AX/IR types to this given backend /// type. More specifically, it's current and expected usage is limited /// to objects which hold a single member of a supported backend type /// and implements a StandardLayoutType as defined by the standard. /// Fundamentally, T1->T2 mapping should be supported by /// reinterpret_cast<> as defined by the type aliasing rules. /// @note The static asserts provide preliminary checks but are by no means /// a guarantee that a provided mapping is correct. Ensure the above /// requirements are met when instantiating an alias. template <typename T1, typename T2> struct AliasTypeMap { using LLVMTypeT = LLVMType<T2>; static_assert(sizeof(T1) == sizeof(T2), "T1 differs in size to T2 during alias mapping. Types should have " "the same memory layout."); static_assert(std::is_standard_layout<T1>::value, "T1 in instantiation of an AliasTypeMap does not have a standard layout. " "This will most likely cause undefined behaviour when attempting to map " "T1->T2."); static inline llvm::Type* get(llvm::LLVMContext& C) { return LLVMTypeT::get(C); } static inline llvm::Constant* get(llvm::LLVMContext& C, const T1& value) { return LLVMTypeT::get(C, reinterpret_cast<const T2&>(value)); } static inline llvm::Constant* get(llvm::LLVMContext& C, const T1* const value) { return LLVMTypeT::get(C, reinterpret_cast<const T2* const>(value)); } }; /// @brief Supported aliasing for VDB math types, allowing use in external /// function signatures. template <typename T> struct LLVMType<math::Vec2<T>> : public AliasTypeMap<math::Vec2<T>, T[2]> {}; template <typename T> struct LLVMType<math::Vec3<T>> : public AliasTypeMap<math::Vec3<T>, T[3]> {}; template <typename T> struct LLVMType<math::Vec4<T>> : public AliasTypeMap<math::Vec4<T>, T[4]> {}; template <typename T> struct LLVMType<math::Mat3<T>> : public AliasTypeMap<math::Mat3<T>, T[9]> {}; template <typename T> struct LLVMType<math::Mat4<T>> : public AliasTypeMap<math::Mat4<T>, T[16]> {}; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /// @brief Templated function traits which provides compile-time index access to /// the types of the function signature /// template<typename SignatureT> struct FunctionTraits; template<typename R, typename... Args> struct FunctionTraits<R(&)(Args...)> : public FunctionTraits<R(Args...)> {}; template<typename R, typename... Args> struct FunctionTraits<R(*)(Args...)> : public FunctionTraits<R(Args...)> {}; template<typename ReturnT, typename ...Args> struct FunctionTraits<ReturnT(Args...)> { using ReturnType = ReturnT; using SignatureType = ReturnType(Args...); static const size_t N_ARGS = sizeof...(Args); template <size_t I> struct Arg { public: static_assert(I < N_ARGS, "Invalid index specified for function argument access"); using Type = typename std::tuple_element<I, std::tuple<Args...>>::type; static_assert(!std::is_reference<Type>::value, "Reference types/arguments are not supported for automatic " "LLVM Type conversion. Use pointers instead."); }; }; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /// @brief Returns an llvm Constant holding a scalar value /// @param t The scalar constant /// @param type The LLVM type. Can differ from the type of t, in which /// case the value will be cast to the llvm type /// template <typename T> inline llvm::Constant* llvmConstant(const T t, llvm::Type* type) { static_assert(std::is_floating_point<T>::value || std::is_integral<T>::value, "T type for llvmConstant must be a floating point or integral type."); if (type->isIntegerTy()) { return llvm::ConstantInt::get(type, static_cast<uint64_t>(t), /*signed*/true); } else { assert(type->isFloatingPointTy()); return llvm::ConstantFP::get(type, static_cast<double>(t)); } } /// @brief Returns an llvm IntegerType given a requested size and context /// @param size The number of bits of the integer type /// @param C The LLVMContext to request the Type from. /// llvm::IntegerType* llvmIntType(const uint32_t size, llvm::LLVMContext& C); /// @brief Returns an llvm floating point Type given a requested size and context /// @param size The size of the float to request, i.e. float - 32, double - 64 etc. /// @param C The LLVMContext to request the Type from. /// llvm::Type* llvmFloatType(const uint32_t size, llvm::LLVMContext& C); /// @brief Returns an llvm type representing a type defined by a string. /// @note For string types, this function returns the element type, not the /// object type! The llvm type representing a char block of memory /// is LLVMType<char*>::get(C); /// @param type The AX token type /// @param C The LLVMContext to request the Type from. /// llvm::Type* llvmTypeFromToken(const ast::tokens::CoreType& type, llvm::LLVMContext& C); /// @brief Return a corresponding AX token which represents the given LLVM Type. /// @note If the type does not exist in AX, ast::tokens::UNKNOWN is returned. /// Must not be a nullptr. /// @param type a valid LLVM Type /// ast::tokens::CoreType tokenFromLLVMType(const llvm::Type* type); } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_TYPES_HAS_BEEN_INCLUDED
14,001
C
37.25683
106
0.63674
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/ComputeGenerator.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/ComputeGenerator.h /// /// @authors Nick Avramoussis, Matt Warner, Francisco Gochez, Richard Jones /// /// @brief The core visitor framework for code generation /// #ifndef OPENVDB_AX_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #include "FunctionRegistry.h" #include "FunctionTypes.h" #include "SymbolTable.h" #include "../ast/AST.h" #include "../ast/Visitor.h" #include "../compiler/CompilerOptions.h" #include "../compiler/Logger.h" #include <openvdb/version.h> #include <llvm/Analysis/TargetLibraryInfo.h> #include <llvm/IR/BasicBlock.h> #include <llvm/IR/Function.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <stack> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief The function definition and signature which is built by the /// ComputeGenerator. /// /// The argument structure is as follows: /// /// 1) - A void pointer to the CustomData /// struct ComputeKernel { /// The name of the generated function static const std::string Name; /// The signature of the generated function using Signature = void(const void* const); using FunctionTraitsT = codegen::FunctionTraits<Signature>; static const size_t N_ARGS = FunctionTraitsT::N_ARGS; /// The argument key names available during code generation static const std::array<std::string, N_ARGS>& getArgumentKeys(); static std::string getDefaultName(); }; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// namespace codegen_internal { /// @brief Visitor object which will generate llvm IR for a syntax tree. /// This provides the majority of the code generation functionality but is incomplete /// and should be inherited from and extended with ast::Attribute handling (see /// PointComputeGenerator.h/VolumeComputeGenerator.h for examples). /// @note: The visit/traverse methods work slightly differently to the normal Visitor /// to allow proper handling of errors and visitation history. Nodes that inherit from /// ast::Expression can return false from visit() (and so traverse()), but this will not /// necessarily stop traversal altogether. Instead, any ast::Statements that are not also /// ast::Expressions i.e. Block, ConditionalStatement, Loop, DeclareLocal override their /// visit/traverse methods to handle custom traversal order, and the catching of failed child /// Expression visit/traverse calls. This allows errors in independent Statements to not halt /// traversal for future Statements and so allow capturing of multiple errors in an ast::Tree /// in a single call to generate(). /// struct ComputeGenerator : public ast::Visitor<ComputeGenerator> { ComputeGenerator(llvm::Module& module, const FunctionOptions& options, FunctionRegistry& functionRegistry, Logger& logger); virtual ~ComputeGenerator() = default; bool generate(const ast::Tree&); inline SymbolTable& globals() { return mSymbolTables.globals(); } inline const SymbolTable& globals() const { return mSymbolTables.globals(); } // Visitor pattern using ast::Visitor<ComputeGenerator>::traverse; using ast::Visitor<ComputeGenerator>::visit; /// @brief Code generation always runs post order inline bool postOrderNodes() const { return true; } /// @brief Custom traversal of scoped blocks /// @note This overrides the default traversal to incorporate /// the scoping of variables declared in this block bool traverse(const ast::Block* block) { if (!block) return true; if (!this->visit(block)) return false; return true; } /// @brief Custom traversal of comma expression /// @note This overrides the default traversal to handle errors /// without stopping generation of entire list /// @todo Replace with a binary operator that simply returns the second value bool traverse(const ast::CommaOperator* comma) { if (!comma) return true; if (!this->visit(comma)) return false; return true; } /// @brief Custom traversal of conditional statements /// @note This overrides the default traversal to handle /// branching between different code paths bool traverse(const ast::ConditionalStatement* cond) { if (!cond) return true; if (!this->visit(cond)) return false; return true; } /// @brief Custom traversal of binary operators /// @note This overrides the default traversal to handle /// short-circuiting in logical AND and OR bool traverse(const ast::BinaryOperator* bin) { if (!bin) return true; if (!this->visit(bin)) return false; return true; } /// @brief Custom traversal of ternary operators /// @note This overrides the default traversal to handle /// branching between different code paths bool traverse(const ast::TernaryOperator* tern) { if (!tern) return true; if (!this->visit(tern)) return false; return true; } /// @brief Custom traversal of loops /// @note This overrides the default traversal to handle /// branching between different code paths and the /// scoping of variables in for-loop initialisation bool traverse(const ast::Loop* loop) { if (!loop) return true; if (!this->visit(loop)) return false; return true; } /// @brief Custom traversal of declarations /// @note This overrides the default traversal to /// handle traversal of the local and /// assignment of initialiser, if it exists bool traverse(const ast::DeclareLocal* decl) { if (!decl) return true; if (!this->visit(decl)) return false; return true; } virtual bool visit(const ast::CommaOperator*); virtual bool visit(const ast::AssignExpression*); virtual bool visit(const ast::Crement*); virtual bool visit(const ast::FunctionCall*); virtual bool visit(const ast::Attribute*); virtual bool visit(const ast::Tree*); virtual bool visit(const ast::Block*); virtual bool visit(const ast::ConditionalStatement*); virtual bool visit(const ast::Loop*); virtual bool visit(const ast::Keyword*); virtual bool visit(const ast::UnaryOperator*); virtual bool visit(const ast::BinaryOperator*); virtual bool visit(const ast::TernaryOperator*); virtual bool visit(const ast::Cast*); virtual bool visit(const ast::DeclareLocal*); virtual bool visit(const ast::Local*); virtual bool visit(const ast::ExternalVariable*); virtual bool visit(const ast::ArrayUnpack*); virtual bool visit(const ast::ArrayPack*); virtual bool visit(const ast::Value<bool>*); virtual bool visit(const ast::Value<int16_t>*); virtual bool visit(const ast::Value<int32_t>*); virtual bool visit(const ast::Value<int64_t>*); virtual bool visit(const ast::Value<float>*); virtual bool visit(const ast::Value<double>*); virtual bool visit(const ast::Value<std::string>*); template <typename ValueType> typename std::enable_if<std::is_integral<ValueType>::value, bool>::type visit(const ast::Value<ValueType>* node); template <typename ValueType> typename std::enable_if<std::is_floating_point<ValueType>::value, bool>::type visit(const ast::Value<ValueType>* node); protected: const FunctionGroup* getFunction(const std::string& identifier, const bool allowInternal = false); bool binaryExpression(llvm::Value*& result, llvm::Value* lhs, llvm::Value* rhs, const ast::tokens::OperatorToken op, const ast::Node* node); bool assignExpression(llvm::Value* lhs, llvm::Value*& rhs, const ast::Node* node); llvm::Module& mModule; llvm::LLVMContext& mContext; llvm::IRBuilder<> mBuilder; // The stack of accessed values std::stack<llvm::Value*> mValues; // The stack of blocks for keyword branching std::stack<std::pair<llvm::BasicBlock*, llvm::BasicBlock*>> mBreakContinueStack; // The current scope number used to track scoped declarations size_t mScopeIndex; // The map of scope number to local variable names to values SymbolTableBlocks mSymbolTables; // The function used as the base code block llvm::Function* mFunction; const FunctionOptions mOptions; Logger& mLog; private: FunctionRegistry& mFunctionRegistry; }; } // codegen_internal } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED
9,038
C
33.899614
93
0.674264
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointLeafLocalData.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/PointLeafLocalData.h /// /// @authors Nick Avramoussis /// /// @brief Thread/Leaf local data used during execution over OpenVDB Points /// #ifndef OPENVDB_AX_COMPILER_LEAF_LOCAL_DATA_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_LEAF_LOCAL_DATA_HAS_BEEN_INCLUDED #include <openvdb/openvdb.h> #include <openvdb/version.h> #include <openvdb/points/AttributeArray.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointGroup.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { namespace codegen_internal { /// @brief Various functions can request the use and initialization of point data from within /// the kernel that does not use the standard attribute handle methods. This data can /// then be accessed after execution to perform post-processes such as adding new groups, /// adding new string attributes or updating positions. /// /// @note Due to the way string handles work, string write attribute handles cannot /// be constructed in parallel, nor can read handles retrieve values in parallel /// if there is a chance the shared metadata is being written to (with set()). /// As the compiler allows for any arbitrary string setting/getting, leaf local /// maps are used for temporary storage per point. The maps use the string array /// pointers as a key for later synchronization. /// struct PointLeafLocalData { using UniquePtr = std::unique_ptr<PointLeafLocalData>; using GroupArrayT = openvdb::points::GroupAttributeArray; using GroupHandleT = openvdb::points::GroupWriteHandle; using PointStringMap = std::map<uint64_t, std::string>; using StringArrayMap = std::map<points::AttributeArray*, PointStringMap>; using LeafNode = openvdb::points::PointDataTree::LeafNodeType; /// @brief Construct a new data object to keep track of various data objects /// created per leaf by the point compute generator. /// /// @param count The number of points within the current leaf, used to initialize /// the size of new arrays /// PointLeafLocalData(const size_t count) : mPointCount(count) , mArrays() , mOffset(0) , mHandles() , mStringMap() {} //////////////////////////////////////////////////////////////////////// /// Group methods /// @brief Return a group write handle to a specific group name, creating the /// group array if it doesn't exist. This includes either registering a /// new offset or allocating an entire array. The returned handle is /// guaranteed to be valid. /// /// @param name The group name /// inline GroupHandleT* getOrInsert(const std::string& name) { GroupHandleT* ptr = get(name); if (ptr) return ptr; static const size_t maxGroupsInArray = #if (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER > 7 || \ (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER >= 7 && \ OPENVDB_LIBRARY_MINOR_VERSION_NUMBER >= 1)) points::AttributeSet::Descriptor::groupBits(); #else // old removed method points::point_group_internal::GroupInfo::groupBits(); #endif if (mArrays.empty() || mOffset == maxGroupsInArray) { assert(mPointCount < static_cast<size_t>(std::numeric_limits<openvdb::Index>::max())); mArrays.emplace_back(new GroupArrayT(static_cast<openvdb::Index>(mPointCount))); mOffset = 0; } GroupArrayT* array = mArrays.back().get(); assert(array); std::unique_ptr<GroupHandleT>& handle = mHandles[name]; handle.reset(new GroupHandleT(*array, mOffset++)); return handle.get(); } /// @brief Return a group write handle to a specific group name if it exists. /// Returns a nullptr if no group exists of the given name /// /// @param name The group name /// inline GroupHandleT* get(const std::string& name) const { const auto iter = mHandles.find(name); if (iter == mHandles.end()) return nullptr; return iter->second.get(); } /// @brief Return true if a valid group handle exists /// /// @param name The group name /// inline bool hasGroup(const std::string& name) const { return mHandles.find(name) != mHandles.end(); } /// @brief Populate a set with all the groups which have been inserted into /// this object. Used to compute a final set of all new groups which /// have been created across all leaf nodes /// /// @param groups The set to populate /// inline void getGroups(std::set<std::string>& groups) const { for (const auto& iter : mHandles) { groups.insert(iter.first); } } /// @brief Compact all arrays stored on this object. This does not invalidate /// any active write handles. /// inline void compact() { for (auto& array : mArrays) array->compact(); } //////////////////////////////////////////////////////////////////////// /// String methods /// @brief Get any new string data associated with a particular point on a /// particular string attribute array. Returns true if data was set, /// false if no data was found. /// /// @param array The array pointer to use as a key lookup /// @param idx The point index /// @param data The string to set if data is stored /// inline bool getNewStringData(const points::AttributeArray* array, const uint64_t idx, std::string& data) const { const auto arrayMapIter = mStringMap.find(const_cast<points::AttributeArray*>(array)); if (arrayMapIter == mStringMap.end()) return false; const auto iter = arrayMapIter->second.find(idx); if (iter == arrayMapIter->second.end()) return false; data = iter->second; return true; } /// @brief Set new string data associated with a particular point on a /// particular string attribute array. /// /// @param array The array pointer to use as a key lookup /// @param idx The point index /// @param data The string to set /// inline void setNewStringData(points::AttributeArray* array, const uint64_t idx, const std::string& data) { mStringMap[array][idx] = data; } /// @brief Remove any new string data associated with a particular point on a /// particular string attribute array. Does nothing if no data exists /// /// @param array The array pointer to use as a key lookup /// @param idx The point index /// inline void removeNewStringData(points::AttributeArray* array, const uint64_t idx) { const auto arrayMapIter = mStringMap.find(array); if (arrayMapIter == mStringMap.end()) return; arrayMapIter->second.erase(idx); if (arrayMapIter->second.empty()) mStringMap.erase(arrayMapIter); } /// @brief Insert all new point strings stored across all collected string /// attribute arrays into a StringMetaInserter. Returns false if the /// inserter was not accessed and true if it was potentially modified. /// /// @param inserter The string meta inserter to update /// inline bool insertNewStrings(points::StringMetaInserter& inserter) const { for (const auto& arrayIter : mStringMap) { for (const auto& iter : arrayIter.second) { inserter.insert(iter.second); } } return !mStringMap.empty(); } /// @brief Returns a const reference to the string array map /// inline const StringArrayMap& getStringArrayMap() const { return mStringMap; } private: const size_t mPointCount; std::vector<std::unique_ptr<GroupArrayT>> mArrays; points::GroupType mOffset; std::map<std::string, std::unique_ptr<GroupHandleT>> mHandles; StringArrayMap mStringMap; }; } // codegen_internal } // namespace compiler } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_LEAF_LOCAL_DATA_HAS_BEEN_INCLUDED
8,466
C
35.029787
104
0.634774
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointFunctions.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/PointFunctions.cc /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief Contains the function objects that define the functions used in /// point compute function generation, to be inserted into the /// FunctionRegistry. These define the functions available when operating /// on points. Also includes the definitions for the point attribute /// retrieval and setting. /// #include "Functions.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "PointLeafLocalData.h" #include "../ast/Tokens.h" #include "../compiler/CompilerOptions.h" #include "../Exceptions.h" #include <openvdb/openvdb.h> #include <openvdb/points/PointDataGrid.h> #include <unordered_map> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { namespace { /// @todo Provide more framework for functions such that they can only /// be registered against compatible code generators. inline void verifyContext(const llvm::Function* const F, const std::string& name) { if (!F || F->getName() != "ax.compute.point") { OPENVDB_THROW(AXCompilerError, "Function \"" << name << "\" cannot be called for " "the current target. This function only runs on OpenVDB Point Grids."); } } /// @brief Retrieve a group handle from an expected vector of handles using the offset /// pointed to by the engine data. Note that HandleT should only ever be a GroupHandle /// or GroupWriteHandle object template <typename HandleT> inline HandleT* groupHandle(const std::string& name, void** groupHandles, const void* const data) { const openvdb::points::AttributeSet* const attributeSet = static_cast<const openvdb::points::AttributeSet*>(data); const size_t groupIdx = attributeSet->groupOffset(name); if (groupIdx == openvdb::points::AttributeSet::INVALID_POS) return nullptr; return static_cast<HandleT*>(groupHandles[groupIdx]); } } inline FunctionGroup::UniquePtr ax_ingroup(const FunctionOptions& op) { static auto ingroup = [](const AXString* const name, const uint64_t index, void** groupHandles, const void* const leafDataPtr, const void* const data) -> bool { assert(name); assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max())); if (name->size == 0) return false; if (!groupHandles) return false; const std::string nameStr(name->ptr, name->size); const openvdb::points::GroupHandle* handle = groupHandle<openvdb::points::GroupHandle>(nameStr, groupHandles, data); if (handle) return handle->get(static_cast<openvdb::Index>(index)); // If the handle doesn't exist, check to see if any new groups have // been added const codegen_internal::PointLeafLocalData* const leafData = static_cast<const codegen_internal::PointLeafLocalData*>(leafDataPtr); handle = leafData->get(nameStr); return handle ? handle->get(static_cast<openvdb::Index>(index)) : false; }; using InGroup = bool(const AXString* const, const uint64_t, void**, const void* const, const void* const); return FunctionBuilder("_ingroup") .addSignature<InGroup>(ingroup) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::NoAlias) .addParameterAttribute(3, llvm::Attribute::ReadOnly) .addParameterAttribute(3, llvm::Attribute::NoAlias) .addParameterAttribute(4, llvm::Attribute::ReadOnly) .addParameterAttribute(4, llvm::Attribute::NoAlias) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) // @note handle->get can throw, so no unwind. Maybe use getUnsafe? .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for querying point group data") .get(); } inline FunctionGroup::UniquePtr axingroup(const FunctionOptions& op) { static auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { // Pull out parent function arguments llvm::Function* compute = B.GetInsertBlock()->getParent(); verifyContext(compute, "ingroup"); llvm::Value* point_index = extractArgument(compute, "point_index"); llvm::Value* group_handles = extractArgument(compute, "group_handles"); llvm::Value* leaf_data = extractArgument(compute, "leaf_data"); llvm::Value* attribute_set = extractArgument(compute, "attribute_set"); assert(point_index); assert(group_handles); assert(leaf_data); assert(attribute_set); std::vector<llvm::Value*> input(args); input.emplace_back(point_index); input.emplace_back(group_handles); input.emplace_back(leaf_data); input.emplace_back(attribute_set); return ax_ingroup(op)->execute(input, B); }; return FunctionBuilder("ingroup") .addSignature<bool(const AXString* const)>(generate) .addDependency("_ingroup") .setEmbedIR(true) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation( "Return whether or not the current point is " "a member of the given group name. This returns false if the group does " "not exist.") .get(); } inline FunctionGroup::UniquePtr axeditgroup(const FunctionOptions& op) { static auto editgroup = [](const AXString* const name, const uint64_t index, void** groupHandles, void* const leafDataPtr, const void* const data, const bool flag) { assert(name); if (name->size == 0) return; // Get the group handle out of the pre-existing container of handles if they // exist const std::string nameStr(name->ptr, name->size); openvdb::points::GroupWriteHandle* handle = nullptr; if (groupHandles) { handle = groupHandle<openvdb::points::GroupWriteHandle>(nameStr, groupHandles, data); } if (!handle) { codegen_internal::PointLeafLocalData* const leafData = static_cast<codegen_internal::PointLeafLocalData*>(leafDataPtr); // If we are setting membership and the handle doesnt exist, create in in // the set of new data thats being added if (!flag && !leafData->hasGroup(nameStr)) return; handle = leafData->getOrInsert(nameStr); assert(handle); } // set the group membership handle->set(static_cast<openvdb::Index>(index), flag); }; using EditGroup = void(const AXString* const, const uint64_t, void**, void* const, const void* const, const bool); return FunctionBuilder("editgroup") .addSignature<EditGroup>(editgroup) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addParameterAttribute(3, llvm::Attribute::ReadOnly) .addParameterAttribute(4, llvm::Attribute::ReadOnly) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for setting point group data") .get(); } inline FunctionGroup::UniquePtr axaddtogroup(const FunctionOptions& op) { static auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { // Pull out parent function arguments llvm::Function* compute = B.GetInsertBlock()->getParent(); verifyContext(compute, "addtogroup"); llvm::Value* point_index = extractArgument(compute, "point_index"); llvm::Value* group_handles = extractArgument(compute, "group_handles"); llvm::Value* leaf_data = extractArgument(compute, "leaf_data"); llvm::Value* attribute_set = extractArgument(compute, "attribute_set"); assert(point_index); assert(group_handles); assert(leaf_data); assert(attribute_set); std::vector<llvm::Value*> input(args); input.emplace_back(point_index); input.emplace_back(group_handles); input.emplace_back(leaf_data); input.emplace_back(attribute_set); input.emplace_back(llvm::ConstantInt::get(LLVMType<bool>::get(B.getContext()), true)); return axeditgroup(op)->execute(input, B); }; return FunctionBuilder("addtogroup") .addSignature<void(const AXString* const)>(generate) .addDependency("editgroup") .setEmbedIR(true) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Add the current point to the given group " "name, effectively setting its membership to true. If the group does not " "exist, it is implicitly created. This function has no effect if the point " "already belongs to the given group.") .get(); } inline FunctionGroup::UniquePtr axremovefromgroup(const FunctionOptions& op) { static auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { // Pull out parent function arguments llvm::Function* compute = B.GetInsertBlock()->getParent(); verifyContext(compute, "removefromgroup"); llvm::Value* point_index = extractArgument(compute, "point_index"); llvm::Value* group_handles = extractArgument(compute, "group_handles"); llvm::Value* leaf_data = extractArgument(compute, "leaf_data"); llvm::Value* attribute_set = extractArgument(compute, "attribute_set"); assert(point_index); assert(group_handles); assert(leaf_data); assert(attribute_set); std::vector<llvm::Value*> input(args); input.emplace_back(point_index); input.emplace_back(group_handles); input.emplace_back(leaf_data); input.emplace_back(attribute_set); input.emplace_back(llvm::ConstantInt::get(LLVMType<bool>::get(B.getContext()), false)); return axeditgroup(op)->execute(input, B); }; return FunctionBuilder("removefromgroup") .addSignature<void(const AXString* const)>(generate) .addDependency("editgroup") .setEmbedIR(true) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Remove the current point from the " "given group name, effectively setting its membership to false. This " "function has no effect if the group does not exist.") .get(); } inline FunctionGroup::UniquePtr axdeletepoint(const FunctionOptions& op) { static auto generate = [op](const std::vector<llvm::Value*>&, llvm::IRBuilder<>& B) -> llvm::Value* { // args guaranteed to be empty llvm::Constant* loc = llvm::cast<llvm::Constant>(B.CreateGlobalStringPtr("dead")); // char* llvm::Constant* size = LLVMType<AXString::SizeType>::get(B.getContext(), 4); llvm::Value* str = LLVMType<AXString>::get(B.getContext(), loc, size); // Always allocate an AXString here for easier passing to functions // @todo shouldn't need an AXString for char* literals llvm::Value* alloc = B.CreateAlloca(LLVMType<AXString>::get(B.getContext())); B.CreateStore(str, alloc); return axaddtogroup(op)->execute({alloc}, B); }; return FunctionBuilder("deletepoint") .addSignature<void()>(generate) .addDependency("addtogroup") .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setEmbedIR(true) // axaddtogroup needs access to parent function arguments .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Delete the current point from the point set. Note that this does not " "stop AX execution - any additional AX commands will be executed on the " "point and it will remain accessible until the end of execution.") .get(); } inline FunctionGroup::UniquePtr axsetattribute(const FunctionOptions& op) { static auto setattribptr = [](void* attributeHandle, uint64_t index, const auto value) { using ValueType = typename std::remove_const <typename std::remove_pointer <decltype(value)>::type>::type; using AttributeHandleType = openvdb::points::AttributeWriteHandle<ValueType>; assert(attributeHandle); assert(value); assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max())); AttributeHandleType* handle = static_cast<AttributeHandleType*>(attributeHandle); handle->set(static_cast<openvdb::Index>(index), *value); }; static auto setattribstr = [](void* attributeHandle, const uint64_t index, const AXString* value, void* const leafDataPtr) { using AttributeHandleType = openvdb::points::StringAttributeWriteHandle; assert(attributeHandle); assert(value); assert(leafDataPtr); assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max())); const std::string s(value->ptr, value->size); AttributeHandleType* const handle = static_cast<AttributeHandleType*>(attributeHandle); codegen_internal::PointLeafLocalData* const leafData = static_cast<codegen_internal::PointLeafLocalData*>(leafDataPtr); // Check to see if the string exists in the metadata cache. If so, set the string and // remove any new data associated with it, otherwise set the new data if (handle->contains(s)) { handle->set(static_cast<openvdb::Index>(index), s); leafData->removeNewStringData(&(handle->array()), index); } else { leafData->setNewStringData(&(handle->array()), index, s); } }; static auto setattrib = [](void* attributeHandle, uint64_t index, const auto value) { setattribptr(attributeHandle, index, &value); }; using SetAttribD = void(void*, uint64_t, const double); using SetAttribF = void(void*, uint64_t, const float); using SetAttribI64 = void(void*, uint64_t, const int64_t); using SetAttribI32 = void(void*, uint64_t, const int32_t); using SetAttribI16 = void(void*, uint64_t, const int16_t); using SetAttribB = void(void*, uint64_t, const bool); using SetAttribV2D = void(void*, uint64_t, const openvdb::math::Vec2<double>*); using SetAttribV2F = void(void*, uint64_t, const openvdb::math::Vec2<float>*); using SetAttribV2I = void(void*, uint64_t, const openvdb::math::Vec2<int32_t>*); using SetAttribV3D = void(void*, uint64_t, const openvdb::math::Vec3<double>*); using SetAttribV3F = void(void*, uint64_t, const openvdb::math::Vec3<float>*); using SetAttribV3I = void(void*, uint64_t, const openvdb::math::Vec3<int32_t>*); using SetAttribV4D = void(void*, uint64_t, const openvdb::math::Vec4<double>*); using SetAttribV4F = void(void*, uint64_t, const openvdb::math::Vec4<float>*); using SetAttribV4I = void(void*, uint64_t, const openvdb::math::Vec4<int32_t>*); using SetAttribM3D = void(void*, uint64_t, const openvdb::math::Mat3<double>*); using SetAttribM3F = void(void*, uint64_t, const openvdb::math::Mat3<float>*); using SetAttribM4D = void(void*, uint64_t, const openvdb::math::Mat4<double>*); using SetAttribM4F = void(void*, uint64_t, const openvdb::math::Mat4<float>*); using SetAttribStr = void(void*, uint64_t, const AXString*, void* const); return FunctionBuilder("setattribute") .addSignature<SetAttribD>((SetAttribD*)(setattrib)) .addSignature<SetAttribF>((SetAttribF*)(setattrib)) .addSignature<SetAttribI64>((SetAttribI64*)(setattrib)) .addSignature<SetAttribI32>((SetAttribI32*)(setattrib)) .addSignature<SetAttribI16>((SetAttribI16*)(setattrib)) .addSignature<SetAttribB>((SetAttribB*)(setattrib)) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .addSignature<SetAttribV2D>((SetAttribV2D*)(setattribptr)) .addSignature<SetAttribV2F>((SetAttribV2F*)(setattribptr)) .addSignature<SetAttribV2I>((SetAttribV2I*)(setattribptr)) .addSignature<SetAttribV3D>((SetAttribV3D*)(setattribptr)) .addSignature<SetAttribV3F>((SetAttribV3F*)(setattribptr)) .addSignature<SetAttribV3I>((SetAttribV3I*)(setattribptr)) .addSignature<SetAttribV4D>((SetAttribV4D*)(setattribptr)) .addSignature<SetAttribV4F>((SetAttribV4F*)(setattribptr)) .addSignature<SetAttribV4I>((SetAttribV4I*)(setattribptr)) .addSignature<SetAttribM3D>((SetAttribM3D*)(setattribptr)) .addSignature<SetAttribM3F>((SetAttribM3F*)(setattribptr)) .addSignature<SetAttribM4D>((SetAttribM4D*)(setattribptr)) .addSignature<SetAttribM4F>((SetAttribM4F*)(setattribptr)) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .addSignature<SetAttribStr>((SetAttribStr*)(setattribstr)) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addParameterAttribute(3, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for setting the value of a point attribute.") .get(); } inline FunctionGroup::UniquePtr axgetattribute(const FunctionOptions& op) { static auto getattrib = [](void* attributeHandle, uint64_t index, auto value) { using ValueType = typename std::remove_const <typename std::remove_pointer <decltype(value)>::type>::type; // typedef is a read handle. As write handles are derived types this // is okay and lets us define the handle types outside IR for attributes that are // only being read! using AttributeHandleType = openvdb::points::AttributeHandle<ValueType>; assert(value); assert(attributeHandle); assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max())); AttributeHandleType* handle = static_cast<AttributeHandleType*>(attributeHandle); (*value) = handle->get(static_cast<openvdb::Index>(index)); }; static auto getattribstr = [](void* attributeHandle, uint64_t index, AXString* value, const void* const leafDataPtr) { using AttributeHandleType = openvdb::points::StringAttributeHandle; assert(value); assert(attributeHandle); assert(leafDataPtr); assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max())); AttributeHandleType* const handle = static_cast<AttributeHandleType*>(attributeHandle); const codegen_internal::PointLeafLocalData* const leafData = static_cast<const codegen_internal::PointLeafLocalData*>(leafDataPtr); std::string data; if (!leafData->getNewStringData(&(handle->array()), index, data)) { handle->get(data, static_cast<openvdb::Index>(index)); } assert(value->size == static_cast<AXString::SizeType>(data.size())); strcpy(const_cast<char*>(value->ptr), data.c_str()); }; using GetAttribD = void(void*, uint64_t, double*); using GetAttribF = void(void*, uint64_t, float*); using GetAttribI64 = void(void*, uint64_t, int64_t*); using GetAttribI32 = void(void*, uint64_t, int32_t*); using GetAttribI16 = void(void*, uint64_t, int16_t*); using GetAttribB = void(void*, uint64_t, bool*); using GetAttribV2D = void(void*, uint64_t, openvdb::math::Vec2<double>*); using GetAttribV2F = void(void*, uint64_t, openvdb::math::Vec2<float>*); using GetAttribV2I = void(void*, uint64_t, openvdb::math::Vec2<int32_t>*); using GetAttribV3D = void(void*, uint64_t, openvdb::math::Vec3<double>*); using GetAttribV3F = void(void*, uint64_t, openvdb::math::Vec3<float>*); using GetAttribV3I = void(void*, uint64_t, openvdb::math::Vec3<int32_t>*); using GetAttribV4D = void(void*, uint64_t, openvdb::math::Vec4<double>*); using GetAttribV4F = void(void*, uint64_t, openvdb::math::Vec4<float>*); using GetAttribV4I = void(void*, uint64_t, openvdb::math::Vec4<int32_t>*); using GetAttribM3D = void(void*, uint64_t, openvdb::math::Mat3<double>*); using GetAttribM3F = void(void*, uint64_t, openvdb::math::Mat3<float>*); using GetAttribM4D = void(void*, uint64_t, openvdb::math::Mat4<double>*); using GetAttribM4F = void(void*, uint64_t, openvdb::math::Mat4<float>*); using GetAttribStr = void(void*, uint64_t, AXString*, const void* const); return FunctionBuilder("getattribute") .addSignature<GetAttribD>((GetAttribD*)(getattrib)) .addSignature<GetAttribF>((GetAttribF*)(getattrib)) .addSignature<GetAttribI64>((GetAttribI64*)(getattrib)) .addSignature<GetAttribI32>((GetAttribI32*)(getattrib)) .addSignature<GetAttribI16>((GetAttribI16*)(getattrib)) .addSignature<GetAttribB>((GetAttribB*)(getattrib)) .addSignature<GetAttribV2D>((GetAttribV2D*)(getattrib)) .addSignature<GetAttribV2F>((GetAttribV2F*)(getattrib)) .addSignature<GetAttribV2I>((GetAttribV2I*)(getattrib)) .addSignature<GetAttribV3D>((GetAttribV3D*)(getattrib)) .addSignature<GetAttribV3F>((GetAttribV3F*)(getattrib)) .addSignature<GetAttribV3I>((GetAttribV3I*)(getattrib)) .addSignature<GetAttribV4D>((GetAttribV4D*)(getattrib)) .addSignature<GetAttribV4F>((GetAttribV4F*)(getattrib)) .addSignature<GetAttribV4I>((GetAttribV4I*)(getattrib)) .addSignature<GetAttribM3D>((GetAttribM3D*)(getattrib)) .addSignature<GetAttribM3F>((GetAttribM3F*)(getattrib)) .addSignature<GetAttribM4D>((GetAttribM4D*)(getattrib)) .addSignature<GetAttribM4F>((GetAttribM4F*)(getattrib)) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .addSignature<GetAttribStr>((GetAttribStr*)(getattribstr)) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(3, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for getting the value of a point attribute.") .get(); } inline FunctionGroup::UniquePtr axstrattribsize(const FunctionOptions& op) { static auto strattribsize = [](void* attributeHandle, uint64_t index, const void* const leafDataPtr) -> AXString::SizeType { using AttributeHandleType = openvdb::points::StringAttributeHandle; assert(attributeHandle); assert(leafDataPtr); assert(index < static_cast<uint64_t>(std::numeric_limits<openvdb::Index>::max())); const AttributeHandleType* const handle = static_cast<AttributeHandleType*>(attributeHandle); const codegen_internal::PointLeafLocalData* const leafData = static_cast<const codegen_internal::PointLeafLocalData*>(leafDataPtr); std::string data; if (!leafData->getNewStringData(&(handle->array()), index, data)) { handle->get(data, static_cast<openvdb::Index>(index)); } return static_cast<AXString::SizeType>(data.size()); }; using StrAttribSize = AXString::SizeType(void*, uint64_t, const void* const); return FunctionBuilder("strattribsize") .addSignature<StrAttribSize>((StrAttribSize*)(strattribsize)) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for querying the size of a points string attribute") .get(); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// void insertVDBPointFunctions(FunctionRegistry& registry, const FunctionOptions* options) { const bool create = options && !options->mLazyFunctions; auto add = [&](const std::string& name, const FunctionRegistry::ConstructorT creator, const bool internal = false) { if (create) registry.insertAndCreate(name, creator, *options, internal); else registry.insert(name, creator, internal); }; // point functions add("addtogroup", axaddtogroup); add("ingroup", axingroup); add("removefromgroup",axremovefromgroup); add("deletepoint", axdeletepoint); add("_ingroup", ax_ingroup, true); add("editgroup", axeditgroup, true); add("getattribute", axgetattribute, true); add("setattribute", axsetattribute, true); add("strattribsize", axstrattribsize, true); } } // namespace codegen } // namespace ax } // namespace openvdb_version } // namespace openvdb
26,426
C++
42.181372
99
0.654961
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/VolumeComputeGenerator.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/VolumeComputeGenerator.cc #include "VolumeComputeGenerator.h" #include "FunctionRegistry.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../Exceptions.h" #include "../ast/Scanners.h" namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { const std::array<std::string, VolumeKernel::N_ARGS>& VolumeKernel::argumentKeys() { static const std::array<std::string, VolumeKernel::N_ARGS> arguments = {{ "custom_data", "coord_is", "coord_ws", "accessors", "transforms", "write_index", "write_acccessor" }}; return arguments; } std::string VolumeKernel::getDefaultName() { return "ax.compute.voxel"; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// namespace codegen_internal { VolumeComputeGenerator::VolumeComputeGenerator(llvm::Module& module, const FunctionOptions& options, FunctionRegistry& functionRegistry, Logger& logger) : ComputeGenerator(module, options, functionRegistry, logger) {} AttributeRegistry::Ptr VolumeComputeGenerator::generate(const ast::Tree& tree) { llvm::FunctionType* type = llvmFunctionTypeFromSignature<VolumeKernel::Signature>(mContext); mFunction = llvm::Function::Create(type, llvm::Function::ExternalLinkage, VolumeKernel::getDefaultName(), &mModule); // Set up arguments for initial entry llvm::Function::arg_iterator argIter = mFunction->arg_begin(); const auto arguments = VolumeKernel::argumentKeys(); auto keyIter = arguments.cbegin(); for (; argIter != mFunction->arg_end(); ++argIter, ++keyIter) { argIter->setName(*keyIter); } llvm::BasicBlock* entry = llvm::BasicBlock::Create(mContext, "entry_" + VolumeKernel::getDefaultName(), mFunction); mBuilder.SetInsertPoint(entry); // build the attribute registry AttributeRegistry::Ptr registry = AttributeRegistry::create(tree); // Visit all attributes and allocate them in local IR memory - assumes attributes // have been verified by the ax compiler // @note Call all attribute allocs at the start of this block so that llvm folds // them into the function prologue (as a static allocation) SymbolTable* localTable = this->mSymbolTables.getOrInsert(1); // run allocations and update the symbol table for (const AttributeRegistry::AccessData& data : registry->data()) { llvm::Value* value = mBuilder.CreateAlloca(llvmTypeFromToken(data.type(), mContext)); assert(llvm::cast<llvm::AllocaInst>(value)->isStaticAlloca()); localTable->insert(data.tokenname(), value); } // insert getters for read variables for (const AttributeRegistry::AccessData& data : registry->data()) { if (!data.reads()) continue; const std::string token = data.tokenname(); this->getAccessorValue(token, localTable->get(token)); } // full code generation // errors can stop traversal, but dont always, so check the log if (!this->traverse(&tree) || mLog.hasError()) return nullptr; // insert set code std::vector<const AttributeRegistry::AccessData*> write; for (const AttributeRegistry::AccessData& access : registry->data()) { if (access.writes()) write.emplace_back(&access); } if (write.empty()) return registry; // Cache the basic blocks which have been created as we will create // new branches below std::vector<llvm::BasicBlock*> blocks; for (auto block = mFunction->begin(); block != mFunction->end(); ++block) { blocks.emplace_back(&*block); } // insert set voxel calls for (auto& block : blocks) { // Only inset set calls if theres a valid return instruction in this block llvm::Instruction* inst = block->getTerminator(); if (!inst || !llvm::isa<llvm::ReturnInst>(inst)) continue; // remove the old return statement (we'll point to the final return jump) inst->eraseFromParent(); // Set builder to the end of this block mBuilder.SetInsertPoint(&(*block)); for (const AttributeRegistry::AccessData* access : write) { const std::string token = access->tokenname(); llvm::Value* value = localTable->get(token); // Expected to be used more than one (i.e. should never be zero) assert(value->hasNUsesOrMore(1)); // Check to see if this value is still being used - it may have // been cleaned up due to returns. If there's only one use, it's // the original get of this attribute. if (value->hasOneUse()) { // @todo The original get can also be optimized out in this case // this->globals().remove(variable.first); // mModule.getGlobalVariable(variable.first)->eraseFromParent(); continue; } llvm::Value* coordis = extractArgument(mFunction, "coord_is"); llvm::Value* accessIndex = extractArgument(mFunction, "write_index"); llvm::Value* accessor = extractArgument(mFunction, "write_acccessor"); assert(coordis); assert(accessor); assert(accessIndex); llvm::Value* registeredIndex = llvm::cast<llvm::GlobalVariable> (mModule.getOrInsertGlobal(token, LLVMType<int64_t>::get(mContext))); registeredIndex = mBuilder.CreateLoad(registeredIndex); llvm::Value* result = mBuilder.CreateICmpEQ(accessIndex, registeredIndex); result = boolComparison(result, mBuilder); llvm::BasicBlock* thenBlock = llvm::BasicBlock::Create(mContext, "post_assign " + token, mFunction); llvm::BasicBlock* continueBlock = llvm::BasicBlock::Create(mContext, "post_continue", mFunction); mBuilder.CreateCondBr(result, thenBlock, continueBlock); mBuilder.SetInsertPoint(thenBlock); llvm::Type* type = value->getType()->getPointerElementType(); // load the result (if its a scalar) if (type->isIntegerTy() || type->isFloatingPointTy()) { value = mBuilder.CreateLoad(value); } const FunctionGroup* const function = this->getFunction("setvoxel", true); function->execute({accessor, coordis, value}, mBuilder); mBuilder.CreateBr(continueBlock); mBuilder.SetInsertPoint(continueBlock); } mBuilder.CreateRetVoid(); } return registry; } bool VolumeComputeGenerator::visit(const ast::Attribute* node) { const std::string globalName = node->tokenname(); SymbolTable* localTable = this->mSymbolTables.getOrInsert(1); llvm::Value* value = localTable->get(globalName); assert(value); mValues.push(value); return true; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// void VolumeComputeGenerator::getAccessorValue(const std::string& globalName, llvm::Value* location) { std::string name, type; ast::Attribute::nametypeFromToken(globalName, &name, &type); llvm::Value* registeredIndex = llvm::cast<llvm::GlobalVariable> (mModule.getOrInsertGlobal(globalName, LLVMType<int64_t>::get(mContext))); this->globals().insert(globalName, registeredIndex); registeredIndex = mBuilder.CreateLoad(registeredIndex); // index into the void* array of handles and load the value. // The result is a loaded void* value llvm::Value* accessorPtr = extractArgument(mFunction, "accessors"); llvm::Value* transformPtr = extractArgument(mFunction, "transforms"); llvm::Value* coordws = extractArgument(mFunction, "coord_ws"); assert(accessorPtr); assert(transformPtr); assert(coordws); accessorPtr = mBuilder.CreateGEP(accessorPtr, registeredIndex); transformPtr = mBuilder.CreateGEP(transformPtr, registeredIndex); llvm::Value* accessor = mBuilder.CreateLoad(accessorPtr); llvm::Value* transform = mBuilder.CreateLoad(transformPtr); const FunctionGroup* const function = this->getFunction("getvoxel", true); function->execute({accessor, transform, coordws, location}, mBuilder); } llvm::Value* VolumeComputeGenerator::accessorHandleFromToken(const std::string& globalName) { // Visiting an "attribute" - get the volume accessor out of a vector of void pointers // mAttributeHandles is a void pointer to a vector of void pointers (void**) llvm::Value* registeredIndex = llvm::cast<llvm::GlobalVariable> (mModule.getOrInsertGlobal(globalName, LLVMType<int64_t>::get(mContext))); this->globals().insert(globalName, registeredIndex); registeredIndex = mBuilder.CreateLoad(registeredIndex); // index into the void* array of handles and load the value. // The result is a loaded void* value llvm::Value* accessorPtr = extractArgument(mFunction, "accessors"); assert(accessorPtr); accessorPtr = mBuilder.CreateGEP(accessorPtr, registeredIndex); // return loaded void** = void* return mBuilder.CreateLoad(accessorPtr); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// } // namespace codegen_internal } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
9,898
C++
35.127737
99
0.627905
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/SymbolTable.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/SymbolTable.h /// /// @authors Nick Avramoussis /// /// @brief Contains the symbol table which holds mappings of variables names /// to llvm::Values. /// #ifndef OPENVDB_AX_CODEGEN_SYMBOL_TABLE_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_SYMBOL_TABLE_HAS_BEEN_INCLUDED #include <openvdb/version.h> #include <llvm/IR/Value.h> #include <string> #include <unordered_map> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief A symbol table which can be used to represent a single scoped set of /// a programs variables. This is simply an unordered map of strings to /// llvm::Values /// @note Consider using llvm's ValueSymbolTable /// struct SymbolTable { using MapType = std::unordered_map<std::string, llvm::Value*>; SymbolTable() : mMap() {} ~SymbolTable() = default; /// @brief Get a llvm::Value from this symbol table with the given name /// mapping. It it does not exist, a nullptr is returned. /// @param name The name of the variable /// inline llvm::Value* get(const std::string& name) const { const auto iter = mMap.find(name); if (iter == mMap.end()) return nullptr; return iter->second; } /// @brief Returns true if a variable exists in this symbol table with the /// given name. /// @param name The name of the variable /// inline bool exists(const std::string& name) const { const auto iter = mMap.find(name); return (iter != mMap.end()); } /// @brief Insert a variable to this symbol table if it does not exist. Returns /// true if successfully, false if a variable already exists with the /// given name. /// @param name The name of the variable /// @param value The llvm::Value corresponding to this variable /// inline bool insert(const std::string& name, llvm::Value* value) { if (exists(name)) return false; mMap[name] = value; return true; } /// @brief Replace a variable in this symbol table. Returns true if the variable /// previously existed and false if not. In both cases, the variable is /// inserted. /// @param name The name of the variable /// @param value The llvm::Value corresponding to this variable /// inline bool replace(const std::string& name, llvm::Value* value) { const bool existed = exists(name); mMap[name] = value; return existed; } /// @brief Clear all symbols in this table /// inline void clear() { mMap.clear(); } /// @brief Access to the underlying map /// inline const MapType& map() const { return mMap; } private: MapType mMap; }; /// @brief A map of unique ids to symbol tables which can be used to represent local /// variables within a program. New scopes can be added and erased where necessary /// and iterated through using find(). Find assumes that tables are added through /// parented ascending ids. /// /// @note The zero id is used to represent global variables /// @note The block symbol table is fairly simple and currently only supports insertion /// by integer ids. Scopes that exist at the same level are expected to be built /// in isolation and erase and re-create the desired ids where necessary. /// struct SymbolTableBlocks { using MapType = std::map<size_t, SymbolTable>; SymbolTableBlocks() : mTables({{0, SymbolTable()}}) {} ~SymbolTableBlocks() = default; /// @brief Access to the list of global variables which are always accessible /// inline SymbolTable& globals() { return mTables.at(0); } inline const SymbolTable& globals() const { return mTables.at(0); } /// @brief Erase a given scoped indexed SymbolTable from the list of held /// SymbolTables. Returns true if the table previously existed. /// @note If the zero index is supplied, this function throws a runtime error /// /// @param index The SymbolTable index to erase /// inline bool erase(const size_t index) { if (index == 0) { throw std::runtime_error("Attempted to erase global variables which is disallowed."); } const bool existed = (mTables.find(index) != mTables.end()); mTables.erase(index); return existed; } /// @brief Get or insert and get a SymbolTable with a unique index /// /// @param index The SymbolTable index /// inline SymbolTable* getOrInsert(const size_t index) { return &(mTables[index]); } /// @brief Get a SymbolTable with a unique index. If the symbol table does not exist, /// this function throws a runtime error /// /// @param index The SymbolTable index /// inline SymbolTable& get(const size_t index) { auto iter = mTables.find(index); if (iter != mTables.end()) return iter->second; throw std::runtime_error("Attempted to access invalid symbol table with index " + std::to_string(index)); } /// @brief Find a variable within the program starting at a given table index. If /// the given index does not exist, the next descending index is used. /// @note This function assumes that tables have been added in ascending order /// dictating their nested structure. /// /// @param name The variable name to find /// @param startIndex The start SymbolTable index /// inline llvm::Value* find(const std::string& name, const size_t startIndex) const { // Find the lower bound start index and if necessary, decrement into // the first block where the search will be started. Note that this // is safe as the global block 0 will always exist auto it = mTables.lower_bound(startIndex); if (it == mTables.end() || it->first != startIndex) --it; // reverse the iterator (which also make it point to the preceding // value, hence the crement) assert(it != mTables.end()); MapType::const_reverse_iterator iter(++it); for (; iter != mTables.crend(); ++iter) { llvm::Value* value = iter->second.get(name); if (value) return value; } return nullptr; } /// @brief Find a variable within the program starting at the lowest level /// SymbolTable /// /// @param name The variable name to find /// inline llvm::Value* find(const std::string& name) const { return this->find(name, mTables.crbegin()->first); } /// @brief Replace the first occurance of a variable with a given name with a /// replacement value. Returns true if a replacement occured. /// /// @param name The variable name to find and replace /// @param value The llvm::Value to replace /// inline bool replace(const std::string& name, llvm::Value* value) { for (auto it = mTables.rbegin(); it != mTables.rend(); ++it) { if (it->second.get(name)) { it->second.replace(name, value); return true; } } return false; } private: MapType mTables; }; } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_SYMBOL_TABLE_HAS_BEEN_INCLUDED
7,650
C
31.978448
97
0.624183
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/VolumeFunctions.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/VolumeFunctions.cc /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief Contains the function objects that define the functions used in /// volume compute function generation, to be inserted into the FunctionRegistry. /// These define the functions available when operating on volumes. /// Also includes the definitions for the volume value retrieval and setting. /// #include "Functions.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../compiler/CompilerOptions.h" #include "../Exceptions.h" #include <openvdb/version.h> #include <unordered_map> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { namespace { /// @todo Provide more framework for functions such that they can only /// be registered against compatible code generators. inline void verifyContext(const llvm::Function* const F, const std::string& name) { if (!F || F->getName() != "ax.compute.voxel") { OPENVDB_THROW(AXCompilerError, "Function \"" << name << "\" cannot be called for " "the current target. This function only runs on OpenVDB Grids (not OpenVDB Point Grids)."); } } } inline FunctionGroup::UniquePtr axgetvoxelpws(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>&, llvm::IRBuilder<>& B) -> llvm::Value* { // Pull out parent function arguments llvm::Function* compute = B.GetInsertBlock()->getParent(); verifyContext(compute, "getvoxelpws"); llvm::Value* coordws = extractArgument(compute, "coord_ws"); assert(coordws); return coordws; }; return FunctionBuilder("getvoxelpws") .addSignature<openvdb::math::Vec3<float>*()>(generate) .setEmbedIR(true) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the current voxel's position in world space as a vector float.") .get(); } template <size_t Index> inline FunctionGroup::UniquePtr axgetcoord(const FunctionOptions& op) { static_assert(Index <= 2, "Invalid index for axgetcoord"); static auto generate = [](const std::vector<llvm::Value*>&, llvm::IRBuilder<>& B) -> llvm::Value* { // Pull out parent function arguments llvm::Function* compute = B.GetInsertBlock()->getParent(); verifyContext(compute, (Index == 0 ? "getcoordx" : Index == 1 ? "getcoordy" : "getcoordz")); llvm::Value* coordis = extractArgument(compute, "coord_is"); assert(coordis); return B.CreateLoad(B.CreateConstGEP2_64(coordis, 0, Index)); }; return FunctionBuilder((Index == 0 ? "getcoordx" : Index == 1 ? "getcoordy" : "getcoordz")) .addSignature<int()>(generate) .setEmbedIR(true) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation(( Index == 0 ? "Returns the current voxel's X index value in index space as an integer." : Index == 1 ? "Returns the current voxel's Y index value in index space as an integer." : "Returns the current voxel's Z index value in index space as an integer.")) .get(); } inline FunctionGroup::UniquePtr axsetvoxel(const FunctionOptions& op) { static auto setvoxelptr = [](void* accessor, const openvdb::math::Vec3<int32_t>* coord, const auto value) { using ValueType = typename std::remove_const <typename std::remove_pointer <decltype(value)>::type>::type; using GridType = typename openvdb::BoolGrid::ValueConverter<ValueType>::Type; using RootNodeType = typename GridType::TreeType::RootNodeType; using AccessorType = typename GridType::Accessor; assert(accessor); assert(coord); // set value only to avoid changing topology const openvdb::Coord* ijk = reinterpret_cast<const openvdb::Coord*>(coord); AccessorType* const accessorPtr = static_cast<AccessorType*>(accessor); // Check the depth to avoid creating voxel topology for higher levels // @todo As this option is not configurable outside of the executable, we // should be able to avoid this branching by setting the depth as a global const int depth = accessorPtr->getValueDepth(*ijk); if (depth == static_cast<int>(RootNodeType::LEVEL)) { accessorPtr->setValueOnly(*ijk, *value); } else { // If the current depth is not the maximum (i.e voxel/leaf level) then // we're iterating over tiles of an internal node (NodeT0 is the leaf level). // We can't call setValueOnly or other variants as this will forcer voxel // topology to be created. Whilst the VolumeExecutables runs in such a // way that this is safe, it's not desriable; we just want to change the // tile value. There is no easy way to do this; we have to set a new tile // with the same active state. // @warning This code assume that getValueDepth() is always called to force // a node cache. using NodeT1 = typename AccessorType::NodeT1; using NodeT2 = typename AccessorType::NodeT2; if (NodeT1* node = accessorPtr->template getNode<NodeT1>()) { const openvdb::Index index = node->coordToOffset(*ijk); assert(node->isChildMaskOff(index)); node->addTile(index, *value, node->isValueOn(index)); } else if (NodeT2* node = accessorPtr->template getNode<NodeT2>()) { const openvdb::Index index = node->coordToOffset(*ijk); assert(node->isChildMaskOff(index)); node->addTile(index, *value, node->isValueOn(index)); } else { const int level = RootNodeType::LEVEL - depth; accessorPtr->addTile(level, *ijk, *value, accessorPtr->isValueOn(*ijk)); } } }; static auto setvoxelstr = [](void* accessor, const openvdb::math::Vec3<int32_t>* coord, const AXString* value) { const std::string copy(value->ptr, value->size); setvoxelptr(accessor, coord, &copy); }; static auto setvoxel = [](void* accessor, const openvdb::math::Vec3<int32_t>* coord, const auto value) { setvoxelptr(accessor, coord, &value); }; using SetVoxelD = void(void*, const openvdb::math::Vec3<int32_t>*, const double); using SetVoxelF = void(void*, const openvdb::math::Vec3<int32_t>*, const float); using SetVoxelI64 = void(void*, const openvdb::math::Vec3<int32_t>*, const int64_t); using SetVoxelI32 = void(void*, const openvdb::math::Vec3<int32_t>*, const int32_t); using SetVoxelI16 = void(void*, const openvdb::math::Vec3<int32_t>*, const int16_t); using SetVoxelB = void(void*, const openvdb::math::Vec3<int32_t>*, const bool); using SetVoxelV2D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec2<double>*); using SetVoxelV2F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec2<float>*); using SetVoxelV2I = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec2<int32_t>*); using SetVoxelV3D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec3<double>*); using SetVoxelV3F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec3<float>*); using SetVoxelV3I = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec3<int32_t>*); using SetVoxelV4D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec4<double>*); using SetVoxelV4F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec4<float>*); using SetVoxelV4I = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Vec4<int32_t>*); using SetVoxelM3D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat3<double>*); using SetVoxelM3F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat3<float>*); using SetVoxelM4D = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat4<double>*); using SetVoxelM4F = void(void*, const openvdb::math::Vec3<int32_t>*, const openvdb::math::Mat4<float>*); using SetVoxelStr = void(void*, const openvdb::math::Vec3<int32_t>*, const AXString*); return FunctionBuilder("setvoxel") .addSignature<SetVoxelD>((SetVoxelD*)(setvoxel)) .addSignature<SetVoxelF>((SetVoxelF*)(setvoxel)) .addSignature<SetVoxelI64>((SetVoxelI64*)(setvoxel)) .addSignature<SetVoxelI32>((SetVoxelI32*)(setvoxel)) .addSignature<SetVoxelI16>((SetVoxelI16*)(setvoxel)) .addSignature<SetVoxelB>((SetVoxelB*)(setvoxel)) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .addSignature<SetVoxelV2D>((SetVoxelV2D*)(setvoxelptr)) .addSignature<SetVoxelV2F>((SetVoxelV2F*)(setvoxelptr)) .addSignature<SetVoxelV2I>((SetVoxelV2I*)(setvoxelptr)) .addSignature<SetVoxelV3D>((SetVoxelV3D*)(setvoxelptr)) .addSignature<SetVoxelV3F>((SetVoxelV3F*)(setvoxelptr)) .addSignature<SetVoxelV3I>((SetVoxelV3I*)(setvoxelptr)) .addSignature<SetVoxelV4D>((SetVoxelV4D*)(setvoxelptr)) .addSignature<SetVoxelV4F>((SetVoxelV4F*)(setvoxelptr)) .addSignature<SetVoxelV4I>((SetVoxelV4I*)(setvoxelptr)) .addSignature<SetVoxelM3D>((SetVoxelM3D*)(setvoxelptr)) .addSignature<SetVoxelM3F>((SetVoxelM3F*)(setvoxelptr)) .addSignature<SetVoxelM4D>((SetVoxelM4D*)(setvoxelptr)) .addSignature<SetVoxelM4F>((SetVoxelM4F*)(setvoxelptr)) .addSignature<SetVoxelStr>((SetVoxelStr*)(setvoxelstr)) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for setting the value of a voxel.") .get(); } inline FunctionGroup::UniquePtr axgetvoxel(const FunctionOptions& op) { static auto getvoxel = [](void* accessor, void* transform, const openvdb::math::Vec3<float>* wspos, auto value) { using ValueType = typename std::remove_pointer<decltype(value)>::type; using GridType = typename openvdb::BoolGrid::ValueConverter<ValueType>::Type; using AccessorType = typename GridType::Accessor; assert(accessor); assert(wspos); assert(transform); const AccessorType* const accessorPtr = static_cast<const AccessorType*>(accessor); const openvdb::math::Transform* const transformPtr = static_cast<const openvdb::math::Transform*>(transform); const openvdb::Coord coordIS = transformPtr->worldToIndexCellCentered(*wspos); (*value) = accessorPtr->getValue(coordIS); }; // @todo This is inherently flawed as we're not allocating the data in IR when passing // this back. When, in the future, grids can be written to and read from at the // same time we might need to revisit string accesses. static auto getvoxelstr = [](void* accessor, void* transform, const openvdb::math::Vec3<float>* wspos, AXString* value) { using GridType = typename openvdb::BoolGrid::ValueConverter<std::string>::Type; using AccessorType = typename GridType::Accessor; assert(accessor); assert(wspos); assert(transform); const AccessorType* const accessorPtr = static_cast<const AccessorType*>(accessor); const openvdb::math::Transform* const transformPtr = static_cast<const openvdb::math::Transform*>(transform); openvdb::Coord coordIS = transformPtr->worldToIndexCellCentered(*wspos); const std::string& str = accessorPtr->getValue(coordIS); value->ptr = str.c_str(); value->size = static_cast<AXString::SizeType>(str.size()); }; using GetVoxelD = void(void*, void*, const openvdb::math::Vec3<float>*, double*); using GetVoxelF = void(void*, void*, const openvdb::math::Vec3<float>*, float*); using GetVoxelI64 = void(void*, void*, const openvdb::math::Vec3<float>*, int64_t*); using GetVoxelI32 = void(void*, void*, const openvdb::math::Vec3<float>*, int32_t*); using GetVoxelI16 = void(void*, void*, const openvdb::math::Vec3<float>*, int16_t*); using GetVoxelB = void(void*, void*, const openvdb::math::Vec3<float>*, bool*); using GetVoxelV2D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec2<double>*); using GetVoxelV2F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec2<float>*); using GetVoxelV2I = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec2<int32_t>*); using GetVoxelV3D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec3<double>*); using GetVoxelV3F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec3<float>*); using GetVoxelV3I = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec3<int32_t>*); using GetVoxelV4D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec4<double>*); using GetVoxelV4F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec4<float>*); using GetVoxelV4I = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Vec4<int32_t>*); using GetVoxelM3D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat3<double>*); using GetVoxelM3F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*); using GetVoxelM4D = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat4<double>*); using GetVoxelM4F = void(void*, void*, const openvdb::math::Vec3<float>*, openvdb::math::Mat4<float>*); using GetVoxelStr = void(void*, void*, const openvdb::math::Vec3<float>*, AXString*); return FunctionBuilder("getvoxel") .addSignature<GetVoxelD>((GetVoxelD*)(getvoxel)) .addSignature<GetVoxelF>((GetVoxelF*)(getvoxel)) .addSignature<GetVoxelI64>((GetVoxelI64*)(getvoxel)) .addSignature<GetVoxelI32>((GetVoxelI32*)(getvoxel)) .addSignature<GetVoxelI16>((GetVoxelI16*)(getvoxel)) .addSignature<GetVoxelB>((GetVoxelB*)(getvoxel)) .addSignature<GetVoxelV2D>((GetVoxelV2D*)(getvoxel)) .addSignature<GetVoxelV2F>((GetVoxelV2F*)(getvoxel)) .addSignature<GetVoxelV2I>((GetVoxelV2I*)(getvoxel)) .addSignature<GetVoxelV3D>((GetVoxelV3D*)(getvoxel)) .addSignature<GetVoxelV3F>((GetVoxelV3F*)(getvoxel)) .addSignature<GetVoxelV3I>((GetVoxelV3I*)(getvoxel)) .addSignature<GetVoxelV4D>((GetVoxelV4D*)(getvoxel)) .addSignature<GetVoxelV4F>((GetVoxelV4F*)(getvoxel)) .addSignature<GetVoxelV4I>((GetVoxelV4I*)(getvoxel)) .addSignature<GetVoxelM3F>((GetVoxelM3F*)(getvoxel)) .addSignature<GetVoxelM3D>((GetVoxelM3D*)(getvoxel)) .addSignature<GetVoxelM4F>((GetVoxelM4F*)(getvoxel)) .addSignature<GetVoxelM4D>((GetVoxelM4D*)(getvoxel)) .addSignature<GetVoxelStr>((GetVoxelStr*)(getvoxelstr)) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(1, llvm::Attribute::NoAlias) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addParameterAttribute(3, llvm::Attribute::WriteOnly) .addParameterAttribute(3, llvm::Attribute::NoAlias) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for setting the value of a voxel.") .get(); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// void insertVDBVolumeFunctions(FunctionRegistry& registry, const FunctionOptions* options) { const bool create = options && !options->mLazyFunctions; auto add = [&](const std::string& name, const FunctionRegistry::ConstructorT creator, const bool internal = false) { if (create) registry.insertAndCreate(name, creator, *options, internal); else registry.insert(name, creator, internal); }; // volume functions add("getcoordx", axgetcoord<0>); add("getcoordy", axgetcoord<1>); add("getcoordz", axgetcoord<2>); add("getvoxelpws", axgetvoxelpws); add("getvoxel", axgetvoxel, true); add("setvoxel", axsetvoxel, true); } } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
18,118
C++
48.370572
110
0.651176
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Functions.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/Functions.h /// /// @authors Nick Avramoussis, Richard Jones, Francisco Gochez /// /// @brief Contains the function objects that define the functions used in /// compute function generation, to be inserted into the FunctionRegistry. /// These define general purpose functions such as math functions. /// #ifndef OPENVDB_AX_CODEGEN_GENERIC_FUNCTIONS_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_GENERIC_FUNCTIONS_HAS_BEEN_INCLUDED #include "FunctionRegistry.h" #include "../compiler/CompilerOptions.h" #include <openvdb/version.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief Creates a registry with the default set of registered functions /// including math functions, point functions and volume functions /// @param op The current function options /// inline FunctionRegistry::UniquePtr createDefaultRegistry(const FunctionOptions* op = nullptr); /// @brief Populates a function registry with all available "standard" AX /// library function. This primarily consists of all mathematical ops /// on AX containers (scalars, vectors, matrices) and other stl built-ins /// @param reg The function registry to populate /// @param options The current function options /// void insertStandardFunctions(FunctionRegistry& reg, const FunctionOptions* options = nullptr); /// @brief Populates a function registry with all available OpenVDB Point AX /// library function /// @param reg The function registry to populate /// @param options The current function options /// void insertVDBPointFunctions(FunctionRegistry& reg, const FunctionOptions* options = nullptr); /// @brief Populates a function registry with all available OpenVDB Volume AX /// library function /// @param reg The function registry to populate /// @param options The current function options /// void insertVDBVolumeFunctions(FunctionRegistry& reg, const FunctionOptions* options = nullptr); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// inline FunctionRegistry::UniquePtr createDefaultRegistry(const FunctionOptions* op) { FunctionRegistry::UniquePtr registry(new FunctionRegistry); insertStandardFunctions(*registry, op); insertVDBPointFunctions(*registry, op); insertVDBVolumeFunctions(*registry, op); return registry; } } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_GENERIC_FUNCTIONS_HAS_BEEN_INCLUDED
2,720
C
33.884615
95
0.720221
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionRegistry.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/FunctionRegistry.h /// /// @authors Nick Avramoussis /// /// @brief Contains the global function registration definition which /// described all available user front end functions /// #ifndef OPENVDB_AX_CODEGEN_FUNCTION_REGISTRY_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_FUNCTION_REGISTRY_HAS_BEEN_INCLUDED #include "FunctionTypes.h" #include "Types.h" #include "../compiler/CompilerOptions.h" #include <openvdb/version.h> #include <unordered_map> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief The function registry which is used for function code generation. /// Each time a function is visited within the AST, its identifier is used as /// a key into this registry for the corresponding function retrieval and /// execution. Functions can be inserted into the registry using insert() with /// a given identifier and pointer. class FunctionRegistry { public: using ConstructorT = FunctionGroup::UniquePtr(*)(const FunctionOptions&); using Ptr = std::shared_ptr<FunctionRegistry>; using UniquePtr = std::unique_ptr<FunctionRegistry>; /// @brief An object to represent a registered function, storing its /// constructor, a pointer to the function definition and whether it /// should only be available internally (i.e. to a developer, not a user) /// struct RegisteredFunction { /// @brief Constructor /// @param creator The function definition used to create this function /// @param internal Whether the function should be only internally accessible RegisteredFunction(const ConstructorT& creator, const bool internal = false) : mConstructor(creator), mFunction(), mInternal(internal) {} /// @brief Create a function object using this creator of this function /// @param op The current function options inline void create(const FunctionOptions& op) { mFunction = mConstructor(op); } /// @brief Return a pointer to this function definition inline const FunctionGroup* function() const { return mFunction.get(); } /// @brief Check whether this function should be only internally accesible inline bool isInternal() const { return mInternal; } private: const ConstructorT mConstructor; FunctionGroup::Ptr mFunction; const bool mInternal; }; using RegistryMap = std::unordered_map<std::string, RegisteredFunction>; /// @brief Insert and register a function object to a function identifier. /// @note Throws if the identifier is already registered /// /// @param identifier The function identifier to register /// @param creator The function to link to the provided identifier /// @param internal Whether to mark the function as only internally accessible void insert(const std::string& identifier, const ConstructorT creator, const bool internal = false); /// @brief Insert and register a function object to a function identifier. /// @note Throws if the identifier is already registered /// /// @param identifier The function identifier to register /// @param creator The function to link to the provided identifier /// @param op FunctionOptions to pass the function constructor /// @param internal Whether to mark the function as only internally accessible void insertAndCreate(const std::string& identifier, const ConstructorT creator, const FunctionOptions& op, const bool internal = false); /// @brief Return the corresponding function from a provided function identifier /// @note Returns a nullptr if no such function identifier has been /// registered or if the function is marked as internal /// /// @param identifier The function identifier /// @param op FunctionOptions to pass the function constructor /// @param allowInternalAccess Whether to look in the 'internal' functions const FunctionGroup* getOrInsert(const std::string& identifier, const FunctionOptions& op, const bool allowInternalAccess); /// @brief Return the corresponding function from a provided function identifier /// @note Returns a nullptr if no such function identifier has been /// registered or if the function is marked as internal /// /// @param identifier The function identifier /// @param allowInternalAccess Whether to look in the 'internal' functions const FunctionGroup* get(const std::string& identifier, const bool allowInternalAccess) const; /// @brief Force the (re)creations of all function objects for all /// registered functions /// @param op The current function options /// @param verify Checks functions are created and have valid identifiers/symbols void createAll(const FunctionOptions& op, const bool verify = false); /// @brief Return a const reference to the current registry map inline const RegistryMap& map() const { return mMap; } /// @brief Return whether or not the registry is empty inline bool empty() const { return mMap.empty(); } /// @brief Clear the underlying function registry inline void clear() { mMap.clear(); } private: RegistryMap mMap; }; } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_FUNCTION_REGISTRY_HAS_BEEN_INCLUDED
5,696
C
39.404255
87
0.696805
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/ComputeGenerator.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/ComputeGenerator.cc #include "ComputeGenerator.h" #include "FunctionRegistry.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../ast/AST.h" #include "../ast/Tokens.h" #include "../compiler/CustomData.h" #include "../Exceptions.h" #include <llvm/ADT/SmallVector.h> #include <llvm/IR/CallingConv.h> #include <llvm/IR/Constants.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/InlineAsm.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Intrinsics.h> #include <llvm/Pass.h> #include <llvm/Support/MathExtras.h> #include <llvm/Support/raw_os_ostream.h> #include <llvm/Transforms/Utils/BuildLibCalls.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { namespace { inline void printType(const llvm::Type* type, llvm::raw_os_ostream& stream, const bool axTypes) { const ast::tokens::CoreType token = axTypes ? tokenFromLLVMType(type) : ast::tokens::UNKNOWN; if (token == ast::tokens::UNKNOWN) type->print(stream); else stream << ast::tokens::typeStringFromToken(token); } inline void printTypes(llvm::raw_os_ostream& stream, const std::vector<llvm::Type*>& types, const std::vector<const char*>& names = {}, const std::string sep = "; ", const bool axTypes = true) { if (types.empty()) return; auto typeIter = types.cbegin(); std::vector<const char*>::const_iterator nameIter; if (!names.empty()) nameIter = names.cbegin(); for (; typeIter != types.cend() - 1; ++typeIter) { printType(*typeIter, stream, axTypes); if (!names.empty() && nameIter != names.cend()) { if (*nameIter && (*nameIter)[0] != '\0') { stream << ' ' << *nameIter; } ++nameIter; } stream << sep; } printType(*typeIter, stream, axTypes); if (!names.empty() && nameIter != names.cend()) { if (*nameIter && (*nameIter)[0] != '\0') { stream << ' ' << *nameIter; } } } } const std::array<std::string, ComputeKernel::N_ARGS>& ComputeKernel::getArgumentKeys() { static const std::array<std::string, ComputeKernel::N_ARGS> arguments = { { "custom_data" } }; return arguments; } std::string ComputeKernel::getDefaultName() { return "ax.compute"; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// namespace codegen_internal { ComputeGenerator::ComputeGenerator(llvm::Module& module, const FunctionOptions& options, FunctionRegistry& functionRegistry, Logger& logger) : mModule(module) , mContext(module.getContext()) , mBuilder(module.getContext()) , mValues() , mBreakContinueStack() , mScopeIndex(1) , mSymbolTables() , mFunction(nullptr) , mOptions(options) , mLog(logger) , mFunctionRegistry(functionRegistry) {} bool ComputeGenerator::generate(const ast::Tree& tree) { llvm::FunctionType* type = llvmFunctionTypeFromSignature<ComputeKernel::Signature>(mContext); mFunction = llvm::Function::Create(type, llvm::Function::ExternalLinkage, ComputeKernel::getDefaultName(), &mModule); // Set up arguments for initial entry llvm::Function::arg_iterator argIter = mFunction->arg_begin(); const auto arguments = ComputeKernel::getArgumentKeys(); auto keyIter = arguments.cbegin(); for (; argIter != mFunction->arg_end(); ++argIter, ++keyIter) { argIter->setName(*keyIter); } llvm::BasicBlock* entry = llvm::BasicBlock::Create(mContext, "entry_" + ComputeKernel::getDefaultName(), mFunction); mBuilder.SetInsertPoint(entry); // if traverse is false, log should have error, but can error // without stopping traversal, so check both return this->traverse(&tree) && !mLog.hasError(); } bool ComputeGenerator::visit(const ast::Block* block) { mScopeIndex++; // traverse the contents of the block const size_t children = block->children(); for (size_t i = 0; i < children; ++i) { if (!this->traverse(block->child(i)) && mLog.atErrorLimit()) { return false; } // reset the value stack for each statement mValues = std::stack<llvm::Value*>(); } mSymbolTables.erase(mScopeIndex); mScopeIndex--; return true; } bool ComputeGenerator::visit(const ast::CommaOperator* comma) { // traverse the contents of the comma expression const size_t children = comma->children(); llvm::Value* value = nullptr; bool hasErrored = false; for (size_t i = 0; i < children; ++i) { if (this->traverse(comma->child(i))) { value = mValues.top(); mValues.pop(); } else { if (mLog.atErrorLimit()) return false; hasErrored = true; } } // only keep the last value if (!value || hasErrored) return false; mValues.push(value); return true; } bool ComputeGenerator::visit(const ast::ConditionalStatement* cond) { llvm::BasicBlock* postIfBlock = llvm::BasicBlock::Create(mContext, "block", mFunction); llvm::BasicBlock* thenBlock = llvm::BasicBlock::Create(mContext, "then", mFunction); const bool hasElse = cond->hasFalse(); llvm::BasicBlock* elseBlock = hasElse ? llvm::BasicBlock::Create(mContext, "else", mFunction) : postIfBlock; // generate conditional if (this->traverse(cond->condition())) { llvm::Value* condition = mValues.top(); mValues.pop(); if (condition->getType()->isPointerTy()) { condition = mBuilder.CreateLoad(condition); } llvm::Type* conditionType = condition->getType(); // check the type of the condition branch is bool-convertable if (conditionType->isFloatingPointTy() || conditionType->isIntegerTy()) { condition = boolComparison(condition, mBuilder); mBuilder.CreateCondBr(condition, thenBlock, elseBlock); } else { if (!mLog.error("cannot convert non-scalar type to bool in condition", cond->condition())) return false; } } else if (mLog.atErrorLimit()) return false; // generate if-then branch mBuilder.SetInsertPoint(thenBlock); if (!this->traverse(cond->trueBranch()) && mLog.atErrorLimit()) return false; mBuilder.CreateBr(postIfBlock); if (hasElse) { // generate else-then branch mBuilder.SetInsertPoint(elseBlock); if (!this->traverse(cond->falseBranch()) && mLog.atErrorLimit()) return false; mBuilder.CreateBr(postIfBlock); } // reset to continue block mBuilder.SetInsertPoint(postIfBlock); // reset the value stack mValues = std::stack<llvm::Value*>(); return true; } bool ComputeGenerator::visit(const ast::TernaryOperator* tern) { llvm::BasicBlock* trueBlock = llvm::BasicBlock::Create(mContext, "ternary_true", mFunction); llvm::BasicBlock* falseBlock = llvm::BasicBlock::Create(mContext, "ternary_false", mFunction); llvm::BasicBlock* returnBlock = llvm::BasicBlock::Create(mContext, "ternary_return", mFunction); llvm::Value* trueValue = nullptr; llvm::Type* trueType = nullptr; bool truePtr = false; // generate conditional bool conditionSuccess = this->traverse(tern->condition()); if (conditionSuccess) { // get the condition trueValue = mValues.top(); mValues.pop(); assert(trueValue); trueType = trueValue->getType(); truePtr = trueType->isPointerTy(); llvm::Type* conditionType = truePtr ? trueType->getPointerElementType() : trueType; llvm::Value* boolCondition = nullptr; // check the type of the condition branch is bool-convertable if (conditionType->isFloatingPointTy() || conditionType->isIntegerTy()) { boolCondition = truePtr ? boolComparison(mBuilder.CreateLoad(trueValue), mBuilder) : boolComparison(trueValue, mBuilder); mBuilder.CreateCondBr(boolCondition, trueBlock, falseBlock); } else { if (!mLog.error("cannot convert non-scalar type to bool in condition", tern->condition())) return false; conditionSuccess = false; } } else if (mLog.atErrorLimit()) return false; // generate true branch, if it exists otherwise take condition as true value mBuilder.SetInsertPoint(trueBlock); bool trueSuccess = conditionSuccess; if (tern->hasTrue()) { trueSuccess = this->traverse(tern->trueBranch()); if (trueSuccess) { trueValue = mValues.top(); mValues.pop();// get true value from true expression // update true type details trueType = trueValue->getType(); } else if (mLog.atErrorLimit()) return false; } llvm::BranchInst* trueBranch = mBuilder.CreateBr(returnBlock); // generate false branch mBuilder.SetInsertPoint(falseBlock); bool falseSuccess = this->traverse(tern->falseBranch()); // even if the condition isnt successful but the others are, we continue to code gen to find type errors in branches if (!(trueSuccess && falseSuccess)) return false; llvm::BranchInst* falseBranch = mBuilder.CreateBr(returnBlock); llvm::Value* falseValue = mValues.top(); mValues.pop(); llvm::Type* falseType = falseValue->getType(); assert(trueType); // if both variables of same type do no casting or loading if (trueType != falseType) { // get the (contained) types of the expressions truePtr = trueType->isPointerTy(); if (truePtr) trueType = trueType->getPointerElementType(); const bool falsePtr = falseType->isPointerTy(); if (falsePtr) falseType = falseType->getPointerElementType(); // if same contained type but one needs loading // can only have one pointer, one not, for scalars right now, i.e. no loaded arrays or strings if (trueType == falseType) { assert(!(truePtr && falsePtr)); if (truePtr) { mBuilder.SetInsertPoint(trueBranch); trueValue = mBuilder.CreateLoad(trueValue); } else { mBuilder.SetInsertPoint(falseBranch); falseValue = mBuilder.CreateLoad(falseValue); } } else { // needs casting // get type for return llvm::Type* returnType = nullptr; const bool trueScalar = (trueType->isIntegerTy() || trueType->isFloatingPointTy()); if (trueScalar && (falseType->isIntegerTy() || falseType->isFloatingPointTy())) { assert(trueType != falseType); // SCALAR_SCALAR returnType = typePrecedence(trueType, falseType); // always load scalars here, even if they are the correct type mBuilder.SetInsertPoint(trueBranch); if (truePtr) trueValue = mBuilder.CreateLoad(trueValue); trueValue = arithmeticConversion(trueValue, returnType, mBuilder); mBuilder.SetInsertPoint(falseBranch); if (falsePtr) falseValue = mBuilder.CreateLoad(falseValue); falseValue = arithmeticConversion(falseValue, returnType, mBuilder); } else if (trueType->isArrayTy() && falseType->isArrayTy() && (trueType->getArrayNumElements() == falseType->getArrayNumElements())) { // ARRAY_ARRAY trueType = trueType->getArrayElementType(); falseType = falseType->getArrayElementType(); returnType = typePrecedence(trueType, falseType); if (trueType != returnType) { mBuilder.SetInsertPoint(trueBranch); trueValue = arrayCast(trueValue, returnType, mBuilder); } else if (falseType != returnType) { mBuilder.SetInsertPoint(falseBranch); falseValue = arrayCast(falseValue, returnType, mBuilder); } } else if (trueScalar && falseType->isArrayTy()) { // SCALAR_ARRAY returnType = typePrecedence(trueType, falseType->getArrayElementType()); mBuilder.SetInsertPoint(trueBranch); if (truePtr) trueValue = mBuilder.CreateLoad(trueValue); trueValue = arithmeticConversion(trueValue, returnType, mBuilder); const size_t arraySize = falseType->getArrayNumElements(); if (arraySize == 9 || arraySize == 16) { trueValue = scalarToMatrix(trueValue, mBuilder, arraySize == 9 ? 3 : 4); } else { trueValue = arrayPack(trueValue, mBuilder, arraySize); } if (falseType->getArrayElementType() != returnType) { mBuilder.SetInsertPoint(falseBranch); falseValue = arrayCast(falseValue, returnType, mBuilder); } } else if (trueType->isArrayTy() && (falseType->isIntegerTy() || falseType->isFloatingPointTy())) { // ARRAY_SCALAR returnType = typePrecedence(trueType->getArrayElementType(), falseType); if (trueType->getArrayElementType() != returnType) { mBuilder.SetInsertPoint(trueBranch); trueValue = arrayCast(trueValue, returnType, mBuilder); } mBuilder.SetInsertPoint(falseBranch); if (falsePtr) falseValue = mBuilder.CreateLoad(falseValue); falseValue = arithmeticConversion(falseValue, returnType, mBuilder); const size_t arraySize = trueType->getArrayNumElements(); if (arraySize == 9 || arraySize == 16) { falseValue = scalarToMatrix(falseValue, mBuilder, arraySize == 9 ? 3 : 4); } else { falseValue = arrayPack(falseValue, mBuilder, arraySize); } } else { mLog.error("unsupported implicit cast in ternary operation", tern->hasTrue() ? tern->trueBranch() : tern->falseBranch()); return false; } } } else if (trueType->isVoidTy() && falseType->isVoidTy()) { // void type ternary acts like if-else statement // push void value to stop use of return from this expression mBuilder.SetInsertPoint(returnBlock); mValues.push(falseValue); return conditionSuccess && trueSuccess && falseSuccess; } // reset to continue block mBuilder.SetInsertPoint(returnBlock); llvm::PHINode* ternary = mBuilder.CreatePHI(trueValue->getType(), 2, "ternary"); // if nesting branches the blocks for true and false branches may have been updated // so get these again rather than reusing trueBlock/falseBlock ternary->addIncoming(trueValue, trueBranch->getParent()); ternary->addIncoming(falseValue, falseBranch->getParent()); mValues.push(ternary); return conditionSuccess && trueSuccess && falseSuccess; } bool ComputeGenerator::visit(const ast::Loop* loop) { mScopeIndex++; llvm::BasicBlock* postLoopBlock = llvm::BasicBlock::Create(mContext, "block", mFunction); llvm::BasicBlock* conditionBlock = llvm::BasicBlock::Create(mContext, "loop_condition", mFunction); llvm::BasicBlock* bodyBlock = llvm::BasicBlock::Create(mContext, "loop_body", mFunction); llvm::BasicBlock* postBodyBlock = conditionBlock; const ast::tokens::LoopToken loopType = loop->loopType(); assert((loopType == ast::tokens::LoopToken::FOR || loopType == ast::tokens::LoopToken::WHILE || loopType == ast::tokens::LoopToken::DO) && "Unsupported loop type"); if (loopType == ast::tokens::LoopToken::FOR) { // init -> condition -> body -> iter -> condition ... continue // generate initial statement if (loop->hasInit()) { if (!this->traverse(loop->initial()) && mLog.atErrorLimit()) return false; // reset the value stack mValues = std::stack<llvm::Value*>(); } mBuilder.CreateBr(conditionBlock); // generate iteration if (loop->hasIter()) { llvm::BasicBlock* iterBlock = llvm::BasicBlock::Create(mContext, "loop_iteration", mFunction); postBodyBlock = iterBlock; mBuilder.SetInsertPoint(iterBlock); if (!this->traverse(loop->iteration()) && mLog.atErrorLimit()) return false; mBuilder.CreateBr(conditionBlock); } } else if (loopType == ast::tokens::LoopToken::DO) { // body -> condition -> body -> condition ... continue mBuilder.CreateBr(bodyBlock); } else if (loopType == ast::tokens::LoopToken::WHILE) { // condition -> body -> condition ... continue mBuilder.CreateBr(conditionBlock); } // store the destinations for break and continue mBreakContinueStack.push({postLoopBlock, postBodyBlock}); // generate loop body mBuilder.SetInsertPoint(bodyBlock); if (!this->traverse(loop->body()) && mLog.atErrorLimit()) return false; mBuilder.CreateBr(postBodyBlock); // generate condition mBuilder.SetInsertPoint(conditionBlock); if (this->traverse(loop->condition())) { llvm::Value* condition = mValues.top(); mValues.pop(); if (condition->getType()->isPointerTy()) { condition = mBuilder.CreateLoad(condition); } llvm::Type* conditionType = condition->getType(); // check the type of the condition branch is bool-convertable if (conditionType->isFloatingPointTy() || conditionType->isIntegerTy()) { condition = boolComparison(condition, mBuilder); mBuilder.CreateCondBr(condition, bodyBlock, postLoopBlock); } else { if (!mLog.error("cannot convert non-scalar type to bool in condition", loop->condition())) return false; } // reset the value stack mValues = std::stack<llvm::Value*>(); } else if (mLog.atErrorLimit()) return false; // reset to post loop block mBuilder.SetInsertPoint(postLoopBlock); // discard break and continue mBreakContinueStack.pop(); // remove the symbol table created in this scope mSymbolTables.erase(mScopeIndex); mScopeIndex--; // reset the value stack mValues = std::stack<llvm::Value*>(); return true; } bool ComputeGenerator::visit(const ast::Keyword* node) { const ast::tokens::KeywordToken keyw = node->keyword(); assert((keyw == ast::tokens::KeywordToken::RETURN || keyw == ast::tokens::KeywordToken::BREAK || keyw == ast::tokens::KeywordToken::CONTINUE) && "Unsupported keyword"); if (keyw == ast::tokens::KeywordToken::RETURN) { mBuilder.CreateRetVoid(); } else if (keyw == ast::tokens::KeywordToken::BREAK || keyw == ast::tokens::KeywordToken::CONTINUE) { // find the parent loop, if it exists const ast::Node* child = node; const ast::Node* parentLoop = node->parent(); while (parentLoop) { if (parentLoop->nodetype() == ast::Node::NodeType::LoopNode) { break; } child = parentLoop; parentLoop = child->parent(); } if (!parentLoop) { if (!mLog.error("keyword \"" + ast::tokens::keywordNameFromToken(keyw) + "\" used outside of loop.", node)) return false; } else { const std::pair<llvm::BasicBlock*, llvm::BasicBlock*> breakContinue = mBreakContinueStack.top(); if (keyw == ast::tokens::KeywordToken::BREAK) { assert(breakContinue.first); mBuilder.CreateBr(breakContinue.first); } else if (keyw == ast::tokens::KeywordToken::CONTINUE) { assert(breakContinue.second); mBuilder.CreateBr(breakContinue.second); } } } llvm::BasicBlock* nullBlock = llvm::BasicBlock::Create(mContext, "null", mFunction); // insert all remaining instructions in scope into a null block // this will incorporate all instructions that follow until new insert point is set mBuilder.SetInsertPoint(nullBlock); return true; } bool ComputeGenerator::visit(const ast::BinaryOperator* node) { openvdb::ax::ast::tokens::OperatorToken opToken = node->operation(); // if AND or OR, need to handle short-circuiting if (opToken == openvdb::ax::ast::tokens::OperatorToken::AND || opToken == openvdb::ax::ast::tokens::OperatorToken::OR) { llvm::BranchInst* lhsBranch = nullptr; llvm::BasicBlock* rhsBlock = llvm::BasicBlock::Create(mContext, "binary_rhs", mFunction); llvm::BasicBlock* returnBlock = llvm::BasicBlock::Create(mContext, "binary_return", mFunction); llvm::Value* lhs = nullptr; bool lhsSuccess = this->traverse(node->lhs()); if (lhsSuccess) { lhs = mValues.top(); mValues.pop(); llvm::Type* lhsType = lhs->getType(); if (lhsType->isPointerTy()) { lhs = mBuilder.CreateLoad(lhs); lhsType = lhsType->getPointerElementType(); } if (lhsType->isFloatingPointTy() || lhsType->isIntegerTy()) { lhs = boolComparison(lhs, mBuilder); if (opToken == openvdb::ax::ast::tokens::OperatorToken::AND) { lhsBranch = mBuilder.CreateCondBr(lhs, rhsBlock, returnBlock); } else { lhsBranch = mBuilder.CreateCondBr(lhs, returnBlock, rhsBlock); } } else { mLog.error("cannot convert non-scalar lhs to bool", node->lhs()); lhsSuccess = false; } } if (mLog.atErrorLimit()) return false; mBuilder.SetInsertPoint(rhsBlock); bool rhsSuccess = this->traverse(node->rhs()); if (rhsSuccess) { llvm::Value* rhs = mValues.top(); mValues.pop(); llvm::Type* rhsType = rhs->getType(); if (rhsType->isPointerTy()) { rhs = mBuilder.CreateLoad(rhs); rhsType = rhsType->getPointerElementType(); } if (rhsType->isFloatingPointTy() || rhsType->isIntegerTy()) { rhs = boolComparison(rhs, mBuilder); llvm::BranchInst* rhsBranch = mBuilder.CreateBr(returnBlock); mBuilder.SetInsertPoint(returnBlock); if (lhsBranch) {// i.e. lhs was successful assert(rhs && lhs); llvm::PHINode* result = mBuilder.CreatePHI(LLVMType<bool>::get(mContext), 2, "binary_op"); result->addIncoming(lhs, lhsBranch->getParent()); result->addIncoming(rhs, rhsBranch->getParent()); mValues.push(result); } } else { mLog.error("cannot convert non-scalar rhs to bool", node->rhs()); rhsSuccess = false; } } return lhsSuccess && rhsSuccess; } else { llvm::Value* lhs = nullptr; if (this->traverse(node->lhs())) { lhs = mValues.top(); mValues.pop(); } else if (mLog.atErrorLimit()) return false; llvm::Value* rhs = nullptr; if (this->traverse(node->rhs())) { rhs = mValues.top(); mValues.pop(); } else if (mLog.atErrorLimit()) return false; llvm::Value* result = nullptr; if (!(lhs && rhs) || !this->binaryExpression(result, lhs, rhs, node->operation(), node)) return false; if (result) { mValues.push(result); } } return true; } bool ComputeGenerator::visit(const ast::UnaryOperator* node) { // If the unary operation is a +, keep the value ptr on the stack and // continue (avoid any new allocations or unecessary loads) const ast::tokens::OperatorToken token = node->operation(); if (token == ast::tokens::PLUS) return true; if (token != ast::tokens::MINUS && token != ast::tokens::BITNOT && token != ast::tokens::NOT) { mLog.error("unrecognised unary operator \"" + ast::tokens::operatorNameFromToken(token) + "\"", node); return false; } // unary operator uses default traversal so value should be on the stack llvm::Value* value = mValues.top(); llvm::Type* type = value->getType(); if (type->isPointerTy()) { type = type->getPointerElementType(); if (type->isIntegerTy() || type->isFloatingPointTy()) { value = mBuilder.CreateLoad(value); } } llvm::Value* result = nullptr; if (type->isIntegerTy()) { if (token == ast::tokens::NOT) { if (type->isIntegerTy(1)) result = mBuilder.CreateICmpEQ(value, llvm::ConstantInt::get(type, 0)); else result = mBuilder.CreateICmpEQ(value, llvm::ConstantInt::getSigned(type, 0)); } else { // if bool, cast to int32 for unary minus and bitnot if (type->isIntegerTy(1)) { type = LLVMType<int32_t>::get(mContext); value = arithmeticConversion(value, type, mBuilder); } if (token == ast::tokens::MINUS) result = mBuilder.CreateNeg(value); else if (token == ast::tokens::BITNOT) result = mBuilder.CreateNot(value); } } else if (type->isFloatingPointTy()) { if (token == ast::tokens::MINUS) result = mBuilder.CreateFNeg(value); else if (token == ast::tokens::NOT) result = mBuilder.CreateFCmpOEQ(value, llvm::ConstantFP::get(type, 0)); else if (token == ast::tokens::BITNOT) { mLog.error("unable to perform operation \"" + ast::tokens::operatorNameFromToken(token) + "\" on floating point values", node); return false; } } else if (type->isArrayTy()) { type = type->getArrayElementType(); std::vector<llvm::Value*> elements; arrayUnpack(value, elements, mBuilder, /*load*/true); assert(elements.size() > 0); if (type->isIntegerTy()) { if (token == ast::tokens::MINUS) { for (llvm::Value*& element : elements) { element = mBuilder.CreateNeg(element); } } else if (token == ast::tokens::NOT) { for (llvm::Value*& element : elements) { element = mBuilder.CreateICmpEQ(element, llvm::ConstantInt::getSigned(type, 0)); } } else if (token == ast::tokens::BITNOT) { for (llvm::Value*& element : elements) { element = mBuilder.CreateNot(element); } } } else if (type->isFloatingPointTy()) { if (token == ast::tokens::MINUS) { for (llvm::Value*& element : elements) { element = mBuilder.CreateFNeg(element); } } else { //@todo support NOT? mLog.error("unable to perform operation \"" + ast::tokens::operatorNameFromToken(token) + "\" on arrays/vectors", node); return false; } } else { mLog.error("unrecognised array element type", node); return false; } result = arrayPack(elements, mBuilder); } else { mLog.error("value is not a scalar or vector", node); return false; } assert(result); mValues.pop(); mValues.push(result); return true; } bool ComputeGenerator::visit(const ast::AssignExpression* assign) { // default traversal, should have rhs and lhs on stack // leave LHS on stack llvm::Value* rhs = mValues.top(); mValues.pop(); llvm::Value* lhs = mValues.top(); llvm::Type* rhsType = rhs->getType(); if (assign->isCompound()) { llvm::Value* rhsValue = nullptr; if (!this->binaryExpression(rhsValue, lhs, rhs, assign->operation(), assign)) return false; assert(rhsValue); rhs = rhsValue; rhsType = rhs->getType(); } // rhs must be loaded for assignExpression() if it's a scalar if (rhsType->isPointerTy()) { rhsType = rhsType->getPointerElementType(); if (rhsType->isIntegerTy() || rhsType->isFloatingPointTy()) { rhs = mBuilder.CreateLoad(rhs); } } if (!this->assignExpression(lhs, rhs, assign)) return false; return true; } bool ComputeGenerator::visit(const ast::Crement* node) { llvm::Value* value = mValues.top(); if (!value->getType()->isPointerTy()) { mLog.error("unable to assign to an rvalue", node); return false; } llvm::Value* rvalue = mBuilder.CreateLoad(value); llvm::Type* type = rvalue->getType(); if (type->isIntegerTy(1) || (!type->isIntegerTy() && !type->isFloatingPointTy())) { mLog.error("variable is an unsupported type for " "crement. Must be a non-boolean scalar", node); return false; } else { llvm::Value* crement = nullptr; assert((node->increment() || node->decrement()) && "unrecognised crement operation"); if (node->increment()) crement = LLVMType<int32_t>::get(mContext, 1); else if (node->decrement()) crement = LLVMType<int32_t>::get(mContext, -1); crement = arithmeticConversion(crement, type, mBuilder); if (type->isIntegerTy()) crement = mBuilder.CreateAdd(rvalue, crement); if (type->isFloatingPointTy()) crement = mBuilder.CreateFAdd(rvalue, crement); mBuilder.CreateStore(crement, value); // decide what to put on the expression stack } mValues.pop(); if (node->post()) mValues.push(rvalue); else mValues.push(value); return true; } bool ComputeGenerator::visit(const ast::FunctionCall* node) { const FunctionGroup* const function = this->getFunction(node->name()); if (!function) { mLog.error("unable to locate function \"" + node->name() + "\"", node); return false; } else { const size_t args = node->children(); assert(mValues.size() >= args); // initialize arguments. scalars are always passed by value, arrays // and strings always by pointer std::vector<llvm::Value*> arguments; arguments.resize(args); for (auto r = arguments.rbegin(); r != arguments.rend(); ++r) { llvm::Value* arg = mValues.top(); mValues.pop(); llvm::Type* type = arg->getType(); if (type->isPointerTy()) { type = type->getPointerElementType(); if (type->isIntegerTy() || type->isFloatingPointTy()) { // pass by value arg = mBuilder.CreateLoad(arg); } } else { // arrays should never be loaded assert(!type->isArrayTy() && type != LLVMType<AXString>::get(mContext)); if (type->isIntegerTy() || type->isFloatingPointTy()) { /*pass by value*/ } } *r = arg; } std::vector<llvm::Type*> inputTypes; valuesToTypes(arguments, inputTypes); Function::SignatureMatch match; const Function::Ptr target = function->match(inputTypes, mContext, &match); if (!target) { assert(!function->list().empty() && "FunctionGroup has no function declarations"); std::ostringstream os; if (match == Function::SignatureMatch::None) { os << "wrong number of arguments. \"" << node->name() << "\"" << " was called with: ("; llvm::raw_os_ostream stream(os); printTypes(stream, inputTypes); stream << ")"; } else { // match == Function::SignatureMatch::Size os << "no matching function for "; printSignature(os, inputTypes, LLVMType<void>::get(mContext), node->name().c_str(), {}, true); } os << " \ncandidates are: "; for (const auto& sig : function->list()) { os << std::endl; sig->print(mContext, os, node->name().c_str()); } mLog.error(os.str(), node); return false; } else { llvm::Value* result = nullptr; if (match == Function::SignatureMatch::Implicit) { if (!mLog.warning("implicit conversion in function call", node)) return false; result = target->call(arguments, mBuilder, /*cast=*/true); } else { // match == Function::SignatureMatch::Explicit result = target->call(arguments, mBuilder, /*cast=*/false); } assert(result && "Function has been invoked with no valid llvm Value return"); mValues.push(result); } } return true; } bool ComputeGenerator::visit(const ast::Cast* node) { llvm::Value* value = mValues.top(); mValues.pop(); llvm::Type* type = value->getType()->isPointerTy() ? value->getType()->getPointerElementType() : value->getType(); if (!type->isIntegerTy() && !type->isFloatingPointTy()) { mLog.error("unable to cast non scalar values", node); return false; } else { // If the value to cast is already the correct type, return llvm::Type* targetType = llvmTypeFromToken(node->type(), mContext); if (type == targetType) return true; if (value->getType()->isPointerTy()) { value = mBuilder.CreateLoad(value); } if (targetType->isIntegerTy(1)) { // if target is bool, perform standard boolean conversion (*not* truncation). value = boolComparison(value, mBuilder); assert(value->getType()->isIntegerTy(1)); } else { value = arithmeticConversion(value, targetType, mBuilder); } mValues.push(value); } return true; } bool ComputeGenerator::visit(const ast::DeclareLocal* node) { // create storage for the local value. llvm::Type* type = llvmTypeFromToken(node->type(), mContext); llvm::Value* value = insertStaticAlloca(mBuilder, type); // for strings, make sure we correctly initialize to the empty string. // strings are the only variable type that are currently default allocated // otherwise you can run into issues with binary operands if (node->type() == ast::tokens::STRING) { llvm::Value* loc = mBuilder.CreateGlobalStringPtr(""); // char* llvm::Constant* constLoc = llvm::cast<llvm::Constant>(loc); llvm::Constant* size = LLVMType<AXString::SizeType>::get (mContext, static_cast<AXString::SizeType>(0)); llvm::Value* constStr = LLVMType<AXString>::get(mContext, constLoc, size); mBuilder.CreateStore(constStr, value); } SymbolTable* current = mSymbolTables.getOrInsert(mScopeIndex); const std::string& name = node->local()->name(); if (!current->insert(name, value)) { mLog.error("local variable \"" + name + "\" has already been declared", node); return false; } if (mSymbolTables.find(name, mScopeIndex - 1)) { if (!mLog.warning("declaration of variable \"" + name + "\" shadows a previous declaration", node)) return false; } // do this to ensure all AST nodes are visited // shouldnt ever fail if (this->traverse(node->local())) { value = mValues.top(); mValues.pop(); } else if (mLog.atErrorLimit()) return false; if (node->hasInit()) { if (this->traverse(node->init())) { llvm::Value* init = mValues.top(); mValues.pop(); llvm::Type* initType = init->getType(); if (initType->isPointerTy()) { initType = initType->getPointerElementType(); if (initType->isIntegerTy() || initType->isFloatingPointTy()) { init = mBuilder.CreateLoad(init); } } if (!this->assignExpression(value, init, node)) return false; // note that loop conditions allow uses of initialized declarations // and so require the value if (value) mValues.push(value); } else if (mLog.atErrorLimit()) return false; } return true; } bool ComputeGenerator::visit(const ast::Local* node) { // Reverse iterate through the current blocks and use the first declaration found // The current block number looks something like as follows // // ENTRY: Block 1 // // if(...) // Block 3 // { // if(...) {} // Block 5 // } // else {} // Block 2 // // Note that in block 5, block 2 variables will be queried. However block variables // are constructed from the top down, so although the block number is used for // reverse iterating, block 2 will not contain any information // llvm::Value* value = mSymbolTables.find(node->name()); if (value) { mValues.push(value); } else { mLog.error("variable \"" + node->name() + "\" hasn't been declared", node); return false; } return true; } bool ComputeGenerator::visit(const ast::ArrayUnpack* node) { llvm::Value* value = mValues.top(); mValues.pop(); llvm::Value* component0 = mValues.top(); mValues.pop(); llvm::Value* component1 = nullptr; if (node->isMatrixIndex()) { component1 = mValues.top(); mValues.pop(); // if double indexing, the two component values will be // pushed onto the stack with the first index last. i.e. // top: expression // 2nd index (if matrix access) // bottom: 1st index // so swap the components std::swap(component0, component1); } llvm::Type* type = value->getType(); if (!type->isPointerTy() || !type->getPointerElementType()->isArrayTy()) { mLog.error("variable is not a valid type for component access", node); return false; } // type now guaranteed to be an array type type = type->getPointerElementType(); const size_t size = type->getArrayNumElements(); if (component1 && size <= 4) { { mLog.error("attribute or local variable is not a compatible matrix type " "for [,] indexing", node); return false; } } if (component0->getType()->isPointerTy()) { component0 = mBuilder.CreateLoad(component0); } if (component1 && component1->getType()->isPointerTy()) { component1 = mBuilder.CreateLoad(component1); } if (!component0->getType()->isIntegerTy() || (component1 && !component1->getType()->isIntegerTy())) { std::ostringstream os; llvm::raw_os_ostream stream(os); component0->getType()->print(stream); if (component1) { stream << ", "; component1->getType()->print(stream); } stream.flush(); { mLog.error("unable to index into array with a non integer value. Types are [" + os.str() + "]", node); return false; } } llvm::Value* zero = LLVMType<int32_t>::get(mContext, 0); if (!component1) { value = mBuilder.CreateGEP(value, {zero, component0}); } else { // component0 = row, component1 = column. Index into the matrix array // which is layed out in row major = (component0*dim + component1) assert(size == 9 || size == 16); const int32_t dim = size == 9 ? 3 : 4; llvm::Value* offset = LLVMType<int32_t>::get(mContext, static_cast<int32_t>(dim)); component0 = binaryOperator(component0, offset, ast::tokens::MULTIPLY, mBuilder); component0 = binaryOperator(component0, component1, ast::tokens::PLUS, mBuilder); value = mBuilder.CreateGEP(value, {zero, component0}); } mValues.push(value); return true; } bool ComputeGenerator::visit(const ast::ArrayPack* node) { const size_t num = node->children(); // if there is only one element on the stack, leave it as a pointer to a scalar // or another array if (num == 1) return true; std::vector<llvm::Value*> values; values.reserve(num); for (size_t i = 0; i < num; ++i) { llvm::Value* value = mValues.top(); mValues.pop(); if (value->getType()->isPointerTy()) { value = mBuilder.CreateLoad(value); } values.push_back(value); } // reserve the values // @todo this should probably be handled by the AST std::reverse(values.begin(), values.end()); llvm::Value* array = arrayPackCast(values, mBuilder); mValues.push(array); return true; } bool ComputeGenerator::visit(const ast::Value<bool>* node) { llvm::Constant* value = LLVMType<bool>::get(mContext, node->value()); mValues.push(value); return true; } bool ComputeGenerator::visit(const ast::Value<int16_t>* node) { return visit<int16_t>(node); } bool ComputeGenerator::visit(const ast::Value<int32_t>* node) { return visit<int32_t>(node); } bool ComputeGenerator::visit(const ast::Value<int64_t>* node) { return visit<int64_t>(node); } bool ComputeGenerator::visit(const ast::Value<float>* node) { return visit<float>(node); } bool ComputeGenerator::visit(const ast::Value<double>* node) { return visit<double>(node); } bool ComputeGenerator::visit(const ast::Value<std::string>* node) { assert(node->value().size() < static_cast<size_t>(std::numeric_limits<AXString::SizeType>::max())); llvm::Value* loc = mBuilder.CreateGlobalStringPtr(node->value()); // char* llvm::Constant* constLoc = llvm::cast<llvm::Constant>(loc); llvm::Constant* size = LLVMType<AXString::SizeType>::get (mContext, static_cast<AXString::SizeType>(node->value().size())); llvm::Value* constStr = LLVMType<AXString>::get(mContext, constLoc, size); // Always allocate an AXString here for easier passing to functions // @todo shouldn't need an AXString for char* literals llvm::Value* alloc = insertStaticAlloca(mBuilder, LLVMType<AXString>::get(mContext)); mBuilder.CreateStore(constStr, alloc); mValues.push(alloc); return true; } const FunctionGroup* ComputeGenerator::getFunction(const std::string &identifier, const bool allowInternal) { return mFunctionRegistry.getOrInsert(identifier, mOptions, allowInternal); } template <typename ValueType> typename std::enable_if<std::is_integral<ValueType>::value, bool>::type ComputeGenerator::visit(const ast::Value<ValueType>* node) { using ContainerT = typename ast::Value<ValueType>::ContainerType; static const ContainerT max = static_cast<ContainerT>(std::numeric_limits<ValueType>::max()); if (node->asContainerType() > max) { if (!mLog.warning("signed integer overflow in integer literal " + std::to_string(node->asContainerType()), node)) return false; } llvm::Constant* value = LLVMType<ValueType>::get(mContext, node->value()); mValues.push(value); return true; } template <typename ValueType> typename std::enable_if<std::is_floating_point<ValueType>::value, bool>::type ComputeGenerator::visit(const ast::Value<ValueType>* node) { assert(std::isinf(node->value()) || node->value() >= 0.0); llvm::Constant* value = LLVMType<ValueType>::get(mContext, node->value()); mValues.push(value); return true; } bool ComputeGenerator::visit(const ast::ExternalVariable* node) { const std::string globalName = node->tokenname(); llvm::Value* ptrToAddress = this->globals().get(globalName); if (!ptrToAddress) { ptrToAddress = llvm::cast<llvm::GlobalVariable> (mModule.getOrInsertGlobal(globalName, LLVMType<uintptr_t>::get(mContext))); this->globals().insert(globalName, ptrToAddress); } llvm::Type* type = llvmTypeFromToken(node->type(), mContext); llvm::Value* address = mBuilder.CreateLoad(ptrToAddress); llvm::Value* value = mBuilder.CreateIntToPtr(address, type->getPointerTo(0)); if (type->isIntegerTy() || type->isFloatingPointTy()) { value = mBuilder.CreateLoad(value); } mValues.push(value); return true; } bool ComputeGenerator::visit(const ast::Tree*) { // In case we haven't returned already (i.e. we are NOT in a null block) // we insert a ret void. If we are, this will just get cleaned up anyway below. mBuilder.CreateRetVoid(); mBuilder.SetInsertPoint(&mFunction->back()); return true; } bool ComputeGenerator::visit(const ast::Attribute*) { assert(false && "Base ComputeGenerator attempted to generate code for an Attribute. " "PointComputeGenerator or VolumeComputeGenerator should be used for " "attribute accesses."); return false; } bool ComputeGenerator::assignExpression(llvm::Value* lhs, llvm::Value*& rhs, const ast::Node* node) { llvm::Type* strtype = LLVMType<AXString>::get(mContext); llvm::Type* ltype = lhs->getType(); llvm::Type* rtype = rhs->getType(); if (!ltype->isPointerTy()) { mLog.error("unable to assign to an rvalue", node); return false; } ltype = ltype->getPointerElementType(); if (rtype->isPointerTy()) rtype = rtype->getPointerElementType(); size_t lsize = ltype->isArrayTy() ? ltype->getArrayNumElements() : 1; size_t rsize = rtype->isArrayTy() ? rtype->getArrayNumElements() : 1; // Handle scalar->matrix promotion if necessary // @todo promote all values (i.e. scalar to vectors) to make below branching // easier. Need to verifier IR is able to optimise to the same logic if (lsize == 9 || lsize == 16) { if (rtype->isIntegerTy() || rtype->isFloatingPointTy()) { if (rhs->getType()->isPointerTy()) { rhs = mBuilder.CreateLoad(rhs); } rhs = arithmeticConversion(rhs, ltype->getArrayElementType(), mBuilder); rhs = scalarToMatrix(rhs, mBuilder, lsize == 9 ? 3 : 4); rtype = rhs->getType()->getPointerElementType(); rsize = lsize; } } if (lsize != rsize) { if (lsize > 1 && rsize > 1) { mLog.error("unable to assign vector/array " "attributes with mismatching sizes", node); return false; } else if (lsize == 1) { assert(rsize > 1); mLog.error("cannot assign a scalar value " "from a vector or matrix. Consider using the [] operator to " "get a particular element", node); return false; } } // All remaining operators are either componentwise, string or invalid implicit casts const bool string = (ltype == strtype && rtype == strtype); const bool componentwise = !string && (rtype->isFloatingPointTy() || rtype->isIntegerTy() || rtype->isArrayTy()) && (ltype->isFloatingPointTy() || ltype->isIntegerTy() || ltype->isArrayTy()); if (componentwise) { assert(rsize == lsize || (rsize == 1 || lsize == 1)); const size_t resultsize = std::max(lsize, rsize); if (ltype != rtype) { llvm::Type* letype = ltype->isArrayTy() ? ltype->getArrayElementType() : ltype; llvm::Type* retype = rtype->isArrayTy() ? rtype->getArrayElementType() : rtype; if (letype != retype) { llvm::Type* highest = typePrecedence(letype, retype); if (highest != letype) { if (!mLog.warning("implicit conversion in assignment (possible truncation)", node)) return false; } } } // compute the componentwise precision llvm::Type* opprec = ltype->isArrayTy() ? ltype->getArrayElementType() : ltype; // if target is bool, perform standard boolean conversion (*not* truncation). // i.e. if rhs is anything but zero, lhs is true // @todo zeroval should be at rhstype if (opprec->isIntegerTy(1)) { llvm::Value* newRhs = nullptr; if (!this->binaryExpression(newRhs, LLVMType<int32_t>::get(mContext, 0), rhs, ast::tokens::NOTEQUALS, node)) return false; if (!newRhs) return true; rhs = newRhs; assert(newRhs->getType()->isIntegerTy(1)); } for (size_t i = 0; i < resultsize; ++i) { llvm::Value* lelement = lsize == 1 ? lhs : mBuilder.CreateConstGEP2_64(lhs, 0, i); llvm::Value* relement = rsize == 1 ? rhs : mBuilder.CreateLoad(mBuilder.CreateConstGEP2_64(rhs, 0, i)); relement = arithmeticConversion(relement, opprec, mBuilder); mBuilder.CreateStore(relement, lelement); } } else if (string) { // get the size of the rhs string llvm::Type* strType = LLVMType<AXString>::get(mContext); llvm::Value* rstrptr = nullptr; llvm::Value* size = nullptr; if (llvm::isa<llvm::Constant>(rhs)) { llvm::Constant* zero = llvm::cast<llvm::Constant>(LLVMType<int32_t>::get(mContext, 0)); llvm::Constant* constant = llvm::cast<llvm::Constant>(rhs)->getAggregateElement(zero); // char* rstrptr = constant; constant = constant->stripPointerCasts(); const size_t count = constant->getType()->getPointerElementType()->getArrayNumElements(); assert(count < static_cast<size_t>(std::numeric_limits<AXString::SizeType>::max())); size = LLVMType<AXString::SizeType>::get (mContext, static_cast<AXString::SizeType>(count)); } else { rstrptr = mBuilder.CreateStructGEP(strType, rhs, 0); // char** rstrptr = mBuilder.CreateLoad(rstrptr); size = mBuilder.CreateStructGEP(strType, rhs, 1); // AXString::SizeType* size = mBuilder.CreateLoad(size); } // total with term llvm::Value* one = LLVMType<AXString::SizeType>::get(mContext, 1); llvm::Value* totalTerm = binaryOperator(size, one, ast::tokens::PLUS, mBuilder); // re-allocate the string array llvm::Value* string = mBuilder.CreateAlloca(LLVMType<char>::get(mContext), totalTerm); llvm::Value* lstrptr = mBuilder.CreateStructGEP(strType, lhs, 0); // char** llvm::Value* lsize = mBuilder.CreateStructGEP(strType, lhs, 1); // AXString::SizeType* #if LLVM_VERSION_MAJOR >= 10 mBuilder.CreateMemCpy(string, /*dest-align*/llvm::MaybeAlign(0), rstrptr, /*src-align*/llvm::MaybeAlign(0), totalTerm); #elif LLVM_VERSION_MAJOR > 6 mBuilder.CreateMemCpy(string, /*dest-align*/0, rstrptr, /*src-align*/0, totalTerm); #else mBuilder.CreateMemCpy(string, rstrptr, totalTerm, /*align*/0); #endif mBuilder.CreateStore(string, lstrptr); mBuilder.CreateStore(size, lsize); } else { mLog.error("unsupported implicit cast in assignment", node); return false; } return true; } bool ComputeGenerator::binaryExpression(llvm::Value*& result, llvm::Value* lhs, llvm::Value* rhs, const ast::tokens::OperatorToken op, const ast::Node* node) { llvm::Type* strtype = LLVMType<AXString>::get(mContext); llvm::Type* ltype = lhs->getType(); llvm::Type* rtype = rhs->getType(); if (ltype->isPointerTy()) ltype = ltype->getPointerElementType(); if (rtype->isPointerTy()) rtype = rtype->getPointerElementType(); size_t lsize = ltype->isArrayTy() ? ltype->getArrayNumElements() : 1; size_t rsize = rtype->isArrayTy() ? rtype->getArrayNumElements() : 1; // Handle scalar->matrix promotion if necessary // @todo promote all values (i.e. scalar to vectors) to make below branching // easier. Need to verifier IR is able to optimise to the same logic if (lsize == 9 || lsize == 16) { if (rtype->isIntegerTy() || rtype->isFloatingPointTy()) { if (rhs->getType()->isPointerTy()) { rhs = mBuilder.CreateLoad(rhs); } rhs = arithmeticConversion(rhs, ltype->getArrayElementType(), mBuilder); rhs = scalarToMatrix(rhs, mBuilder, lsize == 9 ? 3 : 4); rtype = rhs->getType()->getPointerElementType(); rsize = lsize; } } if (rsize == 9 || rsize == 16) { if (ltype->isIntegerTy() || ltype->isFloatingPointTy()) { if (lhs->getType()->isPointerTy()) { lhs = mBuilder.CreateLoad(lhs); } lhs = arithmeticConversion(lhs, rtype->getArrayElementType(), mBuilder); lhs = scalarToMatrix(lhs, mBuilder, rsize == 9 ? 3 : 4); ltype = lhs->getType()->getPointerElementType(); lsize = rsize; } } // const ast::tokens::OperatorType opType = ast::tokens::operatorType(op); result = nullptr; // Handle custom matrix operators if (lsize >= 9 || rsize >= 9) { if (op == ast::tokens::MULTIPLY) { if ((lsize == 9 && rsize == 9) || (lsize == 16 && rsize == 16)) { // matrix matrix multiplication all handled through mmmult result = this->getFunction("mmmult", /*internal*/true)->execute({lhs, rhs}, mBuilder); } else if ((lsize == 9 && rsize == 3) || (lsize == 16 && rsize == 3) || (lsize == 16 && rsize == 4)) { // matrix vector multiplication all handled through pretransform result = this->getFunction("pretransform")->execute({lhs, rhs}, mBuilder); } else if ((lsize == 3 && rsize == 9) || (lsize == 4 && rsize == 16) || (lsize == 4 && rsize == 16)) { // vector matrix multiplication all handled through transform result = this->getFunction("transform")->execute({lhs, rhs}, mBuilder); } else { mLog.error("unsupported * operator on " "vector/matrix sizes", node); return false; } } else if (op == ast::tokens::MORETHAN || op == ast::tokens::LESSTHAN || op == ast::tokens::MORETHANOREQUAL || op == ast::tokens::LESSTHANOREQUAL || op == ast::tokens::DIVIDE || // no / support for mats op == ast::tokens::MODULO || // no % support for mats opType == ast::tokens::LOGICAL || opType == ast::tokens::BITWISE) { mLog.error("call to unsupported operator \"" + ast::tokens::operatorNameFromToken(op) + "\" with a vector/matrix argument", node); return false; } } if (!result) { // Handle matrix/vector ops of mismatching sizes if (lsize > 1 || rsize > 1) { if (lsize != rsize && (lsize > 1 && rsize > 1)) { mLog.error("unsupported binary operator on vector/matrix " "arguments of mismatching sizes", node); return false; } if (op == ast::tokens::MORETHAN || op == ast::tokens::LESSTHAN || op == ast::tokens::MORETHANOREQUAL || op == ast::tokens::LESSTHANOREQUAL || opType == ast::tokens::LOGICAL || opType == ast::tokens::BITWISE) { mLog.error("call to unsupported operator \"" + ast::tokens::operatorNameFromToken(op) + "\" with a vector/matrix argument", node); return false; } } // Handle invalid floating point ops if (rtype->isFloatingPointTy() || ltype->isFloatingPointTy()) { if (opType == ast::tokens::BITWISE) { mLog.error("call to unsupported operator \"" + ast::tokens::operatorNameFromToken(op) + "\" with a floating point argument", node); return false; } } } // All remaining operators are either componentwise, string or invalid implicit casts const bool componentwise = !result && (rtype->isFloatingPointTy() || rtype->isIntegerTy() || rtype->isArrayTy()) && (ltype->isFloatingPointTy() || ltype->isIntegerTy() || ltype->isArrayTy()); if (componentwise) { assert(ltype->isArrayTy() || ltype->isFloatingPointTy() || ltype->isIntegerTy()); assert(rtype->isArrayTy() || rtype->isFloatingPointTy() || rtype->isIntegerTy()); assert(rsize == lsize || (rsize == 1 || lsize == 1)); if (op == ast::tokens::DIVIDE || op == ast::tokens::MODULO) { if (llvm::Constant* c = llvm::dyn_cast<llvm::Constant>(rhs)) { if (c->isZeroValue()) { if (op == ast::tokens::DIVIDE) { if (!mLog.warning("division by zero is undefined", node)) return false; } else { if (!mLog.warning("modulo by zero is undefined", node)) return false; } } } } // compute the componentwise precision llvm::Type* opprec = ltype->isArrayTy() ? ltype->getArrayElementType() : ltype; opprec = rtype->isArrayTy() ? typePrecedence(opprec, rtype->getArrayElementType()) : typePrecedence(opprec, rtype); // if bool, the lowest precision and subsequent result should be int32 // for arithmetic, bitwise and certain other ops // @note - no bool containers, so if the type is a container, it can't // contain booleans if (opprec->isIntegerTy(1)) { if (opType == ast::tokens::ARITHMETIC || opType == ast::tokens::BITWISE || op == ast::tokens::MORETHAN || op == ast::tokens::LESSTHAN || op == ast::tokens::MORETHANOREQUAL || op == ast::tokens::LESSTHANOREQUAL) { opprec = LLVMType<int32_t>::get(mContext); } } // load scalars once if (!ltype->isArrayTy()) { if (lhs->getType()->isPointerTy()) { lhs = mBuilder.CreateLoad(lhs); } } if (!rtype->isArrayTy()) { if (rhs->getType()->isPointerTy()) { rhs = mBuilder.CreateLoad(rhs); } } const size_t resultsize = std::max(lsize, rsize); std::vector<llvm::Value*> elements; elements.reserve(resultsize); // handle floored modulo Function::Ptr target; auto runop = [&target, op, this](llvm::Value* a, llvm::Value* b) { if (target) return target->call({a,b}, this->mBuilder, /*cast=*/false); else return binaryOperator(a, b, op, this->mBuilder); }; if (op == ast::tokens::MODULO) { const FunctionGroup* mod = this->getFunction("floormod"); assert(mod); target = mod->match({opprec,opprec}, mContext); assert(target); } // perform op for (size_t i = 0; i < resultsize; ++i) { llvm::Value* lelement = lsize == 1 ? lhs : mBuilder.CreateLoad(mBuilder.CreateConstGEP2_64(lhs, 0, i)); llvm::Value* relement = rsize == 1 ? rhs : mBuilder.CreateLoad(mBuilder.CreateConstGEP2_64(rhs, 0, i)); lelement = arithmeticConversion(lelement, opprec, mBuilder); relement = arithmeticConversion(relement, opprec, mBuilder); elements.emplace_back(runop(lelement, relement)); } // handle vec/mat results if (resultsize > 1) { if (op == ast::tokens::EQUALSEQUALS || op == ast::tokens::NOTEQUALS) { const ast::tokens::OperatorToken reductionOp = op == ast::tokens::EQUALSEQUALS ? ast::tokens::AND : ast::tokens::OR; result = elements.front(); assert(result->getType() == LLVMType<bool>::get(mContext)); for (size_t i = 1; i < resultsize; ++i) { result = binaryOperator(result, elements[i], reductionOp, mBuilder); } } else { // Create the allocation at the start of the function block result = insertStaticAlloca(mBuilder, llvm::ArrayType::get(opprec, resultsize)); for (size_t i = 0; i < resultsize; ++i) { mBuilder.CreateStore(elements[i], mBuilder.CreateConstGEP2_64(result, 0, i)); } } } else { result = elements.front(); } } const bool string = !result && (ltype == strtype && rtype == strtype); if (string) { if (op != ast::tokens::PLUS) { mLog.error("unsupported string operation \"" + ast::tokens::operatorNameFromToken(op) + "\"", node); return false; } auto& B = mBuilder; auto structToString = [&B, strtype](llvm::Value*& str) -> llvm::Value* { llvm::Value* size = nullptr; if (llvm::isa<llvm::Constant>(str)) { llvm::Constant* zero = llvm::cast<llvm::Constant>(LLVMType<int32_t>::get(B.getContext(), 0)); llvm::Constant* constant = llvm::cast<llvm::Constant>(str)->getAggregateElement(zero); // char* str = constant; constant = constant->stripPointerCasts(); // array size should include the null terminator llvm::Type* arrayType = constant->getType()->getPointerElementType(); assert(arrayType->getArrayNumElements() > 0); const size_t count = arrayType->getArrayNumElements() - 1; assert(count < static_cast<size_t>(std::numeric_limits<AXString::SizeType>::max())); size = LLVMType<AXString::SizeType>::get (B.getContext(), static_cast<AXString::SizeType>(count)); } else { llvm::Value* rstrptr = B.CreateStructGEP(strtype, str, 0); // char** rstrptr = B.CreateLoad(rstrptr); size = B.CreateStructGEP(strtype, str, 1); // AXString::SizeType* size = B.CreateLoad(size); str = rstrptr; } return size; }; // lhs and rhs get set to the char* arrays in structToString llvm::Value* lhsSize = structToString(lhs); llvm::Value* rhsSize = structToString(rhs); // rhs with null terminator llvm::Value* one = LLVMType<AXString::SizeType>::get(mContext, 1); llvm::Value* rhsTermSize = binaryOperator(rhsSize, one, ast::tokens::PLUS, mBuilder); // total and total with term llvm::Value* total = binaryOperator(lhsSize, rhsSize, ast::tokens::PLUS, mBuilder); llvm::Value* totalTerm = binaryOperator(lhsSize, rhsTermSize, ast::tokens::PLUS, mBuilder); // get ptrs to the new structs values result = insertStaticAlloca(mBuilder, strtype); llvm::Value* string = mBuilder.CreateAlloca(LLVMType<char>::get(mContext), totalTerm); llvm::Value* strptr = mBuilder.CreateStructGEP(strtype, result, 0); // char** llvm::Value* sizeptr = mBuilder.CreateStructGEP(strtype, result, 1); // AXString::SizeType* // get rhs offset llvm::Value* stringRhsOffset = mBuilder.CreateGEP(string, lhsSize); // memcpy #if LLVM_VERSION_MAJOR >= 10 mBuilder.CreateMemCpy(string, /*dest-align*/llvm::MaybeAlign(0), lhs, /*src-align*/llvm::MaybeAlign(0), lhsSize); mBuilder.CreateMemCpy(stringRhsOffset, /*dest-align*/llvm::MaybeAlign(0), rhs, /*src-align*/llvm::MaybeAlign(0), rhsTermSize); #elif LLVM_VERSION_MAJOR > 6 mBuilder.CreateMemCpy(string, /*dest-align*/0, lhs, /*src-align*/0, lhsSize); mBuilder.CreateMemCpy(stringRhsOffset, /*dest-align*/0, rhs, /*src-align*/0, rhsTermSize); #else mBuilder.CreateMemCpy(string, lhs, lhsSize, /*align*/0); mBuilder.CreateMemCpy(stringRhsOffset, rhs, rhsTermSize, /*align*/0); #endif mBuilder.CreateStore(string, strptr); mBuilder.CreateStore(total, sizeptr); } if (!result) { mLog.error("unsupported implicit cast in binary op", node); return false; } return true; } } // namespace codegen_internal } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
66,173
C++
37.228769
134
0.579013
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionRegistry.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/FunctionRegistry.cc #include "FunctionRegistry.h" #include "Functions.h" #include "FunctionTypes.h" #include "../Exceptions.h" namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { void FunctionRegistry::insert(const std::string& identifier, const FunctionRegistry::ConstructorT creator, const bool internal) { if (!mMap.emplace(std::piecewise_construct, std::forward_as_tuple(identifier), std::forward_as_tuple(creator, internal)).second) { OPENVDB_THROW(AXCompilerError, "A function already exists" " with the provided identifier: \"" + identifier + "\""); } } void FunctionRegistry::insertAndCreate(const std::string& identifier, const FunctionRegistry::ConstructorT creator, const FunctionOptions& op, const bool internal) { auto inserted = mMap.emplace(std::piecewise_construct, std::forward_as_tuple(identifier), std::forward_as_tuple(creator, internal)); if (!inserted.second) { OPENVDB_THROW(AXCompilerError, "A function already exists" " with the provided token: \"" + identifier + "\""); } inserted.first->second.create(op); } const FunctionGroup* FunctionRegistry::getOrInsert(const std::string& identifier, const FunctionOptions& op, const bool allowInternalAccess) { auto iter = mMap.find(identifier); if (iter == mMap.end()) return nullptr; FunctionRegistry::RegisteredFunction& reg = iter->second; if (!allowInternalAccess && reg.isInternal()) return nullptr; if (!reg.function()) reg.create(op); const FunctionGroup* const function = reg.function(); // initialize function dependencies if necessary if (op.mLazyFunctions && function) { for (const auto& decl : function->list()) { const std::vector<const char*>& deps = decl->dependencies(); for (const auto& dep : deps) { // if the function ptr doesn't exist, create it with getOrInsert. // This provides internal access and ensures handling of cyclical // dependencies do not cause a problem const FunctionGroup* const internal = this->get(dep, true); if (!internal) this->getOrInsert(dep, op, true); } } } return function; } const FunctionGroup* FunctionRegistry::get(const std::string& identifier, const bool allowInternalAccess) const { auto iter = mMap.find(identifier); if (iter == mMap.end()) return nullptr; if (!allowInternalAccess && iter->second.isInternal()) return nullptr; return iter->second.function(); } void FunctionRegistry::createAll(const FunctionOptions& op, const bool verify) { for (auto& it : mMap) it.second.create(op); if (!verify) return; std::set<std::string> symbols; for (auto& it : mMap) { const auto& func = it.second.function(); if (!func) { OPENVDB_LOG_WARN("Unable to create function '" << it.first << "'."); } if (it.first != std::string(func->name())) { OPENVDB_LOG_WARN("Registered function identifier does not match function name '" << it.first << "' -> '" << func->name() << "'."); } if (it.first.empty() || !func->name()) { OPENVDB_LOG_WARN("Registered function has no identifier or name."); } if (func->list().empty()) { OPENVDB_LOG_WARN("Function '" << it.first << "' has no declarations."); } for (const auto& decl : func->list()) { if (symbols.count(std::string(decl->symbol()))) { OPENVDB_LOG_WARN("Function '" << it.first << "' has a symbol clash. Symbol '" << decl->symbol() << "' already exists."); } symbols.insert(std::string(decl->symbol())); } } } } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
4,256
C++
34.181818
111
0.601504
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointComputeGenerator.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/PointComputeGenerator.cc #include "PointComputeGenerator.h" #include "FunctionRegistry.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../Exceptions.h" #include "../ast/Scanners.h" #include <llvm/ADT/SmallVector.h> #include <llvm/IR/BasicBlock.h> #include <llvm/IR/CallingConv.h> #include <llvm/IR/Constants.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Function.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/InlineAsm.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/Pass.h> #include <llvm/Support/MathExtras.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { const std::array<std::string, PointKernel::N_ARGS>& PointKernel::argumentKeys() { static const std::array<std::string, PointKernel::N_ARGS> arguments = {{ "custom_data", "attribute_set", "point_index", "attribute_handles", "group_handles", "leaf_data" }}; return arguments; } std::string PointKernel::getDefaultName() { return "ax.compute.point"; } std::string PointRangeKernel::getDefaultName() { return "ax.compute.pointrange"; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// namespace codegen_internal { PointComputeGenerator::PointComputeGenerator(llvm::Module& module, const FunctionOptions& options, FunctionRegistry& functionRegistry, Logger& logger) : ComputeGenerator(module, options, functionRegistry, logger) {} AttributeRegistry::Ptr PointComputeGenerator::generate(const ast::Tree& tree) { llvm::FunctionType* type = llvmFunctionTypeFromSignature<PointKernel::Signature>(mContext); mFunction = llvm::Function::Create(type, llvm::Function::ExternalLinkage, PointKernel::getDefaultName(), &mModule); // Set up arguments for initial entry llvm::Function::arg_iterator argIter = mFunction->arg_begin(); const auto arguments = PointKernel::argumentKeys(); auto keyIter = arguments.cbegin(); for (; argIter != mFunction->arg_end(); ++argIter, ++keyIter) { argIter->setName(*keyIter); } type = llvmFunctionTypeFromSignature<PointRangeKernel::Signature>(mContext); llvm::Function* rangeFunction = llvm::Function::Create(type, llvm::Function::ExternalLinkage, PointRangeKernel::getDefaultName(), &mModule); // Set up arguments for initial entry for the range function std::vector<llvm::Value*> kPointRangeArguments; argIter = rangeFunction->arg_begin(); for (; argIter != rangeFunction->arg_end(); ++argIter) { kPointRangeArguments.emplace_back(llvm::cast<llvm::Value>(argIter)); } { // Generate the range function which calls mFunction point_count times // For the pointRangeKernelSignature function, create a for loop which calls // kPoint for every point index 0 to mPointCount. The argument types for // pointRangeKernelSignature and kPoint are the same, but the 'point_index' argument for // kPoint is the point index rather than the point range auto iter = std::find(arguments.begin(), arguments.end(), "point_index"); assert(iter != arguments.end()); const size_t argumentIndex = std::distance(arguments.begin(), iter); llvm::BasicBlock* preLoop = llvm::BasicBlock::Create(mContext, "entry_" + PointRangeKernel::getDefaultName(), rangeFunction); mBuilder.SetInsertPoint(preLoop); llvm::Value* pointCountValue = kPointRangeArguments[argumentIndex]; llvm::Value* indexMinusOne = mBuilder.CreateSub(pointCountValue, mBuilder.getInt64(1)); llvm::BasicBlock* loop = llvm::BasicBlock::Create(mContext, "loop_compute_point", rangeFunction); mBuilder.CreateBr(loop); mBuilder.SetInsertPoint(loop); llvm::PHINode* incr = mBuilder.CreatePHI(mBuilder.getInt64Ty(), 2, "i"); incr->addIncoming(/*start*/mBuilder.getInt64(0), preLoop); // Call kPoint with incr which will be updated per branch // Map the function arguments. For the 'point_index' argument, we don't pull in the provided // args, but instead use the value of incr. incr will correspond to the index of the // point being accessed within the pointRangeKernelSignature loop. std::vector<llvm::Value*> args(kPointRangeArguments); args[argumentIndex] = incr; mBuilder.CreateCall(mFunction, args); llvm::Value* next = mBuilder.CreateAdd(incr, mBuilder.getInt64(1), "nextval"); llvm::Value* endCondition = mBuilder.CreateICmpULT(incr, indexMinusOne, "endcond"); llvm::BasicBlock* loopEnd = mBuilder.GetInsertBlock(); llvm::BasicBlock* postLoop = llvm::BasicBlock::Create(mContext, "post_loop_compute_point", rangeFunction); mBuilder.CreateCondBr(endCondition, loop, postLoop); mBuilder.SetInsertPoint(postLoop); incr->addIncoming(next, loopEnd); mBuilder.CreateRetVoid(); mBuilder.ClearInsertionPoint(); } llvm::BasicBlock* entry = llvm::BasicBlock::Create(mContext, "entry_" + PointKernel::getDefaultName(), mFunction); mBuilder.SetInsertPoint(entry); // build the attribute registry AttributeRegistry::Ptr registry = AttributeRegistry::create(tree); // Visit all attributes and allocate them in local IR memory - assumes attributes // have been verified by the ax compiler // @note Call all attribute allocs at the start of this block so that llvm folds // them into the function prologue (as a static allocation) SymbolTable* localTable = this->mSymbolTables.getOrInsert(1); // run allocations and update the symbol table for (const AttributeRegistry::AccessData& data : registry->data()) { llvm::Value* value = mBuilder.CreateAlloca(llvmTypeFromToken(data.type(), mContext)); assert(llvm::cast<llvm::AllocaInst>(value)->isStaticAlloca()); localTable->insert(data.tokenname(), value); } // insert getters for read variables for (const AttributeRegistry::AccessData& data : registry->data()) { if (!data.reads()) continue; const std::string token = data.tokenname(); this->getAttributeValue(token, localTable->get(token)); } // full code generation // errors can stop traversal, but dont always, so check the log if (!this->traverse(&tree) || mLog.hasError()) return nullptr; // insert set code std::vector<const AttributeRegistry::AccessData*> write; for (const AttributeRegistry::AccessData& access : registry->data()) { if (access.writes()) write.emplace_back(&access); } // if it doesn't write to any externally accessible data (i.e attributes) // then early exit if (write.empty()) return registry; for (auto block = mFunction->begin(); block != mFunction->end(); ++block) { // Only inset set calls if theres a valid return instruction in this block llvm::Instruction* inst = block->getTerminator(); if (!inst || !llvm::isa<llvm::ReturnInst>(inst)) continue; mBuilder.SetInsertPoint(inst); // Insert set attribute instructions before termination for (const AttributeRegistry::AccessData* access : write) { const std::string token = access->tokenname(); llvm::Value* value = localTable->get(token); // Expected to be used more than one (i.e. should never be zero) assert(value->hasNUsesOrMore(1)); // Check to see if this value is still being used - it may have // been cleaned up due to returns. If there's only one use, it's // the original get of this attribute. if (value->hasOneUse()) { // @todo The original get can also be optimized out in this case // this->globals().remove(variable.first); // mModule.getGlobalVariable(variable.first)->eraseFromParent(); continue; } llvm::Type* type = value->getType()->getPointerElementType(); llvm::Type* strType = LLVMType<AXString>::get(mContext); const bool usingString = type == strType; llvm::Value* handlePtr = this->attributeHandleFromToken(token); const FunctionGroup* const function = this->getFunction("setattribute", true); // load the result (if its a scalar) if (type->isIntegerTy() || type->isFloatingPointTy()) { value = mBuilder.CreateLoad(value); } llvm::Value* pointidx = extractArgument(mFunction, "point_index"); assert(pointidx); // construct function arguments std::vector<llvm::Value*> args { handlePtr, // handle pointidx, // point index value // set value }; if (usingString) { llvm::Value* leafdata = extractArgument(mFunction, "leaf_data"); assert(leafdata); args.emplace_back(leafdata); } function->execute(args, mBuilder); } } return registry; } bool PointComputeGenerator::visit(const ast::Attribute* node) { const std::string globalName = node->tokenname(); SymbolTable* localTable = this->mSymbolTables.getOrInsert(1); llvm::Value* value = localTable->get(globalName); assert(value); mValues.push(value); return true; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// void PointComputeGenerator::getAttributeValue(const std::string& globalName, llvm::Value* location) { std::string name, type; ast::Attribute::nametypeFromToken(globalName, &name, &type); llvm::Value* handlePtr = this->attributeHandleFromToken(globalName); llvm::Value* pointidx = extractArgument(mFunction, "point_index"); llvm::Value* leafdata = extractArgument(mFunction, "leaf_data"); assert(leafdata); assert(pointidx); std::vector<llvm::Value*> args; const bool usingString = type == "string"; if (usingString) { const FunctionGroup* const function = this->getFunction("strattribsize", true); llvm::Value* size = function->execute({handlePtr, pointidx, leafdata}, mBuilder); // add room for the null terminator llvm::Value* one = LLVMType<AXString::SizeType>::get(mContext, 1); llvm::Value* sizeTerm = binaryOperator(size, one, ast::tokens::PLUS, mBuilder); // re-allocate the string array and store the size. The copying will be performed by // the getattribute function llvm::Type* strType = LLVMType<AXString>::get(mContext); llvm::Value* string = mBuilder.CreateAlloca(LLVMType<char>::get(mContext), sizeTerm); llvm::Value* lstrptr = mBuilder.CreateStructGEP(strType, location, 0); // char** llvm::Value* lsize = mBuilder.CreateStructGEP(strType, location, 1); // AXString::SizeType* mBuilder.CreateStore(string, lstrptr); mBuilder.CreateStore(size, lsize); args.reserve(4); } else { args.reserve(3); } args.emplace_back(handlePtr); args.emplace_back(pointidx); args.emplace_back(location); if (usingString) args.emplace_back(leafdata); const FunctionGroup* const function = this->getFunction("getattribute", true); function->execute(args, mBuilder); } llvm::Value* PointComputeGenerator::attributeHandleFromToken(const std::string& token) { // Visiting an attribute - get the attribute handle out of a vector of void pointers // insert the attribute into the map of global variables and get a unique global representing // the location which will hold the attribute handle offset. llvm::Value* index = llvm::cast<llvm::GlobalVariable> (mModule.getOrInsertGlobal(token, LLVMType<int64_t>::get(mContext))); this->globals().insert(token, index); // index into the void* array of handles and load the value. // The result is a loaded void* value index = mBuilder.CreateLoad(index); llvm::Value* handles = extractArgument(mFunction, "attribute_handles"); assert(handles); llvm::Value* handlePtr = mBuilder.CreateGEP(handles, index); // return loaded void** = void* return mBuilder.CreateLoad(handlePtr); } } // namespace codegen_internal } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
13,076
C++
35.527933
100
0.641863
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/ConstantFolding.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/ConstantFolding.h /// /// @authors Nick Avramoussis /// /// @brief Constant folding for C++ bindings. /// #ifndef OPENVDB_AX_CODEGEN_CONSTANT_FOLDING_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_CONSTANT_FOLDING_HAS_BEEN_INCLUDED #include "Types.h" #include <openvdb/version.h> #include <llvm/IR/Constants.h> #include <type_traits> #include <vector> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief Constant folding support structure /// template <typename SignatureT, size_t I = FunctionTraits<SignatureT>::N_ARGS> struct ConstantFolder { using ArgT = typename FunctionTraits<SignatureT>::template Arg<I-1>; using ArgumentValueType = typename ArgT::Type; // @brief Attempts evaluate a given function with a provided set of constant llvm // values. If successful, the function is invoked and the result is stored // and returned in an llvm::Value. // @details Currently only scalar constant folding is supported due to the way // vectors and matrices are alloced. Functions which return void are also // not supported for constant folding. // @param args The vector of llvm constants that comprise the function arguments. // Note that the size of this vector is expected to match the size of // the required function arguments and the templated parameter I // @param function The function to invoke if all arguments have a valid mapping. // @param C The llvm Context // @param ts The list of evaluated C types from the provided llvm constants. This // is expected to be empty (not provided) on the first call to fold and // is used on subsequent recursive calls. template <typename ...Tys> static llvm::Value* fold(const std::vector<llvm::Constant*>& args, const SignatureT& function, llvm::LLVMContext& C, Tys&&... ts) { assert(I-1 < args.size()); llvm::Constant* constant = args[I-1]; const llvm::Type* type = constant->getType(); if (type->isIntegerTy()) { assert(llvm::isa<llvm::ConstantInt>(constant)); llvm::ConstantInt* cint = llvm::cast<llvm::ConstantInt>(constant); const uint64_t val = cint->getLimitedValue(); return call<uint64_t, ArgumentValueType>(args, function, C, val, ts...); } else if (type->isFloatTy() || type->isDoubleTy()) { assert(llvm::isa<llvm::ConstantFP>(constant)); llvm::ConstantFP* cfp = llvm::cast<llvm::ConstantFP>(constant); const llvm::APFloat& apf = cfp->getValueAPF(); if (type->isFloatTy()) { const float val = apf.convertToFloat(); return call<float, ArgumentValueType>(args, function, C, val, ts...); } if (type->isDoubleTy()) { const double val = apf.convertToDouble(); return call<double, ArgumentValueType>(args, function, C, val, ts...); } } else if (type->isArrayTy()) { // @todo currently all arrays are alloced anyway which // needs to be handled or changed return nullptr; } // fallback return nullptr; } private: // @brief Specialization for supported implicit casting matching AX's supported // scalar casting. Continues to traverse the constant argument list. template <typename In, typename Out, typename ...Tys> static typename std::enable_if<std::is_convertible<In, Out>::value, llvm::Value*>::type call(const std::vector<llvm::Constant*>& args, const SignatureT& function, llvm::LLVMContext& C, const In& arg, Tys&&... ts) { using Next = ConstantFolder<SignatureT, I-1>; return Next::fold(args, function, C, Out(arg), ts...); } // @brief Specialization for unsupported implicit casting. Bails out with a // nullptr return. template <typename In, typename Out, typename ...Tys> static typename std::enable_if<!std::is_convertible<In, Out>::value, llvm::Value*>::type call(const std::vector<llvm::Constant*>&, const SignatureT&, llvm::LLVMContext&, const In&, Tys&&...) { return nullptr; } }; template <typename SignatureT> struct ConstantFolder<SignatureT, 0> { // @brief The final call to fold when all arguments have been evaluated (or no // arguments exist). template <typename ...Tys> static llvm::Value* fold(const std::vector<llvm::Constant*>& args, const SignatureT& function, llvm::LLVMContext& C, Tys&&... ts) { using ReturnT = typename FunctionTraits<SignatureT>::ReturnType; return call<ReturnT>(args, function, C, ts...); } private: // @brief Specialization for the invoking of the provided function if the return // type is not void. template <typename ReturnT, typename ...Tys> static typename std::enable_if<!std::is_same<ReturnT, void>::value, llvm::Value*>::type call(const std::vector<llvm::Constant*>&, const SignatureT& function, llvm::LLVMContext& C, Tys&&... ts) { const ReturnT result = function(ts...); return LLVMType<ReturnT>::get(C, result); } // @brief Specialization if the return type is void. No folding is supported. template <typename ReturnT, typename ...Tys> static typename std::enable_if<std::is_same<ReturnT, void>::value, llvm::Value*>::type call(const std::vector<llvm::Constant*>&, const SignatureT&, llvm::LLVMContext&, Tys&&...) { return nullptr; } }; } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_CONSTANT_FOLDING_HAS_BEEN_INCLUDED
6,160
C
35.455621
92
0.622078
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/StandardFunctions.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/StandardFunctions.cc /// /// @authors Nick Avramoussis, Richard Jones, Francisco Gochez /// /// @brief Definitions for all standard functions supported by AX. A /// standard function is one that is supported no matetr the input /// primitive type and rely either solely on AX types or core AX /// intrinsics. #include "Functions.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../Exceptions.h" #include "../math/OpenSimplexNoise.h" #include "../compiler/CompilerOptions.h" #include "../compiler/CustomData.h" #include <tbb/enumerable_thread_specific.h> #include <llvm/IR/Intrinsics.h> #include <unordered_map> #include <functional> #include <random> #include <cmath> #include <stddef.h> #include <stdint.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { namespace { // Reduce a size_t hash down into an unsigned int, taking all bits in the // size_t into account. We achieve this by repeatedly XORing as many bytes // that fit into an unsigned int, and then shift those bytes out of the // hash. We repeat until we have no bits left in the hash. template <typename SeedType> inline SeedType hashToSeed(size_t hash) { SeedType seed = 0; do { seed ^= (SeedType) hash; } while (hash >>= sizeof(SeedType) * 8); return seed; } struct SimplexNoise { // Open simplex noise - Visually axis-decorrelated coherent noise algorithm // based on the simplectic honeycomb. // See https://gist.github.com/KdotJPG/b1270127455a94ac5d19 inline static double noise(double x, double y, double z) { static const OSN::OSNoise noiseGenerator = OSN::OSNoise(); const double result = noiseGenerator.eval<double>(x, y, z); // adjust result so that it lies between 0 and 1, since // Noise::eval returns a number between -1 and 1 return (result + 1.0) * 0.5; } }; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// #define DEFINE_LLVM_FP_INTRINSIC(Identifier, Doc) \ inline FunctionGroup::UniquePtr llvm_##Identifier(const FunctionOptions& op) \ { \ static auto generate = \ [](const std::vector<llvm::Value*>& args, \ llvm::IRBuilder<>& B) -> llvm::Value* \ { \ llvm::Module* M = B.GetInsertBlock()->getParent()->getParent(); \ llvm::Function* function = \ llvm::Intrinsic::getDeclaration(M, \ llvm::Intrinsic::Identifier, args[0]->getType()); \ return B.CreateCall(function, args); \ }; \ \ return FunctionBuilder(#Identifier) \ .addSignature<double(double)>(generate, (double(*)(double))(std::Identifier)) \ .addSignature<float(float)>(generate, (float(*)(float))(std::Identifier)) \ .setArgumentNames({"n"}) \ .addFunctionAttribute(llvm::Attribute::ReadOnly) \ .addFunctionAttribute(llvm::Attribute::NoRecurse) \ .addFunctionAttribute(llvm::Attribute::NoUnwind) \ .addFunctionAttribute(llvm::Attribute::AlwaysInline) \ .setConstantFold(op.mConstantFoldCBindings) \ .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) \ .setDocumentation(Doc) \ .get(); \ } \ #define DEFINE_AX_C_FP_BINDING(Identifier, Doc) \ inline FunctionGroup::UniquePtr ax##Identifier(const FunctionOptions& op) \ { \ return FunctionBuilder(#Identifier) \ .addSignature<double(double)>((double(*)(double))(std::Identifier)) \ .addSignature<float(float)>((float(*)(float))(std::Identifier)) \ .setArgumentNames({"arg"}) \ .addFunctionAttribute(llvm::Attribute::ReadOnly) \ .addFunctionAttribute(llvm::Attribute::NoRecurse) \ .addFunctionAttribute(llvm::Attribute::NoUnwind) \ .addFunctionAttribute(llvm::Attribute::AlwaysInline) \ .setConstantFold(op.mConstantFoldCBindings) \ .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) \ .setDocumentation(Doc) \ .get(); \ } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Intrinsics DEFINE_LLVM_FP_INTRINSIC(sqrt, "Computes the square root of arg.") DEFINE_LLVM_FP_INTRINSIC(sin, "Computes the sine of arg (measured in radians).") DEFINE_LLVM_FP_INTRINSIC(cos, "Computes the cosine of arg (measured in radians).") DEFINE_LLVM_FP_INTRINSIC(log, "Computes the natural (base e) logarithm of arg.") DEFINE_LLVM_FP_INTRINSIC(log10, "Computes the common (base-10) logarithm of arg.") DEFINE_LLVM_FP_INTRINSIC(log2, "Computes the binary (base-2) logarithm of arg.") DEFINE_LLVM_FP_INTRINSIC(exp, "Computes e (Euler's number, 2.7182818...) raised to the given power arg.") DEFINE_LLVM_FP_INTRINSIC(exp2, "Computes 2 raised to the given power arg.") DEFINE_LLVM_FP_INTRINSIC(fabs, "Computes the absolute value of a floating point value arg.") DEFINE_LLVM_FP_INTRINSIC(floor, "Computes the largest integer value not greater than arg.") DEFINE_LLVM_FP_INTRINSIC(ceil, "Computes the smallest integer value not less than arg.") DEFINE_LLVM_FP_INTRINSIC(round, "Computes the nearest integer value to arg (in floating-point format)," " rounding halfway cases away from zero.") // pow created explicitly as it takes two arguments and performs slighlty different // calls for integer exponents inline FunctionGroup::UniquePtr llvm_pow(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { llvm::Type* overloadType = args[0]->getType(); llvm::Type* expType = args[1]->getType(); const llvm::Intrinsic::ID id = expType->isIntegerTy() ? llvm::Intrinsic::powi : llvm::Intrinsic::pow; llvm::Module* M = B.GetInsertBlock()->getParent()->getParent(); llvm::Function* function = llvm::Intrinsic::getDeclaration(M, id, overloadType); return B.CreateCall(function, args); }; return FunctionBuilder("pow") .addSignature<double(double,double)>(generate, (double(*)(double,double))(std::pow)) .addSignature<float(float,float)>(generate, (float(*)(float,float))(std::pow)) .addSignature<double(double,int32_t)>(generate, (double(*)(double,int32_t))(std::pow)) .setArgumentNames({"base", "exp"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(false) // decl's differ .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Computes the value of the first argument raised to the power of the second argument.") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Math DEFINE_AX_C_FP_BINDING(cbrt, "Computes the cubic root of the input.") inline FunctionGroup::UniquePtr axabs(const FunctionOptions& op) { auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { llvm::Value* value = args.front(); llvm::Type* type = value->getType(); if (type->isFloatingPointTy()) { return llvm_fabs(op)->execute(args, B); } // if negative flip all the bits and add 1 (xor with -1 and sub 1) llvm::Value* shift = type == LLVMType<int32_t>::get(B.getContext()) ? LLVMType<int32_t>::get(B.getContext(), 31) : LLVMType<int64_t>::get(B.getContext(), 63); // arithmetic shift right llvm::Value* mask = B.CreateAShr(value, shift); llvm::Value* xorResult = binaryOperator(value, mask, ast::tokens::BITXOR, B); return binaryOperator(xorResult, mask, ast::tokens::MINUS, B); }; // @note We also support fabs through the ax abs function return FunctionBuilder("abs") .addSignature<int64_t(int64_t)>(generate, (int64_t(*)(int64_t))(std::abs)) .addSignature<int32_t(int32_t)>(generate, (int32_t(*)(int32_t))(std::abs)) .addSignature<double(double)>(generate, (double(*)(double))(std::abs)) .addSignature<float(float)>(generate, (float(*)(float))(std::abs)) .setArgumentNames({"n"}) .addDependency("fabs") .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Computes the absolute value of an integer number.") .get(); } inline FunctionGroup::UniquePtr axdot(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> v1, v2; arrayUnpack(args[0], v1, B, /*load*/true); arrayUnpack(args[1], v2, B, /*load*/true); v1[0] = binaryOperator(v1[0], v2[0], ast::tokens::MULTIPLY, B); v1[1] = binaryOperator(v1[1], v2[1], ast::tokens::MULTIPLY, B); v1[2] = binaryOperator(v1[2], v2[2], ast::tokens::MULTIPLY, B); llvm::Value* result = binaryOperator(v1[0], v1[1], ast::tokens::PLUS, B); result = binaryOperator(result, v1[2], ast::tokens::PLUS, B); return result; }; static auto dot = [](auto a, auto b) { return a->dot(*b); }; using DotD = double(openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*); using DotF = float(openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*); using DotI = int32_t(openvdb::math::Vec3<int32_t>*,openvdb::math::Vec3<int32_t>*); return FunctionBuilder("dot") .addSignature<DotD>(generate, (DotD*)(dot)) .addSignature<DotF>(generate, (DotF*)(dot)) .addSignature<DotI>(generate, (DotI*)(dot)) .setArgumentNames({"a", "b"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Computes the dot product of two vectors.") .get(); } inline FunctionGroup::UniquePtr axcross(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> ptrs, left, right; arrayUnpack(args[0], ptrs, B, /*load*/false); arrayUnpack(args[1], left, B, /*load*/true); arrayUnpack(args[2], right, B, /*load*/true); assert(ptrs.size() == 3); assert(left.size() == 3); assert(right.size() == 3); std::vector<llvm::Value*> results(3); llvm::Value* tmp1 = binaryOperator(left[1], right[2], ast::tokens::MULTIPLY, B); llvm::Value* tmp2 = binaryOperator(left[2], right[1], ast::tokens::MULTIPLY, B); results[0] = binaryOperator(tmp1, tmp2, ast::tokens::MINUS, B); tmp1 = binaryOperator(left[2], right[0], ast::tokens::MULTIPLY, B); tmp2 = binaryOperator(left[0], right[2], ast::tokens::MULTIPLY, B); results[1] = binaryOperator(tmp1, tmp2, ast::tokens::MINUS, B); tmp1 = binaryOperator(left[0], right[1], ast::tokens::MULTIPLY, B); tmp2 = binaryOperator(left[1], right[0], ast::tokens::MULTIPLY, B); results[2] = binaryOperator(tmp1, tmp2, ast::tokens::MINUS, B); B.CreateStore(results[0], ptrs[0]); B.CreateStore(results[1], ptrs[1]); B.CreateStore(results[2], ptrs[2]); return nullptr; }; static auto cross = [](auto out, auto a, auto b) -> auto { *out = a->cross(*b); }; using CrossD = void(openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*); using CrossF = void(openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*); using CrossI = void(openvdb::math::Vec3<int32_t>*,openvdb::math::Vec3<int32_t>*,openvdb::math::Vec3<int32_t>*); return FunctionBuilder("cross") .addSignature<CrossD, true>(generate, (CrossD*)(cross)) .addSignature<CrossF, true>(generate, (CrossF*)(cross)) .addSignature<CrossI, true>(generate, (CrossI*)(cross)) .setArgumentNames({"a", "b"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the length of the given vector") .get(); } inline FunctionGroup::UniquePtr axlengthsq(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> elements; arrayUnpack(args[0], elements, B, /*load*/true); assert(elements.size() >= 2); llvm::Value* v1 = binaryOperator(elements[0], elements[0], ast::tokens::MULTIPLY, B); llvm::Value* v2 = binaryOperator(elements[1], elements[1], ast::tokens::MULTIPLY, B); llvm::Value* result = binaryOperator(v1, v2, ast::tokens::PLUS, B); if (elements.size() > 2) { llvm::Value* v3 = binaryOperator(elements[2], elements[2], ast::tokens::MULTIPLY, B); result = binaryOperator(result, v3, ast::tokens::PLUS, B); } if (elements.size() > 3) { llvm::Value* v4 = binaryOperator(elements[3], elements[3], ast::tokens::MULTIPLY, B); result = binaryOperator(result, v4, ast::tokens::PLUS, B); } return result; }; static auto lengthsq = [](auto in) -> auto { return in->lengthSqr(); }; return FunctionBuilder("lengthsq") .addSignature<double(openvdb::math::Vec2<double>*)>(generate, lengthsq) .addSignature<float(openvdb::math::Vec2<float>*)>(generate, lengthsq) .addSignature<int32_t(openvdb::math::Vec2<int32_t>*)>(generate, lengthsq) .addSignature<double(openvdb::math::Vec3<double>*)>(generate, lengthsq) .addSignature<float(openvdb::math::Vec3<float>*)>(generate, lengthsq) .addSignature<int32_t(openvdb::math::Vec3<int32_t>*)>(generate, lengthsq) .addSignature<double(openvdb::math::Vec4<double>*)>(generate, lengthsq) .addSignature<float(openvdb::math::Vec4<float>*)>(generate, lengthsq) .addSignature<int32_t(openvdb::math::Vec4<int32_t>*)>(generate, lengthsq) .setArgumentNames({"v"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the squared length of the given vector") .get(); } inline FunctionGroup::UniquePtr axlength(const FunctionOptions& op) { auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { auto a = axlengthsq(op); auto s = llvm_sqrt(op); llvm::Value* lsq = a->execute(args, B); return s->execute({lsq}, B); }; static auto length = [](auto in) -> auto { using VecType = typename std::remove_pointer<decltype(in)>::type; using ElementT = typename openvdb::VecTraits<VecType>::ElementType; using RetT = typename std::conditional <std::is_floating_point<ElementT>::value, ElementT, double>::type; return std::sqrt(RetT(in->lengthSqr())); }; return FunctionBuilder("length") .addSignature<double(openvdb::math::Vec2<double>*)>(generate, length) .addSignature<float(openvdb::math::Vec2<float>*)>(generate, length) .addSignature<double(openvdb::math::Vec2<int32_t>*)>(generate, length) .addSignature<double(openvdb::math::Vec3<double>*)>(generate, length) .addSignature<float(openvdb::math::Vec3<float>*)>(generate, length) .addSignature<double(openvdb::math::Vec3<int32_t>*)>(generate, length) .addSignature<double(openvdb::math::Vec4<double>*)>(generate, length) .addSignature<float(openvdb::math::Vec4<float>*)>(generate, length) .addSignature<double(openvdb::math::Vec4<int32_t>*)>(generate, length) .addDependency("lengthsq") .addDependency("sqrt") .setArgumentNames({"v"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the length of the given vector") .get(); } inline FunctionGroup::UniquePtr axnormalize(const FunctionOptions& op) { auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { auto a = axlength(op); llvm::Value* len = a->execute({args[1]}, B); std::vector<llvm::Value*> ptrs, elements; arrayUnpack(args[0], ptrs, B, /*load*/false); arrayUnpack(args[1], elements, B, /*load*/true); assert(ptrs.size() == 3); assert(elements.size() == 3); if (elements[0]->getType()->isIntegerTy()) { arithmeticConversion(elements, LLVMType<double>::get(B.getContext()), B); } // the following is always done at fp precision llvm::Value* one = llvm::ConstantFP::get(len->getType(), 1.0); llvm::Value* oneDividedByLength = B.CreateFDiv(one, len); elements[0] = B.CreateFMul(elements[0], oneDividedByLength); elements[1] = B.CreateFMul(elements[1], oneDividedByLength); elements[2] = B.CreateFMul(elements[2], oneDividedByLength); B.CreateStore(elements[0], ptrs[0]); B.CreateStore(elements[1], ptrs[1]); B.CreateStore(elements[2], ptrs[2]); return nullptr; }; static auto norm = [](auto out, auto in) { using VecType = typename std::remove_pointer<decltype(out)>::type; using ElementT = typename openvdb::VecTraits<VecType>::ElementType; *out = *in; // copy out->normalize(ElementT(0.0)); }; using NormalizeD = void(openvdb::math::Vec3<double>*,openvdb::math::Vec3<double>*); using NormalizeF = void(openvdb::math::Vec3<float>*,openvdb::math::Vec3<float>*); using NormalizeI = void(openvdb::math::Vec3<double>*, openvdb::math::Vec3<int32_t>*); return FunctionBuilder("normalize") .addSignature<NormalizeD, true>(generate, (NormalizeD*)(norm)) .addSignature<NormalizeF, true>(generate, (NormalizeF*)(norm)) .addSignature<NormalizeI, true>(generate, (NormalizeI*)(norm)) .addDependency("length") .setArgumentNames({"v"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the normalized result of the given vector.") .get(); } inline FunctionGroup::UniquePtr axlerp(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { assert(args.size() == 3); llvm::Value* a = args[0], *b = args[1], *t = args[2]; llvm::Value* zero = llvm::ConstantFP::get(a->getType(), 0.0); llvm::Value* one = llvm::ConstantFP::get(a->getType(), 1.0); llvm::Function* base = B.GetInsertBlock()->getParent(); // @todo short-circuit? llvm::Value* a1 = binaryOperator(a, zero, ast::tokens::LESSTHANOREQUAL, B); llvm::Value* b1 = binaryOperator(b, zero, ast::tokens::MORETHANOREQUAL, B); llvm::Value* a2 = binaryOperator(a, zero, ast::tokens::MORETHANOREQUAL, B); llvm::Value* b2 = binaryOperator(b, zero, ast::tokens::LESSTHANOREQUAL, B); a1 = binaryOperator(a1, b1, ast::tokens::AND, B); a2 = binaryOperator(a2, b2, ast::tokens::AND, B); a1 = binaryOperator(a1, a2, ast::tokens::OR, B); llvm::BasicBlock* then = llvm::BasicBlock::Create(B.getContext(), "then", base); llvm::BasicBlock* post = llvm::BasicBlock::Create(B.getContext(), "post", base); B.CreateCondBr(a1, then, post); B.SetInsertPoint(then); llvm::Value* r = binaryOperator(one, t, ast::tokens::MINUS, B); r = binaryOperator(r, a, ast::tokens::MULTIPLY, B); llvm::Value* right = binaryOperator(t, b, ast::tokens::MULTIPLY, B); r = binaryOperator(r, right, ast::tokens::PLUS, B); B.CreateRet(r); B.SetInsertPoint(post); llvm::Value* tisone = binaryOperator(t, one, ast::tokens::EQUALSEQUALS, B); then = llvm::BasicBlock::Create(B.getContext(), "then", base); post = llvm::BasicBlock::Create(B.getContext(), "post", base); B.CreateCondBr(tisone, then, post); B.SetInsertPoint(then); B.CreateRet(b); B.SetInsertPoint(post); // if nlerp llvm::Value* x = binaryOperator(b, a, ast::tokens::MINUS, B); x = binaryOperator(t, x, ast::tokens::MULTIPLY, B); x = binaryOperator(a, x, ast::tokens::PLUS, B); then = llvm::BasicBlock::Create(B.getContext(), "then", base); post = llvm::BasicBlock::Create(B.getContext(), "post", base); a1 = binaryOperator(t, one, ast::tokens::MORETHAN, B); a2 = binaryOperator(b, a, ast::tokens::MORETHAN, B); a1 = binaryOperator(a1, a2, ast::tokens::EQUALSEQUALS, B); B.CreateCondBr(a1, then, post); B.SetInsertPoint(then); b1 = binaryOperator(b, x, ast::tokens::LESSTHAN, B); B.CreateRet(B.CreateSelect(b1, x, b)); B.SetInsertPoint(post); b1 = binaryOperator(x, b, ast::tokens::LESSTHAN, B); return B.CreateRet(B.CreateSelect(b1, x, b)); }; // This lerp implementation is taken from clang and matches the C++20 standard static auto lerp = [](auto a, auto b, auto t) -> auto { using ValueT = decltype(a); // If there is a zero crossing with a,b do the more precise // linear interpolation. This is only monotonic if there is // a zero crossing // Exact, monotonic, bounded, determinate, and (for a=b=0) // consistent if ((a <= 0 && b >= 0) || (a >= 0 && b <= 0)) { return t * b + (ValueT(1.0) - t) * a; } // If t is exactly 1, return b (as the second impl doesn't // guarantee this due to fp arithmetic) if (t == ValueT(1.0)) return b; // less precise interpolation when there is no crossing // Exact at t=0, monotonic except near t=1, bounded, // determinate, and consistent const auto x = a + t * (b - a); // Ensure b is preferred to another equal value (i.e. -0. vs. +0.), // which avoids returning -0 for t==1 but +0 for other nearby // values of t. This branching also stops nans being returns from // inf inputs // monotonic near t=1 if ((t > ValueT(1.0)) == (b > a)) return b < x ? x : b; else return x < b ? x : b; }; return FunctionBuilder("lerp") .addSignature<double(double,double,double)>(generate, (double(*)(double,double,double))(lerp)) .addSignature<float(float,float,float)>(generate, (float(*)(float,float,float))(lerp)) .setArgumentNames({"a", "b", "amount"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Performs bilinear interpolation between the values. If the " "amount is outside the range 0 to 1, the values will be extrapolated linearly. " "If amount is 0, the first value is returned. If it is 1, the second value " "is returned. This implementation is guaranteed to be monotonic.") .get(); } inline FunctionGroup::UniquePtr axmin(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { llvm::Value* result = binaryOperator(args[0], args[1], ast::tokens::MORETHAN, B); return B.CreateSelect(result, args[1], args[0]); }; static auto min = [](auto a, auto b) -> auto { return std::min(a, b); }; return FunctionBuilder("min") .addSignature<double(double,double)>(generate, (double(*)(double,double))(min)) .addSignature<float(float,float)>(generate, (float(*)(float,float))(min)) .addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(min)) .addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(min)) .setArgumentNames({"a", "b"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the smaller of the given values.") .get(); } inline FunctionGroup::UniquePtr axmax(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { llvm::Value* result = binaryOperator(args[0], args[1], ast::tokens::MORETHAN, B); return B.CreateSelect(result, args[0], args[1]); }; static auto max = [](auto a, auto b) -> auto { return std::max(a, b); }; return FunctionBuilder("max") .addSignature<double(double,double)>(generate, (double(*)(double,double))(max)) .addSignature<float(float,float)>(generate, (float(*)(float,float))(max)) .addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(max)) .addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(max)) .setArgumentNames({"a", "b"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the larger of the given values.") .get(); } inline FunctionGroup::UniquePtr axclamp(const FunctionOptions& op) { auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { llvm::Value* min = axmax(op)->execute({args[0], args[1]}, B); llvm::Value* result = axmin(op)->execute({min, args[2]}, B); return result; }; using ClampD = double(double, double, double); using ClampF = float(float, float, float); using ClampI = int32_t(int32_t, int32_t, int32_t); using ClampL = int64_t(int64_t, int64_t, int64_t); return FunctionBuilder("clamp") .addSignature<ClampD>(generate, &openvdb::math::Clamp<double>) .addSignature<ClampF>(generate, &openvdb::math::Clamp<float>) .addSignature<ClampL>(generate, &openvdb::math::Clamp<int64_t>) .addSignature<ClampI>(generate, &openvdb::math::Clamp<int32_t>) .addDependency("min") .addDependency("max") .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setArgumentNames({"in", "min", "max"}) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Clamps the first argument to the minimum second argument " "value and maximum third argument value") .get(); } inline FunctionGroup::UniquePtr axfit(const FunctionOptions& op) { auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { // (outMax - outMin)(x - inMin) // f(x) = ---------------------------- + outMin // inMax - inMin // if inMax == inMin, f(x) = (outMax + outMin) / 2.0 // NOTE: this also performs a clamp on the ordered input range // @TODO revisit. If this is the best thing to do, should add conditional // branching so that the clamping math is never executed when the value // is inside std::vector<llvm::Value*> argcopy(args); // select the precision at which to perform llvm::Type* precision = argcopy[0]->getType(); if (precision->isIntegerTy()) { precision = LLVMType<double>::get(B.getContext()); } // See if the input range has a valid magnitude .i.e. the values are not the same llvm::Value* isInputRangeValid = binaryOperator(argcopy[1], argcopy[2], ast::tokens::NOTEQUALS, B); // clamp the input to the ORDERED inMin to inMax range llvm::Value* minRangeComp = binaryOperator(argcopy[1], argcopy[2], ast::tokens::LESSTHAN, B); llvm::Value* minInputRange = B.CreateSelect(minRangeComp, argcopy[1], argcopy[2]); llvm::Value* maxInputRange = B.CreateSelect(minRangeComp, argcopy[2], argcopy[1]); // clamp { auto clamp = axclamp(op); argcopy[0] = clamp->execute({ argcopy[0], minInputRange, maxInputRange }, B); } // cast all (the following requires floating point precision) for (auto& arg : argcopy) arg = arithmeticConversion(arg, precision, B); llvm::Value* valueMinusMin = B.CreateFSub(argcopy[0], argcopy[1]); llvm::Value* inputRange = B.CreateFSub(argcopy[2], argcopy[1]); llvm::Value* outputRange = B.CreateFSub(argcopy[4], argcopy[3]); llvm::Value* result = B.CreateFMul(outputRange, valueMinusMin); result = B.CreateFDiv(result, inputRange); // NOTE - This can cause division by zero result = B.CreateFAdd(argcopy[3], result); // calculate the output range over 2 and use this value if the input range is invalid llvm::Value* outputRangeOverTwo = B.CreateFAdd(argcopy[3], argcopy[4]); llvm::Value* two = llvm::ConstantFP::get(precision, 2.0); outputRangeOverTwo = B.CreateFDiv(outputRangeOverTwo, two); return B.CreateSelect(isInputRangeValid, result, outputRangeOverTwo); }; using FitD = double(double, double, double, double, double); using FitF = float(float, float, float, float, float); using FitL = double(int64_t, int64_t, int64_t, int64_t, int64_t); using FitI = double(int32_t, int32_t, int32_t, int32_t, int32_t); return FunctionBuilder("fit") .addSignature<FitD>(generate) .addSignature<FitF>(generate) .addSignature<FitL>(generate) .addSignature<FitI>(generate) .addDependency("clamp") .setArgumentNames({"value", "omin", "omax", "nmin", "nmax"}) .setConstantFold(false) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Fit the first argument to the output range by " "first clamping the value between the second and third input range " "arguments and then remapping the result to the output range fourth and " "fifth arguments") .get(); } inline FunctionGroup::UniquePtr axrand(const FunctionOptions& op) { struct Rand { static double rand(const std::mt19937_64::result_type* seed) { using ThreadLocalEngineContainer = tbb::enumerable_thread_specific<std::mt19937_64>; static ThreadLocalEngineContainer ThreadLocalEngines; static std::uniform_real_distribution<double> Generator(0.0,1.0); std::mt19937_64& engine = ThreadLocalEngines.local(); if (seed) { engine.seed(static_cast<std::mt19937_64::result_type>(*seed)); } return Generator(engine); } static double rand() { return Rand::rand(nullptr); } static double rand(double seed) { const std::mt19937_64::result_type hash = static_cast<std::mt19937_64::result_type>(std::hash<double>()(seed)); return Rand::rand(&hash); } static double rand(int64_t seed) { const std::mt19937_64::result_type hash = static_cast<std::mt19937_64::result_type>(seed); return Rand::rand(&hash); } }; return FunctionBuilder("rand") .addSignature<double()>((double(*)())(Rand::rand)) .addSignature<double(double)>((double(*)(double))(Rand::rand)) .addSignature<double(int64_t)>((double(*)(int64_t))(Rand::rand)) .setArgumentNames({"seed"}) // We can't constant fold rand even if it's been called with a constant as // it will leave the generator in a different state in comparison to other // threads and, as it relies on an internal state, doesn't respect branching // etc. We also can't use a different generate for constant calls as subsequent // calls to rand() without an argument won't know to advance the generator. .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Creates a random number based on the provided " "seed. The number will be in the range of 0 to 1. The same number is " "produced for the same seed. Note that if rand is called without a seed " "the previous state of the random number generator is advanced for the " "currently processing element. This state is determined by the last call to " "rand() with a given seed. If rand is not called with a seed, the generator " "advances continuously across different elements which can produce non-" "deterministic results. It is important that rand is always called with a " "seed at least once for deterministic results.") .get(); } inline FunctionGroup::UniquePtr axrand32(const FunctionOptions& op) { struct Rand { static double rand(const std::mt19937::result_type* seed) { using ThreadLocalEngineContainer = tbb::enumerable_thread_specific<std::mt19937>; // Obtain thread-local engine (or create if it doesn't exist already). static ThreadLocalEngineContainer ThreadLocalEngines; static std::uniform_real_distribution<double> Generator(0.0,1.0); std::mt19937& engine = ThreadLocalEngines.local(); if (seed) { engine.seed(static_cast<std::mt19937::result_type>(*seed)); } // Once we have seeded the random number generator, we then evaluate it, // which returns a floating point number in the range [0,1) return Generator(engine); } static double rand() { return Rand::rand(nullptr); } static double rand(double seed) { // We initially hash the double-precision seed with `std::hash`. The // important thing about the hash is that it produces a "reliable" hash value, // taking into account a number of special cases for floating point numbers // (e.g. -0 and +0 must return the same hash value, etc). Other than these // special cases, this function will usually just copy the binary // representation of a float into the resultant `size_t` const size_t hash = std::hash<double>()(seed); // Now that we have a reliable hash (with special floating-point cases taken // care of), we proceed to use this hash to seed a random number generator. // The generator takes an unsigned int, which is not guaranteed to be the // same size as size_t. // // So, we must convert it. I should note that the OpenVDB math libraries will // do this for us, but its implementation static_casts `size_t` to `unsigned int`, // and because `std::hash` returns a binary copy of the original // double-precision number in almost all cases, this ends up producing noticable // patterns in the result (e.g. by truncating the upper 4 bytes, values of 1.0, // 2.0, 3.0, and 4.0 all return the same hash value because their lower 4 bytes // are all zero). // // We use the `hashToSeed` function to reduce our `size_t` to an `unsigned int`, // whilst taking all bits in the `size_t` into account. // On some architectures std::uint_fast32_t may be size_t, but we always hash to // be consistent. const std::mt19937::result_type uintseed = static_cast<std::mt19937::result_type>(hashToSeed<uint32_t>(hash)); return Rand::rand(&uintseed); } static double rand(int32_t seed) { const std::mt19937::result_type uintseed = static_cast<std::mt19937::result_type>(seed); return Rand::rand(&uintseed); } }; return FunctionBuilder("rand32") .addSignature<double()>((double(*)())(Rand::rand)) .addSignature<double(double)>((double(*)(double))(Rand::rand)) .addSignature<double(int32_t)>((double(*)(int32_t))(Rand::rand)) .setArgumentNames({"seed"}) // We can't constant fold rand even if it's been called with a constant as // it will leave the generator in a different state in comparison to other // threads and, as it relies on an internal state, doesn't respect branching // etc. We also can't use a different generate for constant calls as subsequent // calls to rand() without an argument won't know to advance the generator. .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Creates a random number based on the provided 32 bit " "seed. The number will be in the range of 0 to 1. The same number is " "produced for the same seed. " "NOTE: This function does not share the same random number generator as " "rand(). rand32() may provide a higher throughput on some architectures, " "but will produce different results to rand(). " "NOTE: If rand32 is called without a seed the previous state of the random " "number generator is advanced for the currently processing element. This " "state is determined by the last call to rand32() with a given seed. If " "rand32 is not called with a seed, the generator advances continuously " "across different elements which can produce non-deterministic results. " "It is important that rand32 is always called with a seed at least once " "for deterministic results.") .get(); } inline FunctionGroup::UniquePtr axsign(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { // int r = (T(0) < val) - (val < T(0)); assert(args.size() == 1); llvm::Value* arg = args.front(); llvm::Type* type = arg->getType(); llvm::Value* zero; if (type->isIntegerTy()) { zero = llvm::ConstantInt::get(type, static_cast<uint64_t>(0), /*signed*/true); } else { assert(type->isFloatingPointTy()); zero = llvm::ConstantFP::get(type, static_cast<double>(0.0)); } llvm::Value* c1 = binaryOperator(zero, arg, ast::tokens::LESSTHAN, B); c1 = arithmeticConversion(c1, LLVMType<int32_t>::get(B.getContext()), B); llvm::Value* c2 = binaryOperator(arg, zero, ast::tokens::LESSTHAN, B); c2 = arithmeticConversion(c2, LLVMType<int32_t>::get(B.getContext()), B); llvm::Value* r = binaryOperator(c1, c2, ast::tokens::MINUS, B); return arithmeticConversion(r, LLVMType<int32_t>::get(B.getContext()), B); }; return FunctionBuilder("sign") .addSignature<int32_t(double)>(generate) .addSignature<int32_t(float)>(generate) .addSignature<int32_t(int64_t)>(generate) .addSignature<int32_t(int32_t)>(generate) .setArgumentNames({"n"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Implements signum, determining if the input is negative, zero " "or positive. Returns -1 for a negative number, 0 for the number zero, and +1 " "for a positive number. Note that this function does not check the sign of " "floating point +/-0.0 values. See signbit().") .get(); } inline FunctionGroup::UniquePtr axsignbit(const FunctionOptions& op) { return FunctionBuilder("signbit") .addSignature<bool(double)>((bool(*)(double))(std::signbit)) .addSignature<bool(float)>((bool(*)(float))(std::signbit)) .setArgumentNames({"n"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Determines if the given floating point number input is negative. " "Returns true if arg is negative, false otherwise. Will return true for -0.0, " "false for +0.0") .get(); } inline FunctionGroup::UniquePtr axtruncatemod(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { assert(args.size() == 2); return binaryOperator(args[0], args[1], ast::tokens::MODULO, B); }; return FunctionBuilder("truncatemod") .addSignature<double(double,double)>(generate) .addSignature<float(float,float)>(generate) .addSignature<int64_t(int64_t,int64_t)>(generate) .addSignature<int32_t(int32_t,int32_t)>(generate) .addSignature<int16_t(int16_t,int16_t)>(generate) .setArgumentNames({"dividend", "divisor"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Truncated modulo, where the result of the division operator " "on (dividend / divisor) is truncated. The remainder is thus calculated with " "D - d * trunc(D/d). This is equal to the C/C++ % implementation. This is NOT " "equal to a%b in AX. See floormod(), euclideanmod().") .get(); } inline FunctionGroup::UniquePtr axfloormod(const FunctionOptions& op) { static auto ifmod = [](auto D, auto d) -> auto { using ValueType = decltype(D); auto r = D % d; // tmod if ((r > 0 && d < 0) || (r < 0 && d > 0)) r = r+d; return ValueType(r); }; static auto ffmod = [](auto D, auto d) -> auto { auto r = std::fmod(D, d); if ((r > 0 && d < 0) || (r < 0 && d > 0)) r = r+d; return r; }; static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { assert(args.size() == 2); llvm::Value* D = args[0]; llvm::Value* d = args[1]; // tmod llvm::Value* r = binaryOperator(D, d, ast::tokens::MODULO, B); llvm::Value* zero = llvmConstant(0, D->getType()); llvm::Value* a1 = binaryOperator(r, zero, ast::tokens::MORETHAN, B); llvm::Value* a2 = binaryOperator(d, zero, ast::tokens::LESSTHAN, B); a1 = binaryOperator(a1, a2, ast::tokens::AND, B); llvm::Value* b1 = binaryOperator(r, zero, ast::tokens::LESSTHAN, B); llvm::Value* b2 = binaryOperator(d, zero, ast::tokens::MORETHAN, B); b1 = binaryOperator(b1, b2, ast::tokens::AND, B); a1 = binaryOperator(a1, b1, ast::tokens::OR, B); llvm::Value* rplus = binaryOperator(r, d, ast::tokens::PLUS, B); return B.CreateSelect(a1, rplus, r); }; return FunctionBuilder("floormod") .addSignature<double(double,double)>(generate, (double(*)(double,double))(ffmod)) .addSignature<float(float,float)>(generate, (float(*)(float,float))(ffmod)) .addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(ifmod)) .addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(ifmod)) .addSignature<int16_t(int16_t,int16_t)>(generate, (int16_t(*)(int16_t,int16_t))(ifmod)) .setArgumentNames({"dividend", "divisor"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Floored modulo, where the result of the division operator " "on (dividend / divisor) is floored. The remainder is thus calculated with " "D - d * floor(D/d). This is the implemented modulo % operator of AX. This is " "equal to the python % implementation. See trucnatemod(), euclideanmod().") .get(); } inline FunctionGroup::UniquePtr axeuclideanmod(const FunctionOptions& op) { static auto iemod = [](auto D, auto d) -> auto { using ValueType = decltype(D); auto r = D%d; if (r < 0) { if (d > 0) r = r + d; else r = r - d; } return ValueType(r); }; static auto femod = [](auto D, auto d) -> auto { auto r = std::fmod(D, d); if (r < 0) { if (d > 0) r = r + d; else r = r - d; } return r; }; static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { assert(args.size() == 2); llvm::Value* D = args[0], *d = args[1]; llvm::Value* r = binaryOperator(D, d, ast::tokens::MODULO, B); // tmod llvm::Value* zero = llvmConstant(0, D->getType()); llvm::Value* a1 = binaryOperator(d, zero, ast::tokens::MORETHAN, B); llvm::Value* rplus = binaryOperator(r, d, ast::tokens::PLUS, B); llvm::Value* rminus = binaryOperator(r, d, ast::tokens::MINUS, B); llvm::Value* rd = B.CreateSelect(a1, rplus, rminus); a1 = binaryOperator(r, zero, ast::tokens::LESSTHAN, B); return B.CreateSelect(a1, rd, r); }; return FunctionBuilder("euclideanmod") .addSignature<double(double,double)>(generate, (double(*)(double,double))(femod)) .addSignature<float(float,float)>(generate, (float(*)(float,float))(femod)) .addSignature<int64_t(int64_t,int64_t)>(generate, (int64_t(*)(int64_t,int64_t))(iemod)) .addSignature<int32_t(int32_t,int32_t)>(generate, (int32_t(*)(int32_t,int32_t))(iemod)) .addSignature<int16_t(int16_t,int16_t)>(generate, (int16_t(*)(int16_t,int16_t))(iemod)) .setArgumentNames({"dividend", "divisor"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Euclidean modulo, where by the result of the division operator " "on (dividend / divisor) is floored or ceiled depending on its sign, guaranteeing " "that the return value is always positive. The remainder is thus calculated with " "D - d * (d < 0 ? ceil(D/d) : floor(D/d)). This is NOT equal to a%b in AX. See " "truncatemod(), floormod().") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Matrix math inline FunctionGroup::UniquePtr axdeterminant(const FunctionOptions& op) { // 3 by 3 determinant static auto generate3 = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> m1; arrayUnpack(args[0], m1, B, /*load*/true); assert(m1.size() == 9); llvm::Value* e1 = binaryOperator(m1[4], m1[8], ast::tokens::MULTIPLY, B); llvm::Value* e2 = binaryOperator(m1[5], m1[7], ast::tokens::MULTIPLY, B); llvm::Value* c0 = binaryOperator(e1, e2, ast::tokens::MINUS, B); e1 = binaryOperator(m1[5], m1[6], ast::tokens::MULTIPLY, B); e2 = binaryOperator(m1[3], m1[8], ast::tokens::MULTIPLY, B); llvm::Value* c1 = binaryOperator(e1, e2, ast::tokens::MINUS, B); e1 = binaryOperator(m1[3], m1[7], ast::tokens::MULTIPLY, B); e2 = binaryOperator(m1[4], m1[6], ast::tokens::MULTIPLY, B); llvm::Value* c2 = binaryOperator(e1, e2, ast::tokens::MINUS, B); c0 = binaryOperator(m1[0], c0, ast::tokens::MULTIPLY, B); c1 = binaryOperator(m1[1], c1, ast::tokens::MULTIPLY, B); c2 = binaryOperator(m1[2], c2, ast::tokens::MULTIPLY, B); c0 = binaryOperator(c0, c1, ast::tokens::PLUS, B); c0 = binaryOperator(c0, c2, ast::tokens::PLUS, B); return c0; }; // 4 by 4 determinant static auto generate4 = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> m1; arrayUnpack(args[0], m1, B, /*load*/true); assert(m1.size() == 16); // @note Okay to alloca here as long as embed IR is false llvm::Value* subMat = B.CreateAlloca(llvm::ArrayType::get(m1.front()->getType(), 9)); std::vector<llvm::Value*> elements; arrayUnpack(subMat, elements, B, /*load elements*/false); llvm::Value* result = llvm::ConstantFP::get(m1.front()->getType(), 0.0); for (size_t i = 0; i < 4; ++i) { size_t sourceIndex = 0, targetIndex = 0; for (size_t j = 0; j < 4; ++j) { for (size_t k = 0; k < 4; ++k) { if ((k != i) && (j != 0)) { B.CreateStore(m1[sourceIndex], elements[targetIndex]); ++targetIndex; } ++sourceIndex; } } llvm::Value* subResult = generate3({subMat}, B); subResult = binaryOperator(m1[i], subResult, ast::tokens::MULTIPLY, B); if (i % 2) result = binaryOperator(result, subResult, ast::tokens::MINUS, B); else result = binaryOperator(result, subResult, ast::tokens::PLUS, B); } return result; }; static auto determinant = [](auto mat) -> auto { return mat->det(); }; using DeterminantM3D = double(openvdb::math::Mat3<double>*); using DeterminantM3F = float(openvdb::math::Mat3<float>*); using DeterminantM4D = double(openvdb::math::Mat4<double>*); using DeterminantM4F = float(openvdb::math::Mat4<float>*); return FunctionBuilder("determinant") .addSignature<DeterminantM3D>(generate3, (DeterminantM3D*)(determinant)) .addSignature<DeterminantM3F>(generate3, (DeterminantM3F*)(determinant)) .addSignature<DeterminantM4D>(generate4, (DeterminantM4D*)(determinant)) .addSignature<DeterminantM4F>(generate4, (DeterminantM4F*)(determinant)) .setArgumentNames({"mat"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the determinant of a matrix.") .get(); } inline FunctionGroup::UniquePtr axdiag(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> ptrs, arg1; arrayUnpack(args[0], ptrs, B, /*load*/false); arrayUnpack(args[1], arg1, B, /*load*/true); const size_t size = arg1.size(); if (size == 3 || size == 4) { //vector - convert to diagonal matrix const size_t dim = size*size; assert(ptrs.size() == dim); llvm::Type* type = arg1.front()->getType(); llvm::Value* zero = type->isFloatTy() ? LLVMType<float>::get(B.getContext(), 0.0f) : LLVMType<double>::get(B.getContext(), 0.0); for (size_t i = 0, j = 0; i < dim; ++i) { llvm::Value* m = zero; if (i % (size + 1) == 0) { m = arg1[j]; ++j; } B.CreateStore(m, ptrs[i]); } } else { // matrix - convert to vector assert(size == 9 || size == 16); const size_t dim = size == 9 ? 3 : 4; assert(ptrs.size() == dim); for (size_t i = 0; i < dim; ++i) { B.CreateStore(arg1[i+(i*dim)], ptrs[i]); } } return nullptr; }; static auto diag = [](auto result, const auto input) { using ValueType = typename std::remove_pointer<decltype(input)>::type; using ResultType = typename std::remove_pointer<decltype(result)>::type; using ElementT = typename openvdb::ValueTraits<ValueType>::ElementType; using RElementT = typename openvdb::ValueTraits<ResultType>::ElementType; static_assert(std::is_same<ElementT, RElementT>::value, "Input and result arguments for diag are not the same type"); if (openvdb::ValueTraits<ValueType>::IsVec) { // input is a vec, result is a matrix const int size = openvdb::ValueTraits<ValueType>::Size; int element = 0; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { assert(element < openvdb::ValueTraits<ResultType>::Elements); if (i == j) result->asPointer()[element] = (input->asPointer())[i]; else result->asPointer()[element] = ElementT(0.0); ++element; } } } else { assert(openvdb::ValueTraits<ValueType>::IsMat); // input is a matrix, result is a vec const int size = openvdb::ValueTraits<ValueType>::Size; for (int i = 0; i < size; ++i) { assert(i < openvdb::ValueTraits<ResultType>::Size); result->asPointer()[i] = input->asPointer()[i+(i*size)]; } } }; using DiagV3M3D = void(openvdb::math::Vec3<double>*, openvdb::math::Mat3<double>*); using DiagV3M3F = void(openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*); using DiagV4M4D = void(openvdb::math::Vec4<double>*, openvdb::math::Mat4<double>*); using DiagV4M4F = void(openvdb::math::Vec4<float>*, openvdb::math::Mat4<float>*); using DiagM3V3D = void(openvdb::math::Mat3<double>*, openvdb::math::Vec3<double>*); using DiagM3V3F = void(openvdb::math::Mat3<float>*, openvdb::math::Vec3<float>*); using DiagM4V4D = void(openvdb::math::Mat4<double>*, openvdb::math::Vec4<double>*); using DiagM4V4F = void(openvdb::math::Mat4<float>*, openvdb::math::Vec4<float>*); return FunctionBuilder("diag") .addSignature<DiagV3M3D, true>(generate, (DiagV3M3D*)(diag)) .addSignature<DiagV3M3F, true>(generate, (DiagV3M3F*)(diag)) .addSignature<DiagV4M4D, true>(generate, (DiagV4M4D*)(diag)) .addSignature<DiagV4M4F, true>(generate, (DiagV4M4F*)(diag)) .setArgumentNames({"vec"}) .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .addSignature<DiagM3V3D, true>(generate, (DiagM3V3D*)(diag)) .addSignature<DiagM3V3F, true>(generate, (DiagM3V3F*)(diag)) .addSignature<DiagM4V4D, true>(generate, (DiagM4V4D*)(diag)) .addSignature<DiagM4V4F, true>(generate, (DiagM4V4F*)(diag)) .setArgumentNames({"mat"}) .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Create a diagonal matrix from a vector, or return the diagonal " "components of a matrix as a vector.") .get(); } inline FunctionGroup::UniquePtr axidentity3(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> elements; arrayUnpack(args[0], elements, B, /*load elements*/false); assert(elements.size() == 9); llvm::Value* zero = LLVMType<float>::get(B.getContext(), 0.0f); llvm::Value* one = LLVMType<float>::get(B.getContext(), 1.0f); for (size_t i = 0; i < 9; ++i) { llvm::Value* m = ((i == 0 || i == 4 || i == 8) ? one : zero); B.CreateStore(m, elements[i]); } return nullptr; }; return FunctionBuilder("identity3") .addSignature<void(openvdb::math::Mat3<float>*), true>(generate) .setConstantFold(false) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the 3x3 identity matrix") .get(); } inline FunctionGroup::UniquePtr axidentity4(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> elements; arrayUnpack(args[0], elements, B, /*load elements*/false); assert(elements.size() == 16); llvm::Value* zero = LLVMType<float>::get(B.getContext(), 0.0f); llvm::Value* one = LLVMType<float>::get(B.getContext(), 1.0f); for (size_t i = 0; i < 16; ++i) { llvm::Value* m = ((i == 0 || i == 5 || i == 10 || i == 15) ? one : zero); B.CreateStore(m, elements[i]); } return nullptr; }; return FunctionBuilder("identity4") .addSignature<void(openvdb::math::Mat4<float>*), true>(generate) .setConstantFold(false) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the 4x4 identity matrix") .get(); } inline FunctionGroup::UniquePtr axmmmult(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> ptrs, m1, m2; arrayUnpack(args[0], ptrs, B, /*load*/false); arrayUnpack(args[1], m1, B, /*load*/true); arrayUnpack(args[2], m2, B, /*load*/true); assert(m1.size() == 9 || m1.size() == 16); assert(ptrs.size() == m1.size()); assert(ptrs.size() == m2.size()); const size_t dim = m1.size() == 9 ? 3 : 4; llvm::Value* e3 = nullptr, *e4 = nullptr; for (size_t i = 0; i < dim; ++i) { const size_t row = i*dim; for (size_t j = 0; j < dim; ++j) { llvm::Value* e1 = binaryOperator(m1[0+row], m2[j], ast::tokens::MULTIPLY, B); llvm::Value* e2 = binaryOperator(m1[1+row], m2[dim+j], ast::tokens::MULTIPLY, B); if (dim >=3) e3 = binaryOperator(m1[2+row], m2[(dim*2)+j], ast::tokens::MULTIPLY, B); if (dim >=4) e4 = binaryOperator(m1[3+row], m2[(dim*3)+j], ast::tokens::MULTIPLY, B); e1 = binaryOperator(e1, e2, ast::tokens::PLUS, B); if (dim >=3) e1 = binaryOperator(e1, e3, ast::tokens::PLUS, B); if (dim >=4) e1 = binaryOperator(e1, e4, ast::tokens::PLUS, B); B.CreateStore(e1, ptrs[row+j]); } } return nullptr; }; static auto mmmult = [](auto out, auto mat2, auto mat1) { *out = (*mat1) * (*mat2); }; using MMMultM3D = void(openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*); using MMMultM3F = void(openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*); using MMMultM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Mat4<double>*, openvdb::math::Mat4<double>*); using MMMultM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Mat4<float>*, openvdb::math::Mat4<float>*); return FunctionBuilder("mmmult") .addSignature<MMMultM3D, true>(generate, (MMMultM3D*)(mmmult)) .addSignature<MMMultM3F, true>(generate, (MMMultM3F*)(mmmult)) .addSignature<MMMultM4D, true>(generate, (MMMultM4D*)(mmmult)) .addSignature<MMMultM4F, true>(generate, (MMMultM4F*)(mmmult)) .setArgumentNames({"a", "b"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Multiplies two matrices together and returns the result") .get(); } inline FunctionGroup::UniquePtr axpolardecompose(const FunctionOptions& op) { static auto polardecompose = [](auto in, auto orth, auto symm) -> bool { bool success = false; try { success = openvdb::math::polarDecomposition(*in, *orth, *symm); } catch (const openvdb::ArithmeticError&) { success = false; } return success; }; using PolarDecompositionM3D = bool(openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*); using PolarDecompositionM3F = bool(openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*); return FunctionBuilder("polardecompose") .addSignature<PolarDecompositionM3D>((PolarDecompositionM3D*)(polardecompose)) .addSignature<PolarDecompositionM3F>((PolarDecompositionM3F*)(polardecompose)) .setArgumentNames({"input", "unitary", "symmetric"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Decompose an invertible 3x3 matrix into its orthogonal (unitary) " "matrix and symmetric matrix components. If the determinant of the unitary matrix " "is 1 it is a rotation, otherwise if it is -1 there is some part reflection.") .get(); } inline FunctionGroup::UniquePtr axpostscale(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> m1, v1; arrayUnpack(args[0], m1, B, /*load*/false); arrayUnpack(args[1], v1, B, /*load*/true); assert(m1.size() == 16); assert(v1.size() == 3); // modify first 3 elements in all mat rows for (size_t row = 0; row < 4; ++row) { for (size_t col = 0; col < 3; ++col) { const size_t idx = (row*4) + col; assert(idx <= 14); llvm::Value* m1v = B.CreateLoad(m1[idx]); m1v = binaryOperator(m1v, v1[col], ast::tokens::MULTIPLY, B); B.CreateStore(m1v, m1[idx]); } } // @warning this is invalid for embedded IR return nullptr; }; static auto postscale = [](auto mat, auto vec) { mat->postScale(*vec); }; using PostscaleM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Vec3<double>*); using PostscaleM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Vec3<float>*); return FunctionBuilder("postscale") .addSignature<PostscaleM4D>(generate, (PostscaleM4D*)(postscale)) .addSignature<PostscaleM4F>(generate, (PostscaleM4F*)(postscale)) .setArgumentNames({"transform", "vec"}) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Post-scale a given matrix by the provided vector.") .get(); } inline FunctionGroup::UniquePtr axpretransform(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> ptrs, m1, v1; arrayUnpack(args[0], ptrs, B, /*load*/false); arrayUnpack(args[1], m1, B, /*load*/true); arrayUnpack(args[2], v1, B, /*load*/true); const size_t vec = v1.size(); const size_t dim = (m1.size() == 9 ? 3 : 4); assert(m1.size() == 9 || m1.size() == 16); assert(vec == 3 || vec == 4); assert(ptrs.size() == vec); // mat * vec llvm::Value* e3 = nullptr, *e4 = nullptr; for (size_t i = 0; i < vec; ++i) { llvm::Value* e1 = binaryOperator(v1[0], m1[0+(i*dim)], ast::tokens::MULTIPLY, B); llvm::Value* e2 = binaryOperator(v1[1], m1[1+(i*dim)], ast::tokens::MULTIPLY, B); if (dim >= 3) e3 = binaryOperator(v1[2], m1[2+(i*dim)], ast::tokens::MULTIPLY, B); if (dim == 4) { if (vec == 3) e4 = m1[3+(i*dim)]; else if (vec == 4) e4 = binaryOperator(v1[3], m1[3+(i*dim)], ast::tokens::MULTIPLY, B); } e1 = binaryOperator(e1, e2, ast::tokens::PLUS, B); if (e3) e1 = binaryOperator(e1, e3, ast::tokens::PLUS, B); if (e4) e1 = binaryOperator(e1, e4, ast::tokens::PLUS, B); B.CreateStore(e1, ptrs[i]); } return nullptr; }; static auto transform = [](auto out, auto mat, auto vec) { *out = mat->pretransform(*vec); }; using PretransformM3DV3D = void(openvdb::math::Vec3<double>*, openvdb::math::Mat3<double>*, openvdb::math::Vec3<double>*); using PretransformM3FV3F = void(openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*, openvdb::math::Vec3<float>*); using PretransformM4DV3D = void(openvdb::math::Vec3<double>*, openvdb::math::Mat4<double>*, openvdb::math::Vec3<double>*); using PretransformM4FV3F = void(openvdb::math::Vec3<float>*, openvdb::math::Mat4<float>*, openvdb::math::Vec3<float>*); using PretransformM4DV4D = void(openvdb::math::Vec4<double>*, openvdb::math::Mat4<double>*, openvdb::math::Vec4<double>*); using PretransformM4FV4F = void(openvdb::math::Vec4<float>*, openvdb::math::Mat4<float>*, openvdb::math::Vec4<float>*); return FunctionBuilder("pretransform") .addSignature<PretransformM3DV3D, true>(generate, (PretransformM3DV3D*)(transform)) .addSignature<PretransformM3FV3F, true>(generate, (PretransformM3FV3F*)(transform)) .addSignature<PretransformM4DV3D, true>(generate, (PretransformM4DV3D*)(transform)) .addSignature<PretransformM4FV3F, true>(generate, (PretransformM4FV3F*)(transform)) .addSignature<PretransformM4DV4D, true>(generate, (PretransformM4DV4D*)(transform)) .addSignature<PretransformM4FV4F, true>(generate, (PretransformM4FV4F*)(transform)) .setArgumentNames({"vec", "mat"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Return the transformed vector by transpose of this matrix. " "This function is equivalent to pre-multiplying the matrix.") .get(); } inline FunctionGroup::UniquePtr axprescale(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> m1, v1; arrayUnpack(args[0], m1, B, /*load*/false); arrayUnpack(args[1], v1, B, /*load*/true); assert(m1.size() == 16); assert(v1.size() == 3); // modify first 3 mat rows, all columns for (size_t row = 0; row < 3; ++row) { for (size_t col = 0; col < 4; ++col) { const size_t idx = (row*4) + col; assert(idx <= 11); llvm::Value* m1v = B.CreateLoad(m1[idx]); m1v = binaryOperator(m1v, v1[row], ast::tokens::MULTIPLY, B); B.CreateStore(m1v, m1[idx]); } } // @warning this is invalid for embedded IR return nullptr; }; static auto prescale = [](auto mat, auto vec) { mat->preScale(*vec); }; using PrescaleM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Vec3<double>*); using PrescaleM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Vec3<float>*); return FunctionBuilder("prescale") .addSignature<PrescaleM4D>(generate, (PrescaleM4D*)(prescale)) .addSignature<PrescaleM4F>(generate, (PrescaleM4F*)(prescale)) .setArgumentNames({"transform", "vec"}) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Pre-scale a given matrix by the provided vector.") .get(); } inline FunctionGroup::UniquePtr axtrace(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> m1; arrayUnpack(args[0], m1, B, /*load*/true); const size_t dim = (m1.size() == 9 ? 3 : 4); assert(m1.size() == 9 || m1.size() == 16); llvm::Value* result = binaryOperator(m1[0], m1[1+dim], ast::tokens::PLUS, B); result = binaryOperator(result, m1[2+(2*dim)], ast::tokens::PLUS, B); if (dim == 4) { result = binaryOperator(result, m1[3+(3*dim)], ast::tokens::PLUS, B); } return result; }; static auto trace = [](const auto input) -> auto { using MatType = typename std::remove_pointer<decltype(input)>::type; using ElementT = typename openvdb::ValueTraits<MatType>::ElementType; ElementT value((*input)(static_cast<int>(0), static_cast<int>(0))); for (size_t i = 1; i < MatType::numRows(); ++i) { value += (*input)(static_cast<int>(i), static_cast<int>(i)); } return value; }; using TraceM3D = double(openvdb::math::Mat3<double>*); using TraceM3F = float(openvdb::math::Mat3<float>*); using TraceM4D = double(openvdb::math::Mat4<double>*); using TraceM4F = float(openvdb::math::Mat4<float>*); return FunctionBuilder("trace") .addSignature<TraceM3D>(generate, (TraceM3D*)(trace)) .addSignature<TraceM3F>(generate, (TraceM3F*)(trace)) .addSignature<TraceM4D>(generate, (TraceM4D*)(trace)) .addSignature<TraceM4F>(generate, (TraceM4F*)(trace)) .setArgumentNames({"mat"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Return the trace of a matrix, the sum of the diagonal elements.") .get(); } inline FunctionGroup::UniquePtr axtransform(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> ptrs, m1, v1; arrayUnpack(args[0], ptrs, B, /*load*/false); arrayUnpack(args[1], v1, B, /*load*/true); arrayUnpack(args[2], m1, B, /*load*/true); const size_t vec = v1.size(); const size_t dim = (m1.size() == 9 ? 3 : 4); assert(m1.size() == 9 || m1.size() == 16); assert(vec == 3 || vec == 4); assert(ptrs.size() == vec); // vec * mat llvm::Value* e3 = nullptr, *e4 = nullptr; for (size_t i = 0; i < vec; ++i) { llvm::Value* e1 = binaryOperator(v1[0], m1[i+(0*dim)], ast::tokens::MULTIPLY, B); llvm::Value* e2 = binaryOperator(v1[1], m1[i+(1*dim)], ast::tokens::MULTIPLY, B); if (dim >= 3) e3 = binaryOperator(v1[2], m1[i+(2*dim)], ast::tokens::MULTIPLY, B); if (dim == 4) { if (vec == 3) e4 = m1[i+(3*dim)]; else if (vec == 4) e4 = binaryOperator(v1[3], m1[i+(3*dim)], ast::tokens::MULTIPLY, B); } e1 = binaryOperator(e1, e2, ast::tokens::PLUS, B); if (e3) e1 = binaryOperator(e1, e3, ast::tokens::PLUS, B); if (e4) e1 = binaryOperator(e1, e4, ast::tokens::PLUS, B); B.CreateStore(e1, ptrs[i]); } return nullptr; }; static auto transform = [](auto out, auto vec, auto mat) { *out = mat->transform(*vec); }; using TransformV3DM3D = void(openvdb::math::Vec3<double>*, openvdb::math::Vec3<double>*, openvdb::math::Mat3<double>*); using TransformV3FM3F = void(openvdb::math::Vec3<float>*, openvdb::math::Vec3<float>*, openvdb::math::Mat3<float>*); using TransformV3DM4D = void(openvdb::math::Vec3<double>*, openvdb::math::Vec3<double>*, openvdb::math::Mat4<double>*); using TransformV3FM4F = void(openvdb::math::Vec3<float>*, openvdb::math::Vec3<float>*, openvdb::math::Mat4<float>*); using TransformV4DM4D = void(openvdb::math::Vec4<double>*, openvdb::math::Vec4<double>*, openvdb::math::Mat4<double>*); using TransformV4FM4F = void(openvdb::math::Vec4<float>*, openvdb::math::Vec4<float>*, openvdb::math::Mat4<float>*); return FunctionBuilder("transform") .addSignature<TransformV3DM3D, true>(generate, (TransformV3DM3D*)(transform)) .addSignature<TransformV3FM3F, true>(generate, (TransformV3FM3F*)(transform)) .addSignature<TransformV3DM4D, true>(generate, (TransformV3DM4D*)(transform)) .addSignature<TransformV3FM4F, true>(generate, (TransformV3FM4F*)(transform)) .addSignature<TransformV4DM4D, true>(generate, (TransformV4DM4D*)(transform)) .addSignature<TransformV4FM4F, true>(generate, (TransformV4FM4F*)(transform)) .setArgumentNames({"vec", "mat"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Return the transformed vector by the provided " "matrix. This function is equivalent to post-multiplying the matrix, i.e. vec * mult.") .get(); } inline FunctionGroup::UniquePtr axtranspose(const FunctionOptions& op) { static auto generate = [](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { std::vector<llvm::Value*> ptrs, m1; arrayUnpack(args[0], ptrs, B, /*load*/false); arrayUnpack(args[1], m1, B, /*load*/true); assert(m1.size() == 9 || m1.size() == 16); assert(ptrs.size() == m1.size()); const size_t dim = m1.size() == 9 ? 3 : 4; for (size_t i = 0; i < dim; ++i) { for (size_t j = 0; j < dim; ++j) { const size_t source = (i*dim) + j; const size_t target = (j*dim) + i; B.CreateStore(m1[source], ptrs[target]); } } return nullptr; }; static auto transpose = [](auto out, auto in) { *out = in->transpose(); }; using TransposeM3D = void(openvdb::math::Mat3<double>*, openvdb::math::Mat3<double>*); using TransposeM3F = void(openvdb::math::Mat3<float>*, openvdb::math::Mat3<float>*); using TransposeM4D = void(openvdb::math::Mat4<double>*, openvdb::math::Mat4<double>*); using TransposeM4F = void(openvdb::math::Mat4<float>*, openvdb::math::Mat4<float>*); return FunctionBuilder("transpose") .addSignature<TransposeM3D, true>(generate, (TransposeM3D*)(transpose)) .addSignature<TransposeM3F, true>(generate, (TransposeM3F*)(transpose)) .addSignature<TransposeM4D, true>(generate, (TransposeM4D*)(transpose)) .addSignature<TransposeM4F, true>(generate, (TransposeM4F*)(transpose)) .setArgumentNames({"mat"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Returns the transpose of a matrix") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Noise inline FunctionGroup::UniquePtr axsimplexnoise(const FunctionOptions& op) { static auto simplexnoisex = [](double x) -> double { return SimplexNoise::noise(x, 0.0, 0.0); }; static auto simplexnoisexy = [](double x, double y) -> double { return SimplexNoise::noise(x, y, 0.0); }; static auto simplexnoisexyz = [](double x, double y, double z) -> double { return SimplexNoise::noise(x, y, z); }; static auto simplexnoisev = [](const openvdb::math::Vec3<double>* v) -> double { return SimplexNoise::noise((*v)[0], (*v)[1], (*v)[2]); }; return FunctionBuilder("simplexnoise") .addSignature<double(double)>(simplexnoisex) .setArgumentNames({"x"}) .setConstantFold(false) .addSignature<double(double, double)>(simplexnoisexy) .setArgumentNames({"x", "y"}) .setConstantFold(false) .addSignature<double(double,double,double)>(simplexnoisexyz) .setArgumentNames({"x", "y", "z"}) .setConstantFold(false) .addSignature<double(const openvdb::math::Vec3<double>*)>(simplexnoisev) .setArgumentNames({"pos"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Compute simplex noise at coordinates x, y and z. Coordinates which are " "not provided will be set to 0.") .get(); } inline FunctionGroup::UniquePtr axcurlsimplexnoise(const FunctionOptions& op) { using CurlSimplexNoiseV3D = void(double(*)[3], const double(*)[3]); using CurlSimplexNoiseD = void(double(*)[3], double, double, double); return FunctionBuilder("curlsimplexnoise") .addSignature<CurlSimplexNoiseV3D, true>( (CurlSimplexNoiseV3D*)(openvdb::ax::math::curlnoise<SimplexNoise>)) .setArgumentNames({"pos"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .addSignature<CurlSimplexNoiseD, true>( (CurlSimplexNoiseD*)(openvdb::ax::math::curlnoise<SimplexNoise>)) .setArgumentNames({"pos"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) // alloced by the function, always no alias .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::InlineHint) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Generates divergence-free 3D noise, computed using a " "curl function on Simplex Noise.") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Trig/Hyperbolic /// @todo Depending on the platform, some of these methods may be available though /// LLVM as "intrinsics". To avoid conflicts, we currently only expose the C /// bindings. We should perhaps override the C Bindings if the method exists /// in LLVM, so long as it's clear that these methods may produce different /// results from stdlib. /// @note See the following LLVM files for some details: /// Analysis/TargetLibraryInfo.def /// Analysis/ConstantFolding.cpp /// Analysis/TargetLibraryInfo.cpp /// DEFINE_AX_C_FP_BINDING(acos, "Computes the principal value of the arc cosine of the input.") DEFINE_AX_C_FP_BINDING(acosh, "Computes the inverse hyperbolic cosine of the input.") DEFINE_AX_C_FP_BINDING(asin, "Computes the principal value of the arc sine of the input.") DEFINE_AX_C_FP_BINDING(asinh, "Computes the inverse hyperbolic sine of the input.") DEFINE_AX_C_FP_BINDING(atan, "Computes the principal value of the arc tangent of the input.") DEFINE_AX_C_FP_BINDING(atanh, "Computes the inverse hyperbolic tangent of the input.") DEFINE_AX_C_FP_BINDING(cosh, "Computes the hyperbolic cosine of the input.") DEFINE_AX_C_FP_BINDING(sinh, "Computes the hyperbolic sine of the input.") DEFINE_AX_C_FP_BINDING(tanh, "Computes the hyperbolic tangent of the input.") inline FunctionGroup::UniquePtr axtan(const FunctionOptions& op) { // @todo consider using this IR implementation over std::tan, however // we then lose constant folding (as results don't match). Ideally // this ir implementation should exist at compile time as a valid // function for constant folding // // static auto generate = // [](const std::vector<llvm::Value*>& args, // const std::unordered_map<std::string, llvm::Value*>&, // llvm::IRBuilder<>& B) -> llvm::Value* // { // llvm::Module* M = B.GetInsertBlock()->getParent()->getParent(); // llvm::Type* type = args[0]->getType(); // llvm::Function* sinFunction = // llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::sin, type); // llvm::Function* cosFunction = // llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::cos, type); // llvm::Value* sin = B.CreateCall(sinFunction, args[0]); // llvm::Value* cos = B.CreateCall(cosFunction, args[0]); // return binaryOperator(sin, cos, ast::tokens::DIVIDE, B); // }; return FunctionBuilder("tan") .addSignature<double(double)>((double(*)(double))(std::tan)) .addSignature<float(float)>((float(*)(float))(std::tan)) .setArgumentNames({"n"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Computes the tangent of arg (measured in radians).") .get(); } inline FunctionGroup::UniquePtr axatan2(const FunctionOptions& op) { return FunctionBuilder("atan2") .addSignature<double(double,double)>((double(*)(double,double))(std::atan2)) .addSignature<float(float,float)>((float(*)(float,float))(std::atan2)) .setArgumentNames({"y", "x"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Computes the arc tangent of y/x using the signs of arguments " "to determine the correct quadrant.") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // String inline FunctionGroup::UniquePtr axatoi(const FunctionOptions& op) { // WARNING: decltype removes the throw identifer from atoi. We should // use this are automatically update the function attributes as appropriate return FunctionBuilder("atoi") .addSignature<decltype(std::atoi)>(std::atoi) .setArgumentNames({"str"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Parses the string input interpreting its " "content as an integral number, which is returned as a value of type int.") .get(); } inline FunctionGroup::UniquePtr axatof(const FunctionOptions& op) { // WARNING: decltype removes the throw identifer from atof. We should // use this are automatically update the function attributes as appropriate return FunctionBuilder("atof") .addSignature<decltype(std::atof)>(std::atof) .setArgumentNames({"str"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Parses the string input, interpreting its " "content as a floating point number and returns its value as a double.") .get(); } inline FunctionGroup::UniquePtr axhash(const FunctionOptions& op) { static auto hash = [](const AXString* axstr) -> int64_t { const std::string str(axstr->ptr, axstr->size); return static_cast<int64_t>(std::hash<std::string>{}(str)); }; return FunctionBuilder("hash") .addSignature<int64_t(const AXString*)>((int64_t(*)(const AXString*))(hash)) .setArgumentNames({"str"}) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::NoUnwind) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(op.mConstantFoldCBindings) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Return a hash of the provided string.") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Utility inline FunctionGroup::UniquePtr axprint(const FunctionOptions& op) { static auto print = [](auto v) { std::cout << v << std::endl; }; static auto printv = [](auto* v) { std::cout << *v << std::endl; }; static auto printstr = [](const AXString* axstr) { const std::string str(axstr->ptr, axstr->size); std::cout << str << std::endl; }; return FunctionBuilder("print") .addSignature<void(double)>((void(*)(double))(print)) .addSignature<void(float)>((void(*)(float))(print)) .addSignature<void(int64_t)>((void(*)(int64_t))(print)) .addSignature<void(int32_t)>((void(*)(int32_t))(print)) .setArgumentNames({"n"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(false /*never cf*/) .addSignature<void(const AXString*)>((void(*)(const AXString*))(printstr)) .addSignature<void(openvdb::math::Vec2<int32_t>*)>((void(*)(openvdb::math::Vec2<int32_t>*))(printv)) .addSignature<void(openvdb::math::Vec2<float>*)>((void(*)(openvdb::math::Vec2<float>*))(printv)) .addSignature<void(openvdb::math::Vec2<double>*)>((void(*)(openvdb::math::Vec2<double>*))(printv)) .addSignature<void(openvdb::math::Vec3<int32_t>*)>((void(*)(openvdb::math::Vec3<int32_t>*))(printv)) .addSignature<void(openvdb::math::Vec3<float>*)>((void(*)(openvdb::math::Vec3<float>*))(printv)) .addSignature<void(openvdb::math::Vec3<double>*)>((void(*)(openvdb::math::Vec3<double>*))(printv)) .addSignature<void(openvdb::math::Vec4<int32_t>*)>((void(*)(openvdb::math::Vec4<int32_t>*))(printv)) .addSignature<void(openvdb::math::Vec4<float>*)>((void(*)(openvdb::math::Vec4<float>*))(printv)) .addSignature<void(openvdb::math::Vec4<double>*)>((void(*)(openvdb::math::Vec4<double>*))(printv)) .addSignature<void(openvdb::math::Mat3<float>*)>((void(*)(openvdb::math::Mat3<float>*))(printv)) .addSignature<void(openvdb::math::Mat3<double>*)>((void(*)(openvdb::math::Mat3<double>*))(printv)) .addSignature<void(openvdb::math::Mat4<float>*)>((void(*)(openvdb::math::Mat4<float>*))(printv)) .addSignature<void(openvdb::math::Mat4<double>*)>((void(*)(openvdb::math::Mat4<double>*))(printv)) .addParameterAttribute(0, llvm::Attribute::ReadOnly) .setArgumentNames({"n"}) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .addFunctionAttribute(llvm::Attribute::AlwaysInline) .setConstantFold(false /*never cf*/) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Prints the input to the standard output stream. " "Warning: This will be run for every element.") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Custom inline FunctionGroup::UniquePtr ax_external(const FunctionOptions& op) { static auto find = [](auto out, const void* const data, const AXString* const name) { using ValueType = typename std::remove_pointer<decltype(out)>::type; const ax::CustomData* const customData = static_cast<const ax::CustomData*>(data); const std::string nameStr(name->ptr, name->size); const TypedMetadata<ValueType>* const metaData = customData->getData<TypedMetadata<ValueType>>(nameStr); *out = (metaData ? metaData->value() : zeroVal<ValueType>()); }; using FindF = void(float*, const void* const, const AXString* const); using FindV3F = void(openvdb::math::Vec3<float>*, const void* const, const AXString* const); return FunctionBuilder("_external") .addSignature<FindF>((FindF*)(find)) .addSignature<FindV3F>((FindV3F*)(find)) .setArgumentNames({"str", "custom_data", "result"}) .addParameterAttribute(0, llvm::Attribute::NoAlias) .addParameterAttribute(0, llvm::Attribute::WriteOnly) .addParameterAttribute(1, llvm::Attribute::ReadOnly) .addParameterAttribute(2, llvm::Attribute::ReadOnly) .setConstantFold(false) .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Internal function for looking up a custom float value.") .get(); } inline FunctionGroup::UniquePtr axexternal(const FunctionOptions& op) { auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { // Pull out the custom data from the parent function llvm::Function* compute = B.GetInsertBlock()->getParent(); assert(compute); assert(std::string(compute->getName()).rfind("ax.compute", 0) == 0); llvm::Value* arg = extractArgument(compute, 0); assert(arg); assert(arg->getName() == "custom_data"); std::vector<llvm::Value*> inputs; inputs.reserve(2 + args.size()); inputs.emplace_back(insertStaticAlloca(B, LLVMType<float>::get(B.getContext()))); inputs.emplace_back(arg); inputs.insert(inputs.end(), args.begin(), args.end()); ax_external(op)->execute(inputs, B); return B.CreateLoad(inputs.front()); }; return FunctionBuilder("external") .addSignature<float(const AXString*)>(generate) .setArgumentNames({"str"}) .addDependency("_external") .addParameterAttribute(0, llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::ReadOnly) .addFunctionAttribute(llvm::Attribute::NoRecurse) .setConstantFold(false) .setEmbedIR(true) // always embed as we pass through function param "custom_data" .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Find a custom user parameter with a given name of type 'float' " "in the Custom data provided to the AX compiler. If the data can not be found, " "or is not of the expected type 0.0f is returned.") .get(); } inline FunctionGroup::UniquePtr axexternalv(const FunctionOptions& op) { auto generate = [op](const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) -> llvm::Value* { // Pull out the custom data from the parent function llvm::Function* compute = B.GetInsertBlock()->getParent(); assert(compute); assert(std::string(compute->getName()).rfind("ax.compute", 0) == 0); llvm::Value* arg = extractArgument(compute, 0); assert(arg); assert(arg->getName() == "custom_data"); std::vector<llvm::Value*> inputs; inputs.reserve(2 + args.size()); inputs.emplace_back(insertStaticAlloca(B, LLVMType<float[3]>::get(B.getContext()))); inputs.emplace_back(arg); inputs.insert(inputs.end(), args.begin(), args.end()); ax_external(op)->execute(inputs, B); return inputs.front(); }; return FunctionBuilder("externalv") .addSignature<openvdb::math::Vec3<float>*(const AXString*)>(generate) .setArgumentNames({"str"}) .addDependency("_external") .addParameterAttribute(0, llvm::Attribute::ReadOnly) .setConstantFold(false) .setEmbedIR(true) // always embed as we pass through function param "custom_data" .setPreferredImpl(op.mPrioritiseIR ? FunctionBuilder::IR : FunctionBuilder::C) .setDocumentation("Find a custom user parameter with a given name of type 'vector float' " "in the Custom data provided to the AX compiler. If the data can not be found, or is " "not of the expected type { 0.0f, 0.0f, 0.0f } is returned.") .get(); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// void insertStandardFunctions(FunctionRegistry& registry, const FunctionOptions* options) { const bool create = options && !options->mLazyFunctions; auto add = [&](const std::string& name, const FunctionRegistry::ConstructorT creator, const bool internal = false) { if (create) registry.insertAndCreate(name, creator, *options, internal); else registry.insert(name, creator, internal); }; // llvm instrinsics add("ceil", llvm_ceil); add("cos", llvm_cos); add("exp2", llvm_exp2); add("exp", llvm_exp); add("fabs", llvm_fabs); add("floor", llvm_floor); add("log10", llvm_log10); add("log2", llvm_log2); add("log", llvm_log); add("pow", llvm_pow); add("round", llvm_round); add("sin", llvm_sin); add("sqrt", llvm_sqrt); // math add("abs", axabs); add("cbrt", axcbrt); add("clamp", axclamp); add("cross", axcross); add("dot", axdot); add("euclideanmod", axeuclideanmod); add("fit", axfit); add("floormod", axfloormod); add("length", axlength); add("lengthsq", axlengthsq); add("lerp", axlerp); add("max", axmax); add("min", axmin); add("normalize", axnormalize); add("rand", axrand); add("rand32", axrand32); add("sign", axsign); add("signbit", axsignbit); add("truncatemod", axtruncatemod); // matrix math add("determinant", axdeterminant); add("diag", axdiag); add("identity3", axidentity3); add("identity4", axidentity4); add("mmmult", axmmmult, true); add("polardecompose", axpolardecompose); add("postscale", axpostscale); add("prescale", axprescale); add("pretransform", axpretransform); add("trace", axtrace); add("transform", axtransform); add("transpose", axtranspose); // noise add("simplexnoise", axsimplexnoise); add("curlsimplexnoise", axcurlsimplexnoise); // trig add("acos", axacos); add("acosh", axacosh); add("asin", axasin); add("asinh", axasinh); add("atan", axatan); add("atan2", axatan2); add("atanh", axatanh); add("cosh", axcosh); add("sinh", axsinh); add("tan", axtan); add("tanh", axtanh); // string add("atoi", axatoi); add("atof", axatof); add("hash", axhash); // util add("print", axprint); // custom add("_external", ax_external, true); add("external", axexternal); add("externalv", axexternalv); } } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
106,984
C++
44.955756
126
0.60223
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/Types.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/Types.cc /// /// @authors Nick Avramoussis /// #include "Types.h" namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief Returns an llvm IntegerType given a requested size and context /// @param size The number of bits of the integer type /// @param C The LLVMContext to request the Type from. /// llvm::IntegerType* llvmIntType(const uint32_t size, llvm::LLVMContext& C) { switch (size) { case 1 : return llvm::cast<llvm::IntegerType>(LLVMType<bool>::get(C)); case 8 : return llvm::cast<llvm::IntegerType>(LLVMType<int8_t>::get(C)); case 16 : return llvm::cast<llvm::IntegerType>(LLVMType<int16_t>::get(C)); case 32 : return llvm::cast<llvm::IntegerType>(LLVMType<int32_t>::get(C)); case 64 : return llvm::cast<llvm::IntegerType>(LLVMType<int64_t>::get(C)); default : return llvm::Type::getIntNTy(C, size); } } /// @brief Returns an llvm floating point Type given a requested size and context /// @param size The size of the float to request, i.e. float - 32, double - 64 etc. /// @param C The LLVMContext to request the Type from. /// llvm::Type* llvmFloatType(const uint32_t size, llvm::LLVMContext& C) { switch (size) { case 32 : return LLVMType<float>::get(C); case 64 : return LLVMType<double>::get(C); default : OPENVDB_THROW(AXCodeGenError, "Invalid float size requested from LLVM Context"); } } /// @brief Returns an llvm type representing a type defined by a string. /// @note For string types, this function returns the element type, not the /// object type! The llvm type representing a char block of memory /// is LLVMType<char*>::get(C); /// @param type The name of the type to request. /// @param C The LLVMContext to request the Type from. /// llvm::Type* llvmTypeFromToken(const ast::tokens::CoreType& type, llvm::LLVMContext& C) { switch (type) { case ast::tokens::BOOL : return LLVMType<bool>::get(C); case ast::tokens::INT16 : return LLVMType<int16_t>::get(C); case ast::tokens::INT32 : return LLVMType<int32_t>::get(C); case ast::tokens::INT64 : return LLVMType<int64_t>::get(C); case ast::tokens::FLOAT : return LLVMType<float>::get(C); case ast::tokens::DOUBLE : return LLVMType<double>::get(C); case ast::tokens::VEC2I : return LLVMType<int32_t[2]>::get(C); case ast::tokens::VEC2F : return LLVMType<float[2]>::get(C); case ast::tokens::VEC2D : return LLVMType<double[2]>::get(C); case ast::tokens::VEC3I : return LLVMType<int32_t[3]>::get(C); case ast::tokens::VEC3F : return LLVMType<float[3]>::get(C); case ast::tokens::VEC3D : return LLVMType<double[3]>::get(C); case ast::tokens::VEC4I : return LLVMType<int32_t[4]>::get(C); case ast::tokens::VEC4F : return LLVMType<float[4]>::get(C); case ast::tokens::VEC4D : return LLVMType<double[4]>::get(C); case ast::tokens::MAT3F : return LLVMType<float[9]>::get(C); case ast::tokens::MAT3D : return LLVMType<double[9]>::get(C); case ast::tokens::MAT4F : return LLVMType<float[16]>::get(C); case ast::tokens::MAT4D : return LLVMType<double[16]>::get(C); case ast::tokens::STRING : return LLVMType<AXString>::get(C); case ast::tokens::UNKNOWN : default : OPENVDB_THROW(AXCodeGenError, "Token type not recognised in request for LLVM type"); } } ast::tokens::CoreType tokenFromLLVMType(const llvm::Type* type) { if (type->isPointerTy()) { type = type->getPointerElementType(); } if (type->isIntegerTy(1)) return ast::tokens::BOOL; if (type->isIntegerTy(16)) return ast::tokens::INT16; if (type->isIntegerTy(32)) return ast::tokens::INT32; if (type->isIntegerTy(64)) return ast::tokens::INT64; if (type->isFloatTy()) return ast::tokens::FLOAT; if (type->isDoubleTy()) return ast::tokens::DOUBLE; if (type->isArrayTy()) { const ast::tokens::CoreType elementType = tokenFromLLVMType(type->getArrayElementType()); const size_t size = type->getArrayNumElements(); if (size == 2) { if (elementType == ast::tokens::INT32) return ast::tokens::VEC2I; if (elementType == ast::tokens::FLOAT) return ast::tokens::VEC2F; if (elementType == ast::tokens::DOUBLE) return ast::tokens::VEC2D; } else if (size == 3) { if (elementType == ast::tokens::INT32) return ast::tokens::VEC3I; if (elementType == ast::tokens::FLOAT) return ast::tokens::VEC3F; if (elementType == ast::tokens::DOUBLE) return ast::tokens::VEC3D; } else if (size == 4) { if (elementType == ast::tokens::INT32) return ast::tokens::VEC4I; if (elementType == ast::tokens::FLOAT) return ast::tokens::VEC4F; if (elementType == ast::tokens::DOUBLE) return ast::tokens::VEC4D; } else if (size == 9) { if (elementType == ast::tokens::FLOAT) return ast::tokens::MAT3F; if (elementType == ast::tokens::DOUBLE) return ast::tokens::MAT3D; } else if (size == 16) { if (elementType == ast::tokens::FLOAT) return ast::tokens::MAT4F; if (elementType == ast::tokens::DOUBLE) return ast::tokens::MAT4D; } } if (type == LLVMType<AXString>::get(type->getContext())) { return ast::tokens::STRING; } return ast::tokens::UNKNOWN; } } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
5,893
C++
40.801418
84
0.61344
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionTypes.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/FunctionTypes.cc #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../Exceptions.h" #include <openvdb/util/Name.h> #include <llvm/IR/Function.h> #include <llvm/IR/LLVMContext.h> #include <llvm/Support/raw_os_ostream.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { namespace { inline void printType(const llvm::Type* type, llvm::raw_os_ostream& stream, const bool axTypes) { const ast::tokens::CoreType token = axTypes ? tokenFromLLVMType(type) : ast::tokens::UNKNOWN; if (token == ast::tokens::UNKNOWN) type->print(stream); else stream << ast::tokens::typeStringFromToken(token); } inline void printTypes(llvm::raw_os_ostream& stream, const std::vector<llvm::Type*>& types, const std::vector<const char*>& names = {}, const std::string sep = "; ", const bool axTypes = false) { if (types.empty()) return; auto typeIter = types.cbegin(); std::vector<const char*>::const_iterator nameIter; if (!names.empty()) nameIter = names.cbegin(); for (; typeIter != types.cend() - 1; ++typeIter) { printType(*typeIter, stream, axTypes); if (!names.empty() && nameIter != names.cend()) { if (*nameIter && (*nameIter)[0] != '\0') { stream << ' ' << *nameIter; } ++nameIter; } stream << sep; } printType(*typeIter, stream, axTypes); if (!names.empty() && nameIter != names.cend()) { if (*nameIter && (*nameIter)[0] != '\0') { stream << ' ' << *nameIter; } } } } void printSignature(std::ostream& os, const std::vector<llvm::Type*>& signature, const llvm::Type* returnType, const char* name, const std::vector<const char*>& names, const bool axTypes) { llvm::raw_os_ostream stream(os); printType(returnType, stream, axTypes); if (name && name[0] != '\0') { stream << " " << name; } stream << '('; printTypes(stream, signature, names, "; ", axTypes); stream << ')'; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// llvm::Function* Function::create(llvm::LLVMContext& C, llvm::Module* M) const { if (M) { if (llvm::Function* function = M->getFunction(this->symbol())) { return function; } } std::vector<llvm::Type*> parms; parms.reserve(this->size()); llvm::Type* ret = this->types(parms, C); llvm::FunctionType* type = llvm::FunctionType::get(ret, parms, false); // varargs llvm::Function* function = llvm::Function::Create(type, llvm::Function::ExternalLinkage, this->symbol(), M); function->setAttributes(this->flattenAttrs(C)); return function; } llvm::Value* Function::call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const { llvm::BasicBlock* block = B.GetInsertBlock(); assert(block); llvm::Function* currentFunction = block->getParent(); assert(currentFunction); llvm::Module* M = currentFunction->getParent(); assert(M); llvm::Function* function = this->create(B.getContext(), M); std::vector<llvm::Value*> inputs(args); if (cast) { std::vector<llvm::Type*> types; this->types(types, B.getContext()); this->cast(inputs, types, B); } return B.CreateCall(function, inputs); } Function::SignatureMatch Function::match(const std::vector<llvm::Type*>& inputs, llvm::LLVMContext& C) const { // these checks mean we can design the match function signature to not // require the llvm context and instead pull it out of the type vector // which is guaranteed to not be empty if (inputs.size() != this->size()) return None; if (inputs.empty() && this->size() == 0) return Explicit; assert(!inputs.empty()); //llvm::LLVMContext& C = inputs.front()->getContext(); std::vector<llvm::Type*> signature; this->types(signature, C); if (inputs == signature) return Explicit; llvm::Type* strType = LLVMType<AXString>::get(C); // try implicit - signature should not be empty here for (size_t i = 0; i < signature.size(); ++i) { llvm::Type* from = inputs[i]; llvm::Type* to = signature[i]; // if exactly matching, continue if (from == to) continue; // if arg is a ptr and is not marked as readonly, fail - memory will be modified if (to->isPointerTy() && !this->hasParamAttribute(i, llvm::Attribute::AttrKind::ReadOnly)) return Size; // compare contained types if both are pointers if (from->isPointerTy() && to->isPointerTy()) { from = from->getContainedType(0); to = to->getContainedType(0); } // allow for string->char*. Note that this is only allowed from inputs->signature if (from == strType && to == LLVMType<char>::get(C)) continue; if (!isValidCast(from, to)) return Size; } return Implicit; } void Function::print(llvm::LLVMContext& C, std::ostream& os, const char* name, const bool axTypes) const { std::vector<llvm::Type*> current; llvm::Type* ret = this->types(current, C); std::vector<const char*> names; names.reserve(this->size()); for (size_t i = 0; i < this->size(); ++i) { names.emplace_back(this->argName(i)); } printSignature(os, current, ret, name, names, axTypes); } void Function::cast(std::vector<llvm::Value*>& args, const std::vector<llvm::Type*>& types, llvm::IRBuilder<>& B) { llvm::LLVMContext& C = B.getContext(); for (size_t i = 0; i < args.size(); ++i) { if (i >= types.size()) break; llvm::Value*& value = args[i]; llvm::Type* type = value->getType(); if (type->isIntegerTy() || type->isFloatingPointTy()) { if (types[i]->isIntegerTy(1)) { // assume boolean target value value = boolComparison(value, B); } else { value = arithmeticConversion(value, types[i], B); } } else if (type->getContainedType(0)->isArrayTy()) { llvm::Type* arrayType = getBaseContainedType(types[i]); value = arrayCast(value, arrayType->getArrayElementType(), B); } else { if (types[i] == LLVMType<char*>::get(C)) { llvm::Type* strType = LLVMType<AXString>::get(C); if (type->getContainedType(0) == strType) { value = B.CreateStructGEP(strType, value, 0); // char** value = B.CreateLoad(value); // char* } } } } } llvm::AttributeList Function::flattenAttrs(llvm::LLVMContext& C) const { if (!mAttributes) return llvm::AttributeList(); auto buildSetFromKinds = [&C](llvm::AttrBuilder& ab, const std::vector<llvm::Attribute::AttrKind>& kinds) -> llvm::AttributeSet { for (auto& attr : kinds) { ab.addAttribute(attr); } const llvm::AttributeSet set = llvm::AttributeSet::get(C, ab); ab.clear(); return set; }; llvm::AttrBuilder ab; const llvm::AttributeSet fn = buildSetFromKinds(ab, mAttributes->mFnAttrs); const llvm::AttributeSet ret = buildSetFromKinds(ab, mAttributes->mRetAttrs); std::vector<llvm::AttributeSet> parms(this->size()); for (auto& idxAttr : mAttributes->mParamAttrs) { const size_t idx = idxAttr.first; if (idx >= this->size()) continue; parms[idx] = buildSetFromKinds(ab, idxAttr.second); } return llvm::AttributeList::get(C, fn, ret, parms); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// llvm::Function* IRFunctionBase::create(llvm::LLVMContext& C, llvm::Module* M) const { if (this->hasEmbedIR()) return nullptr; llvm::Function* F = this->Function::create(C, M); assert(F); // return if the function has already been generated or if no // module has been provided (just the function prototype requested) if (!F->empty() || !M) return F; // generate the body llvm::BasicBlock* BB = llvm::BasicBlock::Create(C, "entry_" + std::string(this->symbol()), F); std::vector<llvm::Value*> fnargs; fnargs.reserve(this->size()); for (auto arg = F->arg_begin(), arg_end = F->arg_end(); arg != arg_end; ++arg) { fnargs.emplace_back(llvm::cast<llvm::Value>(arg)); } // create a new builder per function (its lightweight) // @todo could pass in the builder similar to Function::call llvm::IRBuilder<> B(BB); llvm::Value* lastInstruction = mGen(fnargs, B); // Allow the user to return a nullptr, an actual value or a return // instruction from the generator callback. This facilitates the same // generator being used for inline IR // if nullptr, insert a ret void inst, otherwise if it's not a return // instruction, either return the value if its supported or insert a // ret void if (!lastInstruction) { // @note if the ret type is not expected to be void, this will // cause verifyResultType to throw lastInstruction = B.CreateRetVoid(); } else if (!llvm::isa<llvm::ReturnInst>(lastInstruction)) { assert(lastInstruction); if (lastInstruction->getType()->isVoidTy()) { lastInstruction = B.CreateRetVoid(); } else { lastInstruction = B.CreateRet(lastInstruction); } } assert(lastInstruction); assert(llvm::isa<llvm::ReturnInst>(lastInstruction)); // pull out the ret type - is null if void llvm::Value* rvalue = llvm::cast<llvm::ReturnInst> (lastInstruction)->getReturnValue(); llvm::Type* type = rvalue ? rvalue->getType() : llvm::Type::getVoidTy(C); this->verifyResultType(type, F->getReturnType()); return F; } llvm::Value* IRFunctionBase::call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const { if (!this->hasEmbedIR()) { return this->Function::call(args, B, cast); } std::vector<llvm::Value*> inputs(args); if (cast) { std::vector<llvm::Type*> types; this->types(types, B.getContext()); this->cast(inputs, types, B); } llvm::Value* result = mGen(inputs, B); if (result) { // only verify if result is not nullptr to // allow for embedded instructions std::vector<llvm::Type*> unused; this->verifyResultType(result->getType(), this->types(unused, B.getContext())); } return result; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// Function::Ptr FunctionGroup::match(const std::vector<llvm::Type*>& types, llvm::LLVMContext& C, Function::SignatureMatch* type) const { Function::Ptr targetFunction; if (type) *type = Function::SignatureMatch::None; for (const auto& function : mFunctionList) { const Function::SignatureMatch matchtype = function->match(types, C); if (type) *type = std::max(matchtype, *type); if (matchtype == Function::SignatureMatch::None) continue; else if (matchtype == Function::SignatureMatch::Size) continue; else if (matchtype == Function::SignatureMatch::Explicit) { return function; } else if (matchtype == Function::SignatureMatch::Implicit) { if (!targetFunction) targetFunction = function; } } return targetFunction; } llvm::Value* FunctionGroup::execute(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) const { std::vector<llvm::Type*> inputTypes; valuesToTypes(args, inputTypes); llvm::LLVMContext& C = B.getContext(); Function::SignatureMatch match; const Function::Ptr target = this->match(inputTypes, C, &match); llvm::Value* result = nullptr; if (!target) return result; if (match == Function::SignatureMatch::Implicit) { result = target->call(args, B, /*cast=*/true); } else { // match == Function::SignatureMatch::Explicit result = target->call(args, B, /*cast=*/false); } assert(result); return result; } } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
12,977
C++
29.753554
89
0.574324
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/PointExecutable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/PointExecutable.cc #include "PointExecutable.h" #include "../Exceptions.h" // @TODO refactor so we don't have to include PointComputeGenerator.h, // but still have the functions defined in one place #include "../codegen/PointComputeGenerator.h" #include "../codegen/PointLeafLocalData.h" #include <openvdb/Types.h> #include <openvdb/points/AttributeArray.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointConversion.h> // ConversionTraits #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointGroup.h> #include <openvdb/points/PointMask.h> #include <openvdb/points/PointMove.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { struct PointExecutable::Settings { bool mCreateMissing = true; size_t mGrainSize = 1; std::string mGroup = ""; }; namespace { /// @brief Point Kernel types /// using KernelFunctionPtr = std::add_pointer<codegen::PointKernel::Signature>::type; using FunctionTraitsT = codegen::PointKernel::FunctionTraitsT; using ReturnT = FunctionTraitsT::ReturnType; using PointLeafLocalData = codegen::codegen_internal::PointLeafLocalData; /// @brief The arguments of the generated function /// struct PointFunctionArguments { using LeafT = points::PointDataTree::LeafNodeType; /// @brief Base untyped handle struct for container storage struct Handles { using UniquePtr = std::unique_ptr<Handles>; virtual ~Handles() = default; }; /// @brief A wrapper around a VDB Points Attribute Handle, allowing for /// typed storage of a read or write handle. This is used for /// automatic memory management and void pointer passing into the /// generated point functions template <typename ValueT> struct TypedHandle final : public Handles { using UniquePtr = std::unique_ptr<TypedHandle<ValueT>>; using HandleTraits = points::point_conversion_internal::ConversionTraits<ValueT>; using HandleT = typename HandleTraits::Handle; ~TypedHandle() override final = default; inline void* initReadHandle(const LeafT& leaf, const size_t pos) { mHandle = HandleTraits::handleFromLeaf(leaf, static_cast<Index>(pos)); return static_cast<void*>(mHandle.get()); } inline void* initWriteHandle(LeafT& leaf, const size_t pos) { mHandle = HandleTraits::writeHandleFromLeaf(leaf, static_cast<Index>(pos)); return static_cast<void*>(mHandle.get()); } private: typename HandleT::Ptr mHandle; }; /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// PointFunctionArguments(const KernelFunctionPtr function, const CustomData* const customData, const points::AttributeSet& attributeSet, PointLeafLocalData* const leafLocalData) : mFunction(function) , mCustomData(customData) , mAttributeSet(&attributeSet) , mVoidAttributeHandles() , mAttributeHandles() , mVoidGroupHandles() , mGroupHandles() , mLeafLocalData(leafLocalData) {} /// @brief Given a built version of the function signature, automatically /// bind the current arguments and return a callable function /// which takes no arguments inline auto bind() { return [&](const uint64_t index) -> ReturnT { return mFunction(static_cast<FunctionTraitsT::Arg<0>::Type>(mCustomData), static_cast<FunctionTraitsT::Arg<1>::Type>(mAttributeSet), static_cast<FunctionTraitsT::Arg<2>::Type>(index), static_cast<FunctionTraitsT::Arg<3>::Type>(mVoidAttributeHandles.data()), static_cast<FunctionTraitsT::Arg<4>::Type>(mVoidGroupHandles.data()), static_cast<FunctionTraitsT::Arg<5>::Type>(mLeafLocalData)); }; } template <typename ValueT> inline void addHandle(const LeafT& leaf, const size_t pos) { typename TypedHandle<ValueT>::UniquePtr handle(new TypedHandle<ValueT>()); mVoidAttributeHandles.emplace_back(handle->initReadHandle(leaf, pos)); mAttributeHandles.emplace_back(std::move(handle)); } template <typename ValueT> inline void addWriteHandle(LeafT& leaf, const size_t pos) { typename TypedHandle<ValueT>::UniquePtr handle(new TypedHandle<ValueT>()); mVoidAttributeHandles.emplace_back(handle->initWriteHandle(leaf, pos)); mAttributeHandles.emplace_back(std::move(handle)); } inline void addGroupHandle(const LeafT& leaf, const std::string& name) { assert(leaf.attributeSet().descriptor().hasGroup(name)); mGroupHandles.emplace_back(new points::GroupHandle(leaf.groupHandle(name))); mVoidGroupHandles.emplace_back(static_cast<void*>(mGroupHandles.back().get())); } inline void addGroupWriteHandle(LeafT& leaf, const std::string& name) { assert(leaf.attributeSet().descriptor().hasGroup(name)); mGroupHandles.emplace_back(new points::GroupWriteHandle(leaf.groupWriteHandle(name))); mVoidGroupHandles.emplace_back(static_cast<void*>(mGroupHandles.back().get())); } inline void addNullGroupHandle() { mVoidGroupHandles.emplace_back(nullptr); } inline void addNullAttribHandle() { mVoidAttributeHandles.emplace_back(nullptr); } private: const KernelFunctionPtr mFunction; const CustomData* const mCustomData; const points::AttributeSet* const mAttributeSet; std::vector<void*> mVoidAttributeHandles; std::vector<Handles::UniquePtr> mAttributeHandles; std::vector<void*> mVoidGroupHandles; #if (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER > 7 || \ (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER >= 7 && \ OPENVDB_LIBRARY_MINOR_VERSION_NUMBER >= 1)) std::vector<points::GroupHandle::UniquePtr> mGroupHandles; #else std::vector<std::unique_ptr<points::GroupHandle>> mGroupHandles; #endif PointLeafLocalData* const mLeafLocalData; }; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// template<typename FilterT = openvdb::points::NullFilter> struct PointExecuterDeformer { PointExecuterDeformer(const std::string& positionAttribute, const FilterT& filter = FilterT()) : mFilter(filter) , mPws(nullptr) , mPositionAttribute(positionAttribute) {} PointExecuterDeformer(const PointExecuterDeformer& other) : mFilter(other.mFilter) , mPws(nullptr) , mPositionAttribute(other.mPositionAttribute) {} template <typename LeafT> void reset(const LeafT& leaf, const size_t) { mFilter.reset(leaf); mPws.reset(new points::AttributeHandle<Vec3f>(leaf.constAttributeArray(mPositionAttribute))); } template <typename IterT> void apply(Vec3d& position, const IterT& iter) const { if (mFilter.valid(iter)) { assert(mPws); position = Vec3d(mPws->get(*iter)); } } FilterT mFilter; points::AttributeHandle<Vec3f>::UniquePtr mPws; const std::string& mPositionAttribute; }; template <typename ValueType> inline void addAttributeHandleTyped(PointFunctionArguments& args, openvdb::points::PointDataTree::LeafNodeType& leaf, const std::string& name, const bool write) { const openvdb::points::AttributeSet& attributeSet = leaf.attributeSet(); const size_t pos = attributeSet.find(name); assert(pos != openvdb::points::AttributeSet::INVALID_POS); if (write) args.addWriteHandle<ValueType>(leaf, pos); else args.addHandle<ValueType>(leaf, pos); } #ifndef NDEBUG inline bool supported(const ast::tokens::CoreType type) { switch (type) { case ast::tokens::BOOL : return true; case ast::tokens::CHAR : return true; case ast::tokens::INT16 : return true; case ast::tokens::INT32 : return true; case ast::tokens::INT64 : return true; case ast::tokens::FLOAT : return true; case ast::tokens::DOUBLE : return true; case ast::tokens::VEC2I : return true; case ast::tokens::VEC2F : return true; case ast::tokens::VEC2D : return true; case ast::tokens::VEC3I : return true; case ast::tokens::VEC3F : return true; case ast::tokens::VEC3D : return true; case ast::tokens::VEC4I : return true; case ast::tokens::VEC4F : return true; case ast::tokens::VEC4D : return true; case ast::tokens::MAT3F : return true; case ast::tokens::MAT3D : return true; case ast::tokens::MAT4F : return true; case ast::tokens::MAT4D : return true; case ast::tokens::STRING : return true; case ast::tokens::UNKNOWN : default : return false; } } #endif inline void addAttributeHandle(PointFunctionArguments& args, openvdb::points::PointDataTree::LeafNodeType& leaf, const std::string& name, const ast::tokens::CoreType type, const bool write) { // assert so the executer can be marked as noexcept (assuming nothing throws in compute) assert(supported(type) && "Could not retrieve attribute handle from unsupported type"); switch (type) { case ast::tokens::BOOL : return addAttributeHandleTyped<bool>(args, leaf, name, write); case ast::tokens::CHAR : return addAttributeHandleTyped<char>(args, leaf, name, write); case ast::tokens::INT16 : return addAttributeHandleTyped<int16_t>(args, leaf, name, write); case ast::tokens::INT32 : return addAttributeHandleTyped<int32_t>(args, leaf, name, write); case ast::tokens::INT64 : return addAttributeHandleTyped<int64_t>(args, leaf, name, write); case ast::tokens::FLOAT : return addAttributeHandleTyped<float>(args, leaf, name, write); case ast::tokens::DOUBLE : return addAttributeHandleTyped<double>(args, leaf, name, write); case ast::tokens::VEC2I : return addAttributeHandleTyped<math::Vec2<int32_t>>(args, leaf, name, write); case ast::tokens::VEC2F : return addAttributeHandleTyped<math::Vec2<float>>(args, leaf, name, write); case ast::tokens::VEC2D : return addAttributeHandleTyped<math::Vec2<double>>(args, leaf, name, write); case ast::tokens::VEC3I : return addAttributeHandleTyped<math::Vec3<int32_t>>(args, leaf, name, write); case ast::tokens::VEC3F : return addAttributeHandleTyped<math::Vec3<float>>(args, leaf, name, write); case ast::tokens::VEC3D : return addAttributeHandleTyped<math::Vec3<double>>(args, leaf, name, write); case ast::tokens::VEC4I : return addAttributeHandleTyped<math::Vec4<int32_t>>(args, leaf, name, write); case ast::tokens::VEC4F : return addAttributeHandleTyped<math::Vec4<float>>(args, leaf, name, write); case ast::tokens::VEC4D : return addAttributeHandleTyped<math::Vec4<double>>(args, leaf, name, write); case ast::tokens::MAT3F : return addAttributeHandleTyped<math::Mat3<float>>(args, leaf, name, write); case ast::tokens::MAT3D : return addAttributeHandleTyped<math::Mat3<double>>(args, leaf, name, write); case ast::tokens::MAT4F : return addAttributeHandleTyped<math::Mat4<float>>(args, leaf, name, write); case ast::tokens::MAT4D : return addAttributeHandleTyped<math::Mat4<double>>(args, leaf, name, write); case ast::tokens::STRING : return addAttributeHandleTyped<std::string>(args, leaf, name, write); case ast::tokens::UNKNOWN : default : return; } } /// @brief VDB Points executer for a compiled function pointer struct PointExecuterOp { using LeafManagerT = openvdb::tree::LeafManager<openvdb::points::PointDataTree>; using LeafNode = openvdb::points::PointDataTree::LeafNodeType; using Descriptor = openvdb::points::AttributeSet::Descriptor; using GroupFilter = openvdb::points::GroupFilter; using GroupIndex = Descriptor::GroupIndex; PointExecuterOp(const AttributeRegistry& attributeRegistry, const CustomData* const customData, const KernelFunctionPtr computeFunction, const math::Transform& transform, const GroupIndex& groupIndex, std::vector<PointLeafLocalData::UniquePtr>& leafLocalData, const std::string& positionAttribute, const std::pair<bool,bool>& positionAccess) : mAttributeRegistry(attributeRegistry) , mCustomData(customData) , mComputeFunction(computeFunction) , mTransform(transform) , mGroupIndex(groupIndex) , mLeafLocalData(leafLocalData) , mPositionAttribute(positionAttribute) , mPositionAccess(positionAccess) {} template<typename FilterT = openvdb::points::NullFilter> inline std::unique_ptr<points::AttributeWriteHandle<Vec3f>> initPositions(LeafNode& leaf, const FilterT& filter = FilterT()) const { const points::AttributeHandle<Vec3f>::UniquePtr positions(new points::AttributeHandle<Vec3f>(leaf.constAttributeArray("P"))); std::unique_ptr<points::AttributeWriteHandle<Vec3f>> pws(new points::AttributeWriteHandle<Vec3f>(leaf.attributeArray(mPositionAttribute))); for (auto iter = leaf.beginIndexAll(filter); iter; ++iter) { const Index idx = *iter; const openvdb::Vec3f pos = positions->get(idx) + iter.getCoord().asVec3s(); pws->set(idx, mTransform.indexToWorld(pos)); } return pws; } void operator()(LeafNode& leaf, size_t idx) const { const size_t count = leaf.getLastValue(); const points::AttributeSet& set = leaf.attributeSet(); auto& leafLocalData = mLeafLocalData[idx]; leafLocalData.reset(new PointLeafLocalData(count)); PointFunctionArguments args(mComputeFunction, mCustomData, set, leafLocalData.get()); // add attributes based on the order and existence in the attribute registry for (const auto& iter : mAttributeRegistry.data()) { const std::string& name = (iter.name() == "P" ? mPositionAttribute : iter.name()); addAttributeHandle(args, leaf, name, iter.type(), iter.writes()); } // add groups const auto& map = set.descriptor().groupMap(); if (!map.empty()) { // add all groups based on their offset within the attribute set - the offset can // then be used as a key when retrieving groups from the linearized array, which // is provided by the attribute set argument std::map<size_t, std::string> orderedGroups; for (const auto& iter : map) { orderedGroups[iter.second] = iter.first; } // add a handle at every offset up to and including the max offset. If the // offset is not in use, we just use a null pointer as this will never be // accessed const size_t maxOffset = orderedGroups.crbegin()->first; auto iter = orderedGroups.begin(); for (size_t i = 0; i <= maxOffset; ++i) { if (iter->first == i) { args.addGroupWriteHandle(leaf, iter->second); ++iter; } else { // empty handle at this index args.addNullGroupHandle(); } } } const bool group = mGroupIndex.first != points::AttributeSet::INVALID_POS; // if we are using position we need to initialise the world space storage std::unique_ptr<points::AttributeWriteHandle<Vec3f>> pws; if (mPositionAccess.first || mPositionAccess.second) { if (group) { const GroupFilter filter(mGroupIndex); pws = this->initPositions(leaf, filter); } else { pws = this->initPositions(leaf); } } const auto run = args.bind(); if (group) { const GroupFilter filter(mGroupIndex); auto iter = leaf.beginIndex<LeafNode::ValueAllCIter, GroupFilter>(filter); for (; iter; ++iter) run(*iter); } else { // the Compute function performs unsigned integer arithmetic and will wrap // if count == 0 inside ComputeGenerator::genComputeFunction() if (count > 0) run(count); } // if not writing to position (i.e. post sorting) collapse the temporary attribute if (pws && !mPositionAccess.second) { pws->collapse(); pws.reset(); } // as multiple groups can be stored in a single array, attempt to compact the // arrays directly so that we're not trying to call compact multiple times // unsuccessfully leafLocalData->compact(); } void operator()(const LeafManagerT::LeafRange& range) const { for (auto leaf = range.begin(); leaf; ++leaf) { (*this)(*leaf, leaf.pos()); } } private: const AttributeRegistry& mAttributeRegistry; const CustomData* const mCustomData; const KernelFunctionPtr mComputeFunction; const math::Transform& mTransform; const GroupIndex& mGroupIndex; std::vector<PointLeafLocalData::UniquePtr>& mLeafLocalData; const std::string& mPositionAttribute; const std::pair<bool,bool>& mPositionAccess; }; void appendMissingAttributes(points::PointDataGrid& grid, const AttributeRegistry& registry) { auto typePairFromToken = [](const ast::tokens::CoreType type) -> NamePair { switch (type) { case ast::tokens::BOOL : return points::TypedAttributeArray<bool>::attributeType(); case ast::tokens::CHAR : return points::TypedAttributeArray<char>::attributeType(); case ast::tokens::INT16 : return points::TypedAttributeArray<int16_t>::attributeType(); case ast::tokens::INT32 : return points::TypedAttributeArray<int32_t>::attributeType(); case ast::tokens::INT64 : return points::TypedAttributeArray<int64_t>::attributeType(); case ast::tokens::FLOAT : return points::TypedAttributeArray<float>::attributeType(); case ast::tokens::DOUBLE : return points::TypedAttributeArray<double>::attributeType(); case ast::tokens::VEC2I : return points::TypedAttributeArray<math::Vec2<int32_t>>::attributeType(); case ast::tokens::VEC2F : return points::TypedAttributeArray<math::Vec2<float>>::attributeType(); case ast::tokens::VEC2D : return points::TypedAttributeArray<math::Vec2<double>>::attributeType(); case ast::tokens::VEC3I : return points::TypedAttributeArray<math::Vec3<int32_t>>::attributeType(); case ast::tokens::VEC3F : return points::TypedAttributeArray<math::Vec3<float>>::attributeType(); case ast::tokens::VEC3D : return points::TypedAttributeArray<math::Vec3<double>>::attributeType(); case ast::tokens::VEC4I : return points::TypedAttributeArray<math::Vec4<int32_t>>::attributeType(); case ast::tokens::VEC4F : return points::TypedAttributeArray<math::Vec4<float>>::attributeType(); case ast::tokens::VEC4D : return points::TypedAttributeArray<math::Vec4<double>>::attributeType(); case ast::tokens::MAT3F : return points::TypedAttributeArray<math::Mat3<float>>::attributeType(); case ast::tokens::MAT3D : return points::TypedAttributeArray<math::Mat3<double>>::attributeType(); case ast::tokens::MAT4F : return points::TypedAttributeArray<math::Mat4<float>>::attributeType(); case ast::tokens::MAT4D : return points::TypedAttributeArray<math::Mat4<double>>::attributeType(); case ast::tokens::STRING : return points::StringAttributeArray::attributeType(); case ast::tokens::UNKNOWN : default : { return NamePair(); } } }; const auto leafIter = grid.tree().cbeginLeaf(); assert(leafIter); // append attributes for (const auto& iter : registry.data()) { const std::string& name = iter.name(); const points::AttributeSet::Descriptor& desc = leafIter->attributeSet().descriptor(); const size_t pos = desc.find(name); if (pos != points::AttributeSet::INVALID_POS) { const NamePair& type = desc.type(pos); const ast::tokens::CoreType typetoken = ast::tokens::tokenFromTypeString(type.first); if (typetoken != iter.type() && !(type.second == "str" && iter.type() == ast::tokens::STRING)) { OPENVDB_THROW(AXExecutionError, "Mismatching attributes types. \"" + name + "\" exists of type \"" + type.first + "\" but has been " "accessed with type \"" + ast::tokens::typeStringFromToken(iter.type()) + "\""); } continue; } assert(supported(iter.type())); const NamePair type = typePairFromToken(iter.type()); points::appendAttribute(grid.tree(), name, type); } } void checkAttributesExist(const points::PointDataGrid& grid, const AttributeRegistry& registry) { const auto leafIter = grid.tree().cbeginLeaf(); assert(leafIter); const points::AttributeSet::Descriptor& desc = leafIter->attributeSet().descriptor(); for (const auto& iter : registry.data()) { const std::string& name = iter.name(); const size_t pos = desc.find(name); if (pos == points::AttributeSet::INVALID_POS) { OPENVDB_THROW(AXExecutionError, "Attribute \"" + name + "\" does not exist on grid \"" + grid.getName() + "\""); } } } } // anonymous namespace PointExecutable::PointExecutable(const std::shared_ptr<const llvm::LLVMContext>& context, const std::shared_ptr<const llvm::ExecutionEngine>& engine, const AttributeRegistry::ConstPtr& attributeRegistry, const CustomData::ConstPtr& customData, const std::unordered_map<std::string, uint64_t>& functions) : mContext(context) , mExecutionEngine(engine) , mAttributeRegistry(attributeRegistry) , mCustomData(customData) , mFunctionAddresses(functions) , mSettings(new Settings) { assert(mContext); assert(mExecutionEngine); assert(mAttributeRegistry); } PointExecutable::PointExecutable(const PointExecutable& other) : mContext(other.mContext) , mExecutionEngine(other.mExecutionEngine) , mAttributeRegistry(other.mAttributeRegistry) , mCustomData(other.mCustomData) , mFunctionAddresses(other.mFunctionAddresses) , mSettings(new Settings(*other.mSettings)) {} PointExecutable::~PointExecutable() {} void PointExecutable::execute(openvdb::points::PointDataGrid& grid) const { using LeafManagerT = openvdb::tree::LeafManager<openvdb::points::PointDataTree>; const auto leafIter = grid.tree().cbeginLeaf(); if (!leafIter) return; // create any missing attributes if (mSettings->mCreateMissing) appendMissingAttributes(grid, *mAttributeRegistry); else checkAttributesExist(grid, *mAttributeRegistry); const std::pair<bool,bool> positionAccess = mAttributeRegistry->accessPattern("P", ast::tokens::VEC3F); const bool usingPosition = positionAccess.first || positionAccess.second; // create temporary world space position attribute if P is being accessed // @todo should avoid actually adding this attribute to the tree as its temporary std::string positionAttribute = "P"; if (usingPosition /*mAttributeRegistry->isWritable("P", ast::tokens::VEC3F)*/) { const points::AttributeSet::Descriptor& desc = leafIter->attributeSet().descriptor(); positionAttribute = desc.uniqueName("__P"); points::appendAttribute<openvdb::Vec3f>(grid.tree(), positionAttribute); } const bool usingGroup = !mSettings->mGroup.empty(); openvdb::points::AttributeSet::Descriptor::GroupIndex groupIndex; if (usingGroup) groupIndex = leafIter->attributeSet().groupIndex(mSettings->mGroup); else groupIndex.first = openvdb::points::AttributeSet::INVALID_POS; // extract appropriate function pointer KernelFunctionPtr compute = nullptr; const auto iter = usingGroup ? mFunctionAddresses.find(codegen::PointKernel::getDefaultName()) : mFunctionAddresses.find(codegen::PointRangeKernel::getDefaultName()); if (iter != mFunctionAddresses.end()) { compute = reinterpret_cast<KernelFunctionPtr>(iter->second); } if (!compute) { OPENVDB_THROW(AXCompilerError, "No code has been successfully compiled for execution."); } const math::Transform& transform = grid.transform(); LeafManagerT leafManager(grid.tree()); std::vector<PointLeafLocalData::UniquePtr> leafLocalData(leafManager.leafCount()); const bool threaded = mSettings->mGrainSize > 0; PointExecuterOp executerOp(*mAttributeRegistry, mCustomData.get(), compute, transform, groupIndex, leafLocalData, positionAttribute, positionAccess); leafManager.foreach(executerOp, threaded, mSettings->mGrainSize); // Check to see if any new data has been added and apply it accordingly std::set<std::string> groups; bool newStrings = false; { points::StringMetaInserter inserter(leafIter->attributeSet().descriptorPtr()->getMetadata()); for (const auto& data : leafLocalData) { data->getGroups(groups); newStrings |= data->insertNewStrings(inserter); } } // append and copy over newly created groups // @todo We should just be able to steal the arrays and compact // groups but the API for this isn't very nice at the moment for (const auto& name : groups) { points::appendGroup(grid.tree(), name); } // add new groups and set strings leafManager.foreach( [&groups, &leafLocalData, newStrings] (auto& leaf, size_t idx) { PointLeafLocalData::UniquePtr& data = leafLocalData[idx]; for (const auto& name : groups) { // Attempt to get the group handle out of the leaf local data form this // leaf. This may not exist as although all of the unique set are appended // to the tree (above), not every leaf may have been directly touched // by every new group. Some leaf nodes may not require any bit mask copying points::GroupWriteHandle* tmpHandle = data->get(name); if (!tmpHandle) continue; points::GroupWriteHandle handle = leaf.groupWriteHandle(name); if (tmpHandle->isUniform()) { handle.collapse(tmpHandle->get(0)); } else { const openvdb::Index size = tmpHandle->size(); for (openvdb::Index i = 0; i < size; ++i) { handle.set(i, tmpHandle->get(i)); } } } if (newStrings) { const MetaMap& metadata = leaf.attributeSet().descriptor().getMetadata(); const PointLeafLocalData::StringArrayMap& stringArrayMap = data->getStringArrayMap(); for (const auto& arrayIter : stringArrayMap) { points::StringAttributeWriteHandle::Ptr handle = points::StringAttributeWriteHandle::create(*(arrayIter.first), metadata); for (const auto& iter : arrayIter.second) { handle->set(static_cast<Index>(iter.first), iter.second); } } } }, threaded, mSettings->mGrainSize); if (positionAccess.second) { // if position is writable, sort the points if (usingGroup) { openvdb::points::GroupFilter filter(groupIndex); PointExecuterDeformer<openvdb::points::GroupFilter> deformer(positionAttribute, filter); openvdb::points::movePoints(grid, deformer); } else { PointExecuterDeformer<> deformer(positionAttribute); openvdb::points::movePoints(grid, deformer); } } if (usingPosition) { // remove temporary world space storage points::dropAttribute(grid.tree(), positionAttribute); } } ///////////////////////////////////////////// ///////////////////////////////////////////// void PointExecutable::setCreateMissing(const bool flag) { mSettings->mCreateMissing = flag; } bool PointExecutable::getCreateMissing() const { return mSettings->mCreateMissing; } void PointExecutable::setGrainSize(const size_t grain) { mSettings->mGrainSize = grain; } size_t PointExecutable::getGrainSize() const { return mSettings->mGrainSize; } void PointExecutable::setGroupExecution(const std::string& group) { mSettings->mGroup = group; } const std::string& PointExecutable::getGroupExecution() const { return mSettings->mGroup; } } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
30,050
C++
40.278846
113
0.633178
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/VolumeExecutable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/VolumeExecutable.cc #include "VolumeExecutable.h" #include "../Exceptions.h" // @TODO refactor so we don't have to include VolumeComputeGenerator.h, // but still have the functions defined in one place #include "../codegen/VolumeComputeGenerator.h" #include <openvdb/Exceptions.h> #include <openvdb/Types.h> #include <openvdb/math/Coord.h> #include <openvdb/math/Transform.h> #include <openvdb/math/Vec3.h> #include <openvdb/tree/ValueAccessor.h> #include <openvdb/tree/LeafManager.h> #include <openvdb/tree/NodeManager.h> #include <tbb/parallel_for.h> #include <memory> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { struct VolumeExecutable::Settings { Index mTreeExecutionLevel = 0; bool mCreateMissing = true; IterType mValueIterator = IterType::ON; size_t mGrainSize = 1; }; namespace { /// @brief Volume Kernel types /// using KernelFunctionPtr = std::add_pointer<codegen::VolumeKernel::Signature>::type; using FunctionTraitsT = codegen::VolumeKernel::FunctionTraitsT; using ReturnT = FunctionTraitsT::ReturnType; template <typename ValueT> using ConverterT = typename openvdb::BoolGrid::ValueConverter<ValueT>::Type; using SupportedTypeList = openvdb::TypeList< ConverterT<double>, ConverterT<float>, ConverterT<int64_t>, ConverterT<int32_t>, ConverterT<int16_t>, ConverterT<bool>, ConverterT<openvdb::math::Vec2<double>>, ConverterT<openvdb::math::Vec2<float>>, ConverterT<openvdb::math::Vec2<int32_t>>, ConverterT<openvdb::math::Vec3<double>>, ConverterT<openvdb::math::Vec3<float>>, ConverterT<openvdb::math::Vec3<int32_t>>, ConverterT<openvdb::math::Vec4<double>>, ConverterT<openvdb::math::Vec4<float>>, ConverterT<openvdb::math::Vec4<int32_t>>, ConverterT<openvdb::math::Mat3<double>>, ConverterT<openvdb::math::Mat3<float>>, ConverterT<openvdb::math::Mat4<double>>, ConverterT<openvdb::math::Mat4<float>>, ConverterT<std::string>>; /// The arguments of the generated function struct VolumeFunctionArguments { struct Accessors { using UniquePtr = std::unique_ptr<Accessors>; virtual ~Accessors() = default; }; template <typename TreeT> struct TypedAccessor final : public Accessors { using UniquePtr = std::unique_ptr<TypedAccessor<TreeT>>; TypedAccessor(TreeT& tree) : mAccessor(new tree::ValueAccessor<TreeT>(tree)) {} ~TypedAccessor() override final = default; inline void* get() const { return static_cast<void*>(mAccessor.get()); } const std::unique_ptr<tree::ValueAccessor<TreeT>> mAccessor; }; /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// VolumeFunctionArguments(const KernelFunctionPtr function, const size_t index, void* const accessor, const CustomData* const customData) : mFunction(function) , mIdx(index) , mAccessor(accessor) , mCustomData(customData) , mVoidAccessors() , mAccessors() , mVoidTransforms() {} /// @brief Given a built version of the function signature, automatically /// bind the current arguments and return a callable function /// which takes no arguments inline auto bind() { return [&](const openvdb::Coord& ijk, const openvdb::Vec3f& pos) -> ReturnT { return mFunction(static_cast<FunctionTraitsT::Arg<0>::Type>(mCustomData), reinterpret_cast<FunctionTraitsT::Arg<1>::Type>(ijk.data()), reinterpret_cast<FunctionTraitsT::Arg<2>::Type>(pos.asV()), static_cast<FunctionTraitsT::Arg<3>::Type>(mVoidAccessors.data()), static_cast<FunctionTraitsT::Arg<4>::Type>(mVoidTransforms.data()), static_cast<FunctionTraitsT::Arg<5>::Type>(mIdx), mAccessor); }; } template <typename TreeT> inline void addAccessor(TreeT& tree) { typename TypedAccessor<TreeT>::UniquePtr accessor(new TypedAccessor<TreeT>(tree)); mVoidAccessors.emplace_back(accessor->get()); mAccessors.emplace_back(std::move(accessor)); } inline void addTransform(math::Transform& transform) { mVoidTransforms.emplace_back(static_cast<void*>(&transform)); } private: const KernelFunctionPtr mFunction; const size_t mIdx; void* const mAccessor; const CustomData* const mCustomData; std::vector<void*> mVoidAccessors; std::vector<Accessors::UniquePtr> mAccessors; std::vector<void*> mVoidTransforms; }; inline bool supported(const ast::tokens::CoreType type) { switch (type) { case ast::tokens::BOOL : return true; case ast::tokens::INT16 : return true; case ast::tokens::INT32 : return true; case ast::tokens::INT64 : return true; case ast::tokens::FLOAT : return true; case ast::tokens::DOUBLE : return true; case ast::tokens::VEC2I : return true; case ast::tokens::VEC2F : return true; case ast::tokens::VEC2D : return true; case ast::tokens::VEC3I : return true; case ast::tokens::VEC3F : return true; case ast::tokens::VEC3D : return true; case ast::tokens::VEC4I : return true; case ast::tokens::VEC4F : return true; case ast::tokens::VEC4D : return true; case ast::tokens::MAT3F : return true; case ast::tokens::MAT3D : return true; case ast::tokens::MAT4F : return true; case ast::tokens::MAT4D : return true; case ast::tokens::STRING : return true; case ast::tokens::UNKNOWN : default : return false; } } inline void retrieveAccessor(VolumeFunctionArguments& args, openvdb::GridBase* grid, const ast::tokens::CoreType& type) { // assert so the executer can be marked as noexcept (assuming nothing throws in compute) assert(supported(type) && "Could not retrieve accessor from unsupported type"); switch (type) { case ast::tokens::BOOL : { args.addAccessor(static_cast<ConverterT<bool>*>(grid)->tree()); return; } case ast::tokens::INT16 : { args.addAccessor(static_cast<ConverterT<int16_t>*>(grid)->tree()); return; } case ast::tokens::INT32 : { args.addAccessor(static_cast<ConverterT<int32_t>*>(grid)->tree()); return; } case ast::tokens::INT64 : { args.addAccessor(static_cast<ConverterT<int64_t>*>(grid)->tree()); return; } case ast::tokens::FLOAT : { args.addAccessor(static_cast<ConverterT<float>*>(grid)->tree()); return; } case ast::tokens::DOUBLE : { args.addAccessor(static_cast<ConverterT<double>*>(grid)->tree()); return; } case ast::tokens::VEC2D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec2<double>>*>(grid)->tree()); return; } case ast::tokens::VEC2F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec2<float>>*>(grid)->tree()); return; } case ast::tokens::VEC2I : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec2<int32_t>>*>(grid)->tree()); return; } case ast::tokens::VEC3D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec3<double>>*>(grid)->tree()); return; } case ast::tokens::VEC3F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec3<float>>*>(grid)->tree()); return; } case ast::tokens::VEC3I : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec3<int32_t>>*>(grid)->tree()); return; } case ast::tokens::VEC4D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec4<double>>*>(grid)->tree()); return; } case ast::tokens::VEC4F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec4<float>>*>(grid)->tree()); return; } case ast::tokens::VEC4I : { args.addAccessor(static_cast<ConverterT<openvdb::math::Vec4<int32_t>>*>(grid)->tree()); return; } case ast::tokens::MAT3D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat3<double>>*>(grid)->tree()); return; } case ast::tokens::MAT3F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat3<float>>*>(grid)->tree()); return; } case ast::tokens::MAT4D : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat4<double>>*>(grid)->tree()); return; } case ast::tokens::MAT4F : { args.addAccessor(static_cast<ConverterT<openvdb::math::Mat4<float>>*>(grid)->tree()); return; } case ast::tokens::STRING : { args.addAccessor(static_cast<ConverterT<std::string>*>(grid)->tree()); return; } case ast::tokens::UNKNOWN : default : return; } } inline openvdb::GridBase::Ptr createGrid(const ast::tokens::CoreType& type) { // assert so the executer can be marked as noexcept (assuming nothing throws in compute) assert(supported(type) && "Could not retrieve accessor from unsupported type"); switch (type) { case ast::tokens::BOOL : return ConverterT<bool>::create(); case ast::tokens::INT16 : return ConverterT<int16_t>::create(); case ast::tokens::INT32 : return ConverterT<int32_t>::create(); case ast::tokens::INT64 : return ConverterT<int64_t>::create(); case ast::tokens::FLOAT : return ConverterT<float>::create(); case ast::tokens::DOUBLE : return ConverterT<double>::create(); case ast::tokens::VEC2D : return ConverterT<openvdb::math::Vec2<double>>::create(); case ast::tokens::VEC2F : return ConverterT<openvdb::math::Vec2<float>>::create(); case ast::tokens::VEC2I : return ConverterT<openvdb::math::Vec2<int32_t>>::create(); case ast::tokens::VEC3D : return ConverterT<openvdb::math::Vec3<double>>::create(); case ast::tokens::VEC3F : return ConverterT<openvdb::math::Vec3<float>>::create(); case ast::tokens::VEC3I : return ConverterT<openvdb::math::Vec3<int32_t>>::create(); case ast::tokens::VEC4D : return ConverterT<openvdb::math::Vec4<double>>::create(); case ast::tokens::VEC4F : return ConverterT<openvdb::math::Vec4<float>>::create(); case ast::tokens::VEC4I : return ConverterT<openvdb::math::Vec4<int32_t>>::create(); case ast::tokens::MAT3D : return ConverterT<openvdb::math::Mat3<double>>::create(); case ast::tokens::MAT3F : return ConverterT<openvdb::math::Mat3<float>>::create(); case ast::tokens::MAT4D : return ConverterT<openvdb::math::Mat4<double>>::create(); case ast::tokens::MAT4F : return ConverterT<openvdb::math::Mat4<float>>::create(); case ast::tokens::STRING : return ConverterT<std::string>::create(); case ast::tokens::UNKNOWN : default : return nullptr; } } template <typename TreeT, typename LeafIterTraitsT> struct VolumeExecuterOp { using LeafManagerT = tree::LeafManager<TreeT>; using LeafRangeT = typename LeafManagerT::LeafRange; VolumeExecuterOp(const AttributeRegistry& attributeRegistry, const CustomData* const customData, const math::Transform& assignedVolumeTransform, const KernelFunctionPtr computeFunction, openvdb::GridBase** grids, TreeT& tree, const size_t idx, const Index level) : mAttributeRegistry(attributeRegistry) , mCustomData(customData) , mComputeFunction(computeFunction) , mTransform(assignedVolumeTransform) , mGrids(grids) , mIdx(idx) , mTree(tree) , mLevel(level) { assert(mGrids); } // For use with a NodeManager // @note The enable_if shouldn't be necessary but the partitioner // through TBB refuses to call the LeafRange operator with a // const reference argument. template <typename NodeType, typename = typename std::enable_if<!std::is_same<NodeType, LeafRangeT>::value>::type> void operator()(NodeType& node) const { // if the current node level does not match, skip // @todo only run over the given level, avoid caching other nodes assert(node.getLevel() > 0); if (node.getLevel() != mLevel) return; openvdb::tree::ValueAccessor<TreeT> acc(mTree); VolumeFunctionArguments args(mComputeFunction, mIdx, static_cast<void*>(&acc), mCustomData); openvdb::GridBase** read = mGrids; for (const auto& iter : mAttributeRegistry.data()) { assert(read); retrieveAccessor(args, *read, iter.type()); args.addTransform((*read)->transform()); ++read; } const auto run = args.bind(); (*this)(node, run); } // For use with a LeafManager, when the target execution level is 0 void operator()(const typename LeafManagerT::LeafRange& range) const { openvdb::tree::ValueAccessor<TreeT> acc(mTree); VolumeFunctionArguments args(mComputeFunction, mIdx, static_cast<void*>(&acc), mCustomData); openvdb::GridBase** read = mGrids; for (const auto& iter : mAttributeRegistry.data()) { assert(read); retrieveAccessor(args, *read, iter.type()); args.addTransform((*read)->transform()); ++read; } const auto run = args.bind(); for (auto leaf = range.begin(); leaf; ++leaf) { (*this)(*leaf, run); } } template <typename NodeType, typename FuncT> void operator()(NodeType& node, const FuncT& axfunc) const { using IterT = typename LeafIterTraitsT::template NodeConverter<NodeType>::Type; using IterTraitsT = tree::IterTraits<NodeType, IterT>; for (auto iter = IterTraitsT::begin(node); iter; ++iter) { const openvdb::Coord& coord = iter.getCoord(); const openvdb::Vec3f& pos = mTransform.indexToWorld(coord); axfunc(coord, pos); } } private: const AttributeRegistry& mAttributeRegistry; const CustomData* const mCustomData; const KernelFunctionPtr mComputeFunction; const math::Transform& mTransform; openvdb::GridBase** const mGrids; const size_t mIdx; TreeT& mTree; const Index mLevel; // only used with NodeManagers }; void registerVolumes(GridPtrVec& grids, GridPtrVec& writeableGrids, GridPtrVec& readGrids, const AttributeRegistry& registry, const bool createMissing) { for (auto& iter : registry.data()) { openvdb::GridBase::Ptr matchedGrid; bool matchedName(false); ast::tokens::CoreType type = ast::tokens::UNKNOWN; for (const auto& grid : grids) { if (grid->getName() != iter.name()) continue; matchedName = true; type = ast::tokens::tokenFromTypeString(grid->valueType()); if (type != iter.type()) continue; matchedGrid = grid; break; } if (createMissing && !matchedGrid) { matchedGrid = createGrid(iter.type()); if (matchedGrid) { matchedGrid->setName(iter.name()); grids.emplace_back(matchedGrid); matchedName = true; type = iter.type(); } } if (!matchedName && !matchedGrid) { OPENVDB_THROW(AXExecutionError, "Missing grid \"" + ast::tokens::typeStringFromToken(iter.type()) + "@" + iter.name() + "\"."); } if (matchedName && !matchedGrid) { OPENVDB_THROW(AXExecutionError, "Mismatching grid access type. \"@" + iter.name() + "\" exists but has been accessed with type \"" + ast::tokens::typeStringFromToken(iter.type()) + "\"."); } assert(matchedGrid); if (!supported(type)) { OPENVDB_THROW(AXExecutionError, "Could not register volume '" + matchedGrid->getName() + "' as it has an unknown or unsupported value type '" + matchedGrid->valueType() + "'"); } // Populate the write/read grids based on the access registry. If a // grid is being written to and has non self usage, (influences // another grids value which isn't it's own) it must be deep copied // @todo implement better execution order detection which could minimize // the number of deep copies required if (iter.writes() && iter.affectsothers()) { // if affectsothers(), it's also read from at some point assert(iter.reads()); readGrids.push_back(matchedGrid->deepCopyGrid()); writeableGrids.push_back(matchedGrid); } else { if (iter.writes()) { writeableGrids.push_back(matchedGrid); } readGrids.push_back(matchedGrid); } } } template<typename LeafT> struct ValueOnIter { using IterTraitsT = typename tree::IterTraits<LeafT, typename LeafT::ValueOnIter>; }; template<typename LeafT> struct ValueAllIter { using IterTraitsT = typename tree::IterTraits<LeafT, typename LeafT::ValueAllIter>; }; template<typename LeafT> struct ValueOffIter { using IterTraitsT = typename tree::IterTraits<LeafT, typename LeafT::ValueOffIter>; }; template <template <typename> class IterT, typename GridT> inline void run(openvdb::GridBase& grid, openvdb::GridBase** readptrs, const KernelFunctionPtr kernel, const AttributeRegistry& registry, const CustomData* const custom, const VolumeExecutable::Settings& S) { using TreeType = typename GridT::TreeType; using IterType = IterT<typename TreeType::LeafNodeType>; const ast::tokens::CoreType type = ast::tokens::tokenFromTypeString(grid.valueType()); const int64_t idx = registry.accessIndex(grid.getName(), type); assert(idx >= 0); GridT& typed = static_cast<GridT&>(grid); VolumeExecuterOp<TreeType, typename IterType::IterTraitsT> executerOp(registry, custom, grid.transform(), kernel, readptrs, typed.tree(), idx, S.mTreeExecutionLevel); const bool thread = S.mGrainSize > 0; if (S.mTreeExecutionLevel == 0) { // execute over the topology of the grid currently being modified. tree::LeafManager<TreeType> leafManager(typed.tree()); if (thread) tbb::parallel_for(leafManager.leafRange(S.mGrainSize), executerOp); else executerOp(leafManager.leafRange()); } else { // no leaf nodes tree::NodeManager<TreeType, TreeType::RootNodeType::LEVEL-1> manager(typed.tree()); manager.foreachBottomUp(executerOp, thread, S.mGrainSize); } } template <template <typename> class IterT> inline void run(const openvdb::GridPtrVec& writeableGrids, const openvdb::GridPtrVec& readGrids, const KernelFunctionPtr kernel, const AttributeRegistry& registry, const CustomData* const custom, const VolumeExecutable::Settings& S) { // extract grid pointers from shared pointer container assert(readGrids.size() == registry.data().size()); std::vector<openvdb::GridBase*> readptrs; readptrs.reserve(readGrids.size()); for (auto& grid : readGrids) readptrs.emplace_back(grid.get()); for (const auto& grid : writeableGrids) { const bool success = grid->apply<SupportedTypeList>([&](auto& typed) { using GridType = typename std::decay<decltype(typed)>::type; run<IterT, GridType>(*grid, readptrs.data(), kernel, registry, custom, S); }); if (!success) { OPENVDB_THROW(AXExecutionError, "Could not retrieve volume '" + grid->getName() + "' as it has an unknown or unsupported value type '" + grid->valueType() + "'"); } } } } // anonymous namespace VolumeExecutable::VolumeExecutable(const std::shared_ptr<const llvm::LLVMContext>& context, const std::shared_ptr<const llvm::ExecutionEngine>& engine, const AttributeRegistry::ConstPtr& accessRegistry, const CustomData::ConstPtr& customData, const std::unordered_map<std::string, uint64_t>& functionAddresses) : mContext(context) , mExecutionEngine(engine) , mAttributeRegistry(accessRegistry) , mCustomData(customData) , mFunctionAddresses(functionAddresses) , mSettings(new Settings) { assert(mContext); assert(mExecutionEngine); assert(mAttributeRegistry); } VolumeExecutable::VolumeExecutable(const VolumeExecutable& other) : mContext(other.mContext) , mExecutionEngine(other.mExecutionEngine) , mAttributeRegistry(other.mAttributeRegistry) , mCustomData(other.mCustomData) , mFunctionAddresses(other.mFunctionAddresses) , mSettings(new Settings(*other.mSettings)) {} VolumeExecutable::~VolumeExecutable() {} void VolumeExecutable::execute(openvdb::GridPtrVec& grids) const { openvdb::GridPtrVec readGrids, writeableGrids; registerVolumes(grids, writeableGrids, readGrids, *mAttributeRegistry, mSettings->mCreateMissing); const auto iter = mFunctionAddresses.find(codegen::VolumeKernel::getDefaultName()); KernelFunctionPtr kernel = nullptr; if (iter != mFunctionAddresses.end()) { kernel = reinterpret_cast<KernelFunctionPtr>(iter->second); } if (kernel == nullptr) { OPENVDB_THROW(AXCompilerError, "No AX kernel found for execution."); } if (mSettings->mValueIterator == IterType::ON) run<ValueOnIter>(writeableGrids, readGrids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings); else if (mSettings->mValueIterator == IterType::OFF) run<ValueOffIter>(writeableGrids, readGrids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings); else if (mSettings->mValueIterator == IterType::ALL) run<ValueAllIter>(writeableGrids, readGrids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings); else { OPENVDB_THROW(AXExecutionError, "Unrecognised voxel iterator."); } } void VolumeExecutable::execute(openvdb::GridBase& grid) const { const auto data = mAttributeRegistry->data(); if (data.empty()) return; for (auto& iter : mAttributeRegistry->data()) { if (grid.getName() != iter.name()) { OPENVDB_THROW(LookupError, "Missing grid \"" + ast::tokens::typeStringFromToken(iter.type()) + "@" + iter.name() + "\"."); } const ast::tokens::CoreType type = ast::tokens::tokenFromTypeString(grid.valueType()); if (type != iter.type()) { OPENVDB_THROW(TypeError, "Mismatching grid access type. \"@" + iter.name() + "\" exists but has been accessed with type \"" + ast::tokens::typeStringFromToken(iter.type()) + "\"."); } if (!supported(type)) { OPENVDB_THROW(TypeError, "Could not register volume '" + grid.getName() + "' as it has an unknown or unsupported value type '" + grid.valueType() + "'"); } } assert(mAttributeRegistry->data().size() == 1); const auto iter = mFunctionAddresses.find(codegen::VolumeKernel::getDefaultName()); KernelFunctionPtr kernel = nullptr; if (iter != mFunctionAddresses.end()) { kernel = reinterpret_cast<KernelFunctionPtr>(iter->second); } if (kernel == nullptr) { OPENVDB_THROW(AXCompilerError, "No code has been successfully compiled for execution."); } const bool success = grid.apply<SupportedTypeList>([&](auto& typed) { using GridType = typename std::decay<decltype(typed)>::type; openvdb::GridBase* grids = &grid; if (mSettings->mValueIterator == IterType::ON) run<ValueOnIter, GridType>(grid, &grids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings); else if (mSettings->mValueIterator == IterType::OFF) run<ValueOffIter, GridType>(grid, &grids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings); else if (mSettings->mValueIterator == IterType::ALL) run<ValueAllIter, GridType>(grid, &grids, kernel, *mAttributeRegistry, mCustomData.get(), *mSettings); else OPENVDB_THROW(AXExecutionError,"Unrecognised voxel iterator."); }); if (!success) { OPENVDB_THROW(TypeError, "Could not retrieve volume '" + grid.getName() + "' as it has an unknown or unsupported value type '" + grid.valueType() + "'"); } } ///////////////////////////////////////////// ///////////////////////////////////////////// void VolumeExecutable::setCreateMissing(const bool flag) { mSettings->mCreateMissing = flag; } bool VolumeExecutable::getCreateMissing() const { return mSettings->mCreateMissing; } void VolumeExecutable::setTreeExecutionLevel(const Index level) { // use the default implementation of FloatTree for reference if (level >= FloatTree::DEPTH) { OPENVDB_THROW(RuntimeError, "Invalid tree execution level in VolumeExecutable."); } mSettings->mTreeExecutionLevel = level; } Index VolumeExecutable::getTreeExecutionLevel() const { return mSettings->mTreeExecutionLevel; } void VolumeExecutable::setValueIterator(const VolumeExecutable::IterType& iter) { mSettings->mValueIterator = iter; } VolumeExecutable::IterType VolumeExecutable::getValueIterator() const { return mSettings->mValueIterator; } void VolumeExecutable::setGrainSize(const size_t grain) { mSettings->mGrainSize = grain; } size_t VolumeExecutable::getGrainSize() const { return mSettings->mGrainSize; } } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
26,225
C++
39.914197
135
0.63428
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/CustomData.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/CustomData.h /// /// @authors Nick Avramoussis, Francisco Gochez /// /// @brief Access to the CustomData class which can provide custom user /// user data to the OpenVDB AX Compiler. /// #ifndef OPENVDB_AX_COMPILER_CUSTOM_DATA_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_CUSTOM_DATA_HAS_BEEN_INCLUDED #include <openvdb/version.h> #include <openvdb/Metadata.h> #include <openvdb/Types.h> #include <unordered_map> #include <memory> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { /// @brief The backend representation of strings in AX. This is also how /// strings are passed from the AX code generation to functions. struct AXString { // usually size_t. Used to match the implementation of std:string using SizeType = std::allocator<char>::size_type; const char* ptr = nullptr; SizeType size = 0; }; /// @brief The custom data class is a simple container for named openvdb metadata. Its primary use /// case is passing arbitrary "external" data to an AX executable object when calling /// Compiler::compile. For example, it is the mechanism by which we pass data held inside of a /// parent DCC to executable AX code. class CustomData { public: using Ptr = std::shared_ptr<CustomData>; using ConstPtr = std::shared_ptr<const CustomData>; using UniquePtr = std::unique_ptr<CustomData>; CustomData() : mData() {} static UniquePtr create() { UniquePtr data(new CustomData); return data; } /// @brief Reset the custom data. This will clear and delete all previously added data. /// @note When used the Compiler::compile method, this should not be used prior to executing /// the built executable object inline void reset() { mData.clear(); } /// @brief Checks whether or not data of given name has been inserted inline bool hasData(const Name& name) { const auto iter = mData.find(name); return (iter != mData.end()); } /// @brief Checks whether or not data of given name and type has been inserted template <typename TypedDataCacheT> inline bool hasData(const Name& name) { const auto iter = mData.find(name); if (iter == mData.end()) return false; const TypedDataCacheT* const typed = dynamic_cast<const TypedDataCacheT* const>(iter->second.get()); return typed != nullptr; } /// @brief Retrieves a const pointer to data of given name. If it does not /// exist, returns nullptr inline const Metadata::ConstPtr getData(const Name& name) const { const auto iter = mData.find(name); if (iter == mData.end()) return Metadata::ConstPtr(); return iter->second; } /// @brief Retrieves a const pointer to data of given name and type. If it does not /// exist, returns nullptr /// @param name Name of the data entry /// @returns Object of given type and name. If the type does not match, nullptr is returned. template <typename TypedDataCacheT> inline const TypedDataCacheT* getData(const Name& name) const { Metadata::ConstPtr data = getData(name); if (!data) return nullptr; const TypedDataCacheT* const typed = dynamic_cast<const TypedDataCacheT* const>(data.get()); return typed; } /// @brief Retrieves or inserts typed metadata. If thedata exists, it is dynamic-casted to the /// expected type, which may result in a nullptr. If the data does not exist it is guaranteed /// to be inserted and returned. The value of the inserted data can then be modified template <typename TypedDataCacheT> inline TypedDataCacheT* getOrInsertData(const Name& name) { const auto iter = mData.find(name); if (iter == mData.end()) { Metadata::Ptr data(new TypedDataCacheT()); mData[name] = data; return static_cast<TypedDataCacheT* const>(data.get()); } else { return dynamic_cast<TypedDataCacheT* const>(iter->second.get()); } } /// @brief Inserts data of specified type with given name. /// @param name Name of the data /// @param data Shared pointer to the data /// @note If an entry of the given name already exists, will copy the data into the existing /// entry rather than overwriting the pointer template <typename TypedDataCacheT> inline void insertData(const Name& name, const typename TypedDataCacheT::Ptr data) { if (hasData(name)) { TypedDataCacheT* const dataToSet = getOrInsertData<TypedDataCacheT>(name); if (!dataToSet) { OPENVDB_THROW(TypeError, "Custom data \"" + name + "\" already exists with a different type."); } dataToSet->value() = data->value(); } else { mData[name] = data->copy(); } } /// @brief Inserts data with given name. /// @param name Name of the data /// @param data The metadata /// @note If an entry of the given name already exists, will copy the data into the existing /// entry rather than overwriting the pointer inline void insertData(const Name& name, const Metadata::Ptr data) { const auto iter = mData.find(name); if (iter == mData.end()) { mData[name] = data; } else { iter->second->copy(*data); } } private: std::unordered_map<Name, Metadata::Ptr> mData; }; struct AXStringMetadata : public StringMetadata { using Ptr = openvdb::SharedPtr<AXStringMetadata>; using ConstPtr = openvdb::SharedPtr<const AXStringMetadata>; AXStringMetadata(const std::string& string) : StringMetadata(string) , mData() { this->initialize(); } // delegate, ensure valid string initialization AXStringMetadata() : AXStringMetadata("") {} AXStringMetadata(const AXStringMetadata& other) : StringMetadata(other) , mData() { this->initialize(); } ~AXStringMetadata() override {} openvdb::Metadata::Ptr copy() const override { openvdb::Metadata::Ptr metadata(new AXStringMetadata()); metadata->copy(*this); return metadata; } void copy(const openvdb::Metadata& other) override { const AXStringMetadata* t = dynamic_cast<const AXStringMetadata*>(&other); if (t == nullptr) OPENVDB_THROW(openvdb::TypeError, "Incompatible type during copy"); this->StringMetadata::setValue(t->StringMetadata::value()); this->initialize(); } void setValue(const std::string& string) { this->StringMetadata::setValue(string); this->initialize(); } ax::AXString& value() { return mData; } const ax::AXString& value() const { return mData; } protected: void readValue(std::istream& is, openvdb::Index32 size) override { StringMetadata::readValue(is, size); this->initialize(); } private: void initialize() { mData.ptr = StringMetadata::value().c_str(); mData.size = StringMetadata::value().size(); } ax::AXString mData; }; } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_CUSTOM_DATA_HAS_BEEN_INCLUDED
7,640
C
30.315574
111
0.631152
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/VolumeExecutable.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/VolumeExecutable.h /// /// @authors Nick Avramoussis, Francisco Gochez, Richard Jones /// /// @brief The VolumeExecutable, produced by the OpenVDB AX Compiler for /// execution over Numerical OpenVDB Grids. /// #ifndef OPENVDB_AX_COMPILER_VOLUME_EXECUTABLE_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_VOLUME_EXECUTABLE_HAS_BEEN_INCLUDED #include "CustomData.h" #include "AttributeRegistry.h" #include <openvdb/version.h> #include <openvdb/Grid.h> #include <unordered_map> class TestVolumeExecutable; namespace llvm { class ExecutionEngine; class LLVMContext; } namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { class Compiler; /// @brief Object that encapsulates compiled AX code which can be executed on a collection of /// VDB volume grids class VolumeExecutable { public: using Ptr = std::shared_ptr<VolumeExecutable>; ~VolumeExecutable(); /// @brief Copy constructor. Shares the LLVM constructs but deep copies the /// settings. Multiple copies of an executor can be used at the same time /// safely. VolumeExecutable(const VolumeExecutable& other); //////////////////////////////////////////////////////// /// @brief Execute AX code on target grids void execute(openvdb::GridPtrVec& grids) const; void execute(openvdb::GridBase& grid) const; //////////////////////////////////////////////////////// /// @brief Set the behaviour when missing grids are accessed. Default /// behaviour is true, which creates them with default transforms and /// background values /// @param flag Enables or disables the creation of missing attributes void setCreateMissing(const bool flag); /// @return Whether this executable will generate new grids. bool getCreateMissing() const; /// @brief Set the execution level for this executable. This controls what /// nodes are processed when execute is called. Possible values depend on /// the OpenVDB configuration in use however a value of 0 is the default /// and will always correspond to the lowest level (leaf-level). /// @note A value larger that the number of levels in the tree (i.e. larger /// than the tree depth) will cause this method to throw a runtime error. /// @warning Executing over tiles with compiled code designed for voxel /// level access may produce incorrect results. This is typically the /// case when accessing VDBs with mismatching topology. Consider /// voxelizing tiles where necessary. /// @param level The tree execution level to set void setTreeExecutionLevel(const Index level); /// @return The tree execution level. Default is 0 i.e. the leaf level Index getTreeExecutionLevel() const; enum class IterType { ON, OFF, ALL }; /// @brief Set the value iterator type to use with this executable. Options /// are ON, OFF, ALL. Default is ON. /// @param iter The value iterator type to set void setValueIterator(const IterType& iter); /// @return The current value iterator type IterType getValueIterator() const; /// @brief Set the threading grain size. Default is 1. A value of 0 has the /// effect of disabling multi-threading. /// @param grain The grain size void setGrainSize(const size_t grain); /// @return The current grain size size_t getGrainSize() const; //////////////////////////////////////////////////////// // foward declaration of settings for this executable struct Settings; private: friend class Compiler; friend class ::TestVolumeExecutable; /// @brief Constructor, expected to be invoked by the compiler. Should not /// be invoked directly. /// @param context Shared pointer to an llvm:LLVMContext associated with the /// execution engine /// @param engine Shared pointer to an llvm::ExecutionEngine used to build /// functions. Context should be the associated LLVMContext /// @param accessRegistry Registry of volumes accessed by AX code /// @param customData Custom data which will be shared by this executable. /// It can be used to retrieve external data from within the AX code /// @param functions A map of function names to physical memory addresses /// which were built by llvm using engine VolumeExecutable(const std::shared_ptr<const llvm::LLVMContext>& context, const std::shared_ptr<const llvm::ExecutionEngine>& engine, const AttributeRegistry::ConstPtr& accessRegistry, const CustomData::ConstPtr& customData, const std::unordered_map<std::string, uint64_t>& functions); private: // The Context and ExecutionEngine must exist _only_ for object lifetime // management. The ExecutionEngine must be destroyed before the Context const std::shared_ptr<const llvm::LLVMContext> mContext; const std::shared_ptr<const llvm::ExecutionEngine> mExecutionEngine; const AttributeRegistry::ConstPtr mAttributeRegistry; const CustomData::ConstPtr mCustomData; const std::unordered_map<std::string, uint64_t> mFunctionAddresses; std::unique_ptr<Settings> mSettings; }; } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_VOLUME_EXECUTABLE_HAS_BEEN_INCLUDED
5,446
C
38.18705
93
0.695006
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Compiler.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/Compiler.h /// /// @authors Nick Avramoussis, Francisco Gochez, Richard Jones /// /// @brief The OpenVDB AX Compiler class provides methods to generate /// AX executables from a provided AX AST (or directly from a given /// string). The class object exists to cache various structures, /// primarily LLVM constructs, which benefit from existing across /// additional compilation runs. /// #ifndef OPENVDB_AX_COMPILER_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_HAS_BEEN_INCLUDED #include "CompilerOptions.h" #include "CustomData.h" #include "Logger.h" #include "../ax.h" // backward compat support for initialize() #include "../ast/Parse.h" #include <openvdb/version.h> #include <memory> #include <sstream> // forward namespace llvm { class LLVMContext; } namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { // forward class FunctionRegistry; } /// @brief The compiler class. This holds an llvm context and set of compiler /// options, and constructs executable objects (e.g. PointExecutable or /// VolumeExecutable) from a syntax tree or snippet of code. class Compiler { public: using Ptr = std::shared_ptr<Compiler>; using UniquePtr = std::unique_ptr<Compiler>; /// @brief Construct a compiler object with given settings /// @param options CompilerOptions object with various settings Compiler(const CompilerOptions& options = CompilerOptions()); ~Compiler() = default; /// @brief Static method for creating Compiler objects static UniquePtr create(const CompilerOptions& options = CompilerOptions()); /// @brief Compile a given AST into an executable object of the given type. /// @param syntaxTree An abstract syntax tree to compile /// @param logger Logger for errors and warnings during compilation, this /// should be linked to an ast::Tree and populated with AST node + line /// number mappings for this Tree, e.g. during ast::parse(). This Tree can /// be different from the syntaxTree argument. /// @param data Optional external/custom data which is to be referenced by /// the executable object. It allows one to reference data held elsewhere, /// such as inside of a DCC, from inside the AX code /// @note If the logger has not been populated with AST node and line /// mappings, all messages will appear without valid line and column /// numbers. template <typename ExecutableT> typename ExecutableT::Ptr compile(const ast::Tree& syntaxTree, Logger& logger, const CustomData::Ptr data = CustomData::Ptr()); /// @brief Compile a given snippet of AX code into an executable object of /// the given type. /// @param code A string of AX code /// @param logger Logger for errors and warnings during compilation, will be /// cleared of existing data /// @param data Optional external/custom data which is to be referenced by /// the executable object. It allows one to reference data held elsewhere, /// such as inside of a DCC, from inside the AX code /// @note If compilation is unsuccessful, will return nullptr. Logger can /// then be queried for errors. template <typename ExecutableT> typename ExecutableT::Ptr compile(const std::string& code, Logger& logger, const CustomData::Ptr data = CustomData::Ptr()) { logger.clear(); const ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger); if (syntaxTree) return compile<ExecutableT>(*syntaxTree, logger, data); else return nullptr; } /// @brief Compile a given snippet of AX code into an executable object of /// the given type. /// @param code A string of AX code /// @param data Optional external/custom data which is to be referenced by /// the executable object. It allows one to reference data held elsewhere, /// such as inside of a DCC, from inside the AX code /// @note Parser errors are handled separately from compiler errors. /// Each are collected and produce runtime errors. template <typename ExecutableT> typename ExecutableT::Ptr compile(const std::string& code, const CustomData::Ptr data = CustomData::Ptr()) { std::vector<std::string> errors; openvdb::ax::Logger logger( [&errors] (const std::string& error) { errors.emplace_back(error + "\n"); }, // ignore warnings [] (const std::string&) {} ); const ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger); typename ExecutableT::Ptr exe; if (syntaxTree) { exe = this->compile<ExecutableT>(*syntaxTree, logger, data); } if (!errors.empty()) { std::ostringstream os; for (const auto& e : errors) os << e << "\n"; OPENVDB_THROW(AXCompilerError, os.str()); } assert(exe); return exe; } /// @brief Compile a given AST into an executable object of the given type. /// @param syntaxTree An abstract syntax tree to compile /// @param data Optional external/custom data which is to be referenced by /// the executable object. It allows one to reference data held elsewhere, /// such as inside of a DCC, from inside the AX code /// @note Any errors encountered are collected into a single runtime error template <typename ExecutableT> typename ExecutableT::Ptr compile(const ast::Tree& syntaxTree, const CustomData::Ptr data = CustomData::Ptr()) { std::vector<std::string> errors; openvdb::ax::Logger logger( [&errors] (const std::string& error) { errors.emplace_back(error + "\n"); }, // ignore warnings [] (const std::string&) {} ); auto exe = compile<ExecutableT>(syntaxTree, logger, data); if (!errors.empty()) { std::ostringstream os; for (const auto& e : errors) os << e << "\n"; OPENVDB_THROW(AXCompilerError, os.str()); } assert(exe); return exe; } /// @brief Sets the compiler's function registry object. /// @param functionRegistry A unique pointer to a FunctionRegistry object. /// The compiler will take ownership of the registry that was passed in. /// @todo Perhaps allow one to register individual functions into this /// class rather than the entire registry at once, and/or allow one to /// extract a pointer to the registry and update it manually. void setFunctionRegistry(std::unique_ptr<codegen::FunctionRegistry>&& functionRegistry); /////////////////////////////////////////////////////////////////////////// private: std::shared_ptr<llvm::LLVMContext> mContext; const CompilerOptions mCompilerOptions; std::shared_ptr<codegen::FunctionRegistry> mFunctionRegistry; }; } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_HAS_BEEN_INCLUDED
7,279
C
36.720207
92
0.65215
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Logger.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/Logger.cc #include "Logger.h" #include <stack> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { struct Logger::Settings { size_t mMaxErrors = 0; bool mWarningsAsErrors = false; // message formatting settings bool mNumbered = true; const char* mErrorPrefix = "error: "; const char* mWarningPrefix = "warning: "; bool mPrintLines = false; }; /// @brief Wrapper around a code snippet to print individual lines from a multi /// line string /// @note Assumes a null terminated c-style string input struct Logger::SourceCode { SourceCode(const char* string = nullptr) : mString(string) , mOffsets() , mLines() { reset(string); } /// @brief Print a line of the multi-line string to the stream /// @note If no string hs been provided, will do nothing /// @param line Line number to print /// @param os Output stream void getLine(const size_t num, std::ostream* os) { if (num < 1) return; if (mOffsets.empty()) getLineOffsets(); if (num > mLines) return; const size_t start = mOffsets[num - 1]; const size_t end = mOffsets[num]; for (size_t i = start; i < end - 1; ++i) *os << mString[i]; } void reset(const char* string) { mString = string; mOffsets.clear(); mLines = 0; } bool hasString() const { return static_cast<bool>(mString); } private: void getLineOffsets() { if (!mString) return; mOffsets.emplace_back(0); size_t offset = 1; const char* iter = mString; while (*iter != '\0') { if (*iter == '\n') mOffsets.emplace_back(offset); ++iter; ++offset; } mOffsets.emplace_back(offset); mLines = mOffsets.size(); } const char* mString; std::vector<size_t> mOffsets; size_t mLines; }; namespace { /// @brief Return a stack denoting the position in the tree of this node /// Where each node is represented by its childidx of its parent /// This gives a branching path to follow to reach this node from the /// tree root /// @parm node Node pointer to create position stack for inline std::stack<size_t> pathStackFromNode(const ast::Node* node) { std::stack<size_t> path; const ast::Node* child = node; const ast::Node* parent = node->parent(); while (parent) { path.emplace(child->childidx()); child = parent; parent = child->parent(); } return path; } /// @brief Iterate through a tree, following the branch numbers from the path /// stack, returning a Node* to the node at this position /// @parm path Stack of child branches to follow /// @parm tree Tree containing node to return inline const ast::Node* nodeFromPathStack(std::stack<size_t>& path, const ast::Tree& tree) { const ast::Node* node = &tree; while (node) { if (path.empty()) return node; node = node->child(path.top()); path.pop(); } return nullptr; } /// @brief Given any node and a tree and node to location map, return the line /// and column number for the nodes equivalent (in terms of position in the /// tree) from the supplied tree /// @note Requires the map to have been populated for all nodes in the supplied /// tree, otherwise will return 0:0 inline const Logger::CodeLocation nodeToCodeLocation(const ast::Node* node, const ast::Tree::ConstPtr tree, const std::unordered_map <const ax::ast::Node*, Logger::CodeLocation>& map) { if (!tree) return Logger::CodeLocation(0,0); assert(node); std::stack<size_t> pathStack = pathStackFromNode(node); const ast::Node* nodeInMap = nodeFromPathStack(pathStack, *tree); const auto locationIter = map.find(nodeInMap); if (locationIter == map.end()) return Logger::CodeLocation(0,0); return locationIter->second; } std::string format(const std::string& message, const Logger::CodeLocation& loc, const size_t numMessage, const bool numbered, const bool printLines, Logger::SourceCode* sourceCode) { std::stringstream ss; if (numbered) ss << "[" << numMessage + 1 << "] "; ss << message; if (loc.first > 0) { ss << " " << loc.first << ":" << loc.second; if (printLines && sourceCode) { ss << "\n"; sourceCode->getLine(loc.first, &ss); ss << "\n"; for (size_t i = 0; i < loc.second - 1; ++i) ss << "-"; ss << "^"; } } return ss.str(); } } Logger::Logger(const Logger::OutputFunction& errors, const Logger::OutputFunction& warnings) : mErrorOutput(errors) , mWarningOutput(warnings) , mNumErrors(0) , mNumWarnings(0) , mSettings(new Logger::Settings()) , mCode() {} Logger::~Logger() {} void Logger::setSourceCode(const char* code) { mCode.reset(new SourceCode(code)); } bool Logger::error(const std::string& message, const Logger::CodeLocation& lineCol) { // already exceeded the error limit if (this->atErrorLimit()) return false; mErrorOutput(format(this->getErrorPrefix() + message, lineCol, this->errors(), this->getNumberedOutput(), this->getPrintLines(), this->mCode.get())); ++mNumErrors; // now exceeds the limit if (this->atErrorLimit()) return false; else return true; } bool Logger::error(const std::string& message, const ax::ast::Node* node) { return this->error(message, nodeToCodeLocation(node, mTreePtr, mNodeToLineColMap)); } bool Logger::warning(const std::string& message, const Logger::CodeLocation& lineCol) { if (this->getWarningsAsErrors()) { return this->error(message + " [warning-as-error]", lineCol); } else { mWarningOutput(format(this->getWarningPrefix() + message, lineCol, this->warnings(), this->getNumberedOutput(), this->getPrintLines(), this->mCode.get())); ++mNumWarnings; return true; } } bool Logger::warning(const std::string& message, const ax::ast::Node* node) { return this->warning(message, nodeToCodeLocation(node, mTreePtr, mNodeToLineColMap)); } void Logger::setWarningsAsErrors(const bool warnAsError) { mSettings->mWarningsAsErrors = warnAsError; } bool Logger::getWarningsAsErrors() const { return mSettings->mWarningsAsErrors; } void Logger::setMaxErrors(const size_t maxErrors) { mSettings->mMaxErrors = maxErrors; } size_t Logger::getMaxErrors() const { return mSettings->mMaxErrors; } void Logger::setNumberedOutput(const bool numbered) { mSettings->mNumbered = numbered; } void Logger::setErrorPrefix(const char* prefix) { mSettings->mErrorPrefix = prefix; } void Logger::setWarningPrefix(const char* prefix) { mSettings->mWarningPrefix = prefix; } void Logger::setPrintLines(const bool print) { mSettings->mPrintLines = print; } bool Logger::getNumberedOutput() const { return mSettings->mNumbered; } const char* Logger::getErrorPrefix() const { return mSettings->mErrorPrefix; } const char* Logger::getWarningPrefix() const { return mSettings->mWarningPrefix; } bool Logger::getPrintLines() const { return mSettings->mPrintLines; } void Logger::clear() { mCode.reset(); mNumErrors = 0; mNumWarnings = 0; mNodeToLineColMap.clear(); mTreePtr = nullptr; } void Logger::setSourceTree(openvdb::ax::ast::Tree::ConstPtr tree) { mTreePtr = tree; } void Logger::addNodeLocation(const ax::ast::Node* node, const Logger::CodeLocation& location) { mNodeToLineColMap.emplace(node, location); } } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
8,366
C++
25.903537
93
0.60447
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Compiler.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/Compiler.cc #include "Compiler.h" #include "PointExecutable.h" #include "VolumeExecutable.h" #include "../ast/Scanners.h" #include "../codegen/Functions.h" #include "../codegen/PointComputeGenerator.h" #include "../codegen/VolumeComputeGenerator.h" #include "../Exceptions.h" #include <openvdb/Exceptions.h> #include <llvm/ADT/Optional.h> #include <llvm/ADT/Triple.h> #include <llvm/Analysis/TargetLibraryInfo.h> #include <llvm/Analysis/TargetTransformInfo.h> #include <llvm/Config/llvm-config.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Mangler.h> #include <llvm/IR/Module.h> #include <llvm/IR/PassManager.h> #include <llvm/IR/Verifier.h> #include <llvm/IRReader/IRReader.h> #include <llvm/MC/SubtargetFeature.h> #include <llvm/Passes/PassBuilder.h> #include <llvm/Support/Host.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Support/raw_os_ostream.h> #include <llvm/Support/SourceMgr.h> // SMDiagnostic #include <llvm/Support/TargetRegistry.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetOptions.h> // @note As of adding support for LLVM 5.0 we not longer explicitly // perform standrd compiler passes (-std-compile-opts) based on the changes // to the opt binary in the llvm codebase (tools/opt.cpp). We also no // longer explicitly perform: // - llvm::createStripSymbolsPass() // And have never performed any specific target machine analysis passes // // @todo Properly identify the IPO passes that we would benefit from using // as well as what user controls would otherwise be appropriate #include <llvm/Transforms/IPO.h> // Inter-procedural optimization passes #include <llvm/Transforms/IPO/AlwaysInliner.h> #include <llvm/Transforms/IPO/PassManagerBuilder.h> #include <unordered_map> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace { /// @brief Initialize a target machine for the host platform. Returns a nullptr /// if a target could not be created. /// @note This logic is based off the Kaleidoscope tutorial below with extensions /// for CPU and CPU featrue set targetting /// https://llvm.org/docs/tutorial/MyFirstLanguageFrontend/LangImpl08.html inline std::unique_ptr<llvm::TargetMachine> initializeTargetMachine() { const std::string TargetTriple = llvm::sys::getDefaultTargetTriple(); std::string Error; const llvm::Target* Target = llvm::TargetRegistry::lookupTarget(TargetTriple, Error); if (!Target) { OPENVDB_LOG_DEBUG_RUNTIME("Unable to retrieve target machine information. " "No target specific optimization will be performed: " << Error); return nullptr; } // default cpu with no additional features = "generic" const llvm::StringRef& CPU = llvm::sys::getHostCPUName(); llvm::SubtargetFeatures Features; llvm::StringMap<bool> HostFeatures; if (llvm::sys::getHostCPUFeatures(HostFeatures)) for (auto &F : HostFeatures) Features.AddFeature(F.first(), F.second); // default options llvm::TargetOptions opt; const llvm::Optional<llvm::Reloc::Model> RM = llvm::Optional<llvm::Reloc::Model>(); std::unique_ptr<llvm::TargetMachine> TargetMachine( Target->createTargetMachine(TargetTriple, CPU, Features.getString(), opt, RM)); return TargetMachine; } #ifndef USE_NEW_PASS_MANAGER void addStandardLinkPasses(llvm::legacy::PassManagerBase& passes) { llvm::PassManagerBuilder builder; builder.VerifyInput = true; builder.Inliner = llvm::createFunctionInliningPass(); builder.populateLTOPassManager(passes); } /// This routine adds optimization passes based on selected optimization level /// void addOptimizationPasses(llvm::legacy::PassManagerBase& passes, llvm::legacy::FunctionPassManager& functionPasses, llvm::TargetMachine* targetMachine, const unsigned optLevel, const unsigned sizeLevel, const bool disableInline = false, const bool disableUnitAtATime = false, const bool disableLoopUnrolling = false, const bool disableLoopVectorization = false, const bool disableSLPVectorization = false) { llvm::PassManagerBuilder builder; builder.OptLevel = optLevel; builder.SizeLevel = sizeLevel; if (disableInline) { // No inlining pass } else if (optLevel > 1) { builder.Inliner = llvm::createFunctionInliningPass(optLevel, sizeLevel, /*DisableInlineHotCallSite*/false); } else { builder.Inliner = llvm::createAlwaysInlinerLegacyPass(); } #if LLVM_VERSION_MAJOR < 9 // Enable IPO. This corresponds to gcc's -funit-at-a-time builder.DisableUnitAtATime = disableUnitAtATime; #else // unused from llvm 9 (void)(disableUnitAtATime); #endif // Disable loop unrolling in all relevant passes builder.DisableUnrollLoops = disableLoopUnrolling ? disableLoopUnrolling : optLevel == 0; // See the following link for more info on vectorizers // http://llvm.org/docs/Vectorizers.html // (-vectorize-loops, -loop-vectorize) builder.LoopVectorize = disableLoopVectorization ? false : optLevel > 1 && sizeLevel < 2; builder.SLPVectorize = disableSLPVectorization ? false : optLevel > 1 && sizeLevel < 2; // If a target machine is provided, allow the target to modify the pass manager // e.g. by calling PassManagerBuilder::addExtension. if (targetMachine) { targetMachine->adjustPassManager(builder); } builder.populateFunctionPassManager(functionPasses); builder.populateModulePassManager(passes); } void LLVMoptimise(llvm::Module* module, const unsigned optLevel, const unsigned sizeLevel, const bool verify, llvm::TargetMachine* TM) { // Pass manager setup and IR optimisations - Do target independent optimisations // only - i.e. the following do not require an llvm TargetMachine analysis pass llvm::legacy::PassManager passes; llvm::TargetLibraryInfoImpl TLII(llvm::Triple(module->getTargetTriple())); passes.add(new llvm::TargetLibraryInfoWrapperPass(TLII)); // Add internal analysis passes from the target machine. if (TM) passes.add(llvm::createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); else passes.add(llvm::createTargetTransformInfoWrapperPass(llvm::TargetIRAnalysis())); llvm::legacy::FunctionPassManager functionPasses(module); if (TM) functionPasses.add(llvm::createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); else functionPasses.add(llvm::createTargetTransformInfoWrapperPass(llvm::TargetIRAnalysis())); if (verify) functionPasses.add(llvm::createVerifierPass()); addStandardLinkPasses(passes); addOptimizationPasses(passes, functionPasses, TM, optLevel, sizeLevel); functionPasses.doInitialization(); for (llvm::Function& function : *module) { functionPasses.run(function); } functionPasses.doFinalization(); if (verify) passes.add(llvm::createVerifierPass()); passes.run(*module); } void LLVMoptimise(llvm::Module* module, const llvm::PassBuilder::OptimizationLevel opt, const bool verify, llvm::TargetMachine* TM) { unsigned optLevel = 0, sizeLevel = 0; // llvm::PassBuilder::OptimizationLevel is an enum in llvm 10 // and earlier, a class in llvm 11 and later (which holds // various member data about the optimization level) #if LLVM_VERSION_MAJOR < 11 switch (opt) { case llvm::PassBuilder::OptimizationLevel::O0 : { optLevel = 0; sizeLevel = 0; break; } case llvm::PassBuilder::OptimizationLevel::O1 : { optLevel = 1; sizeLevel = 0; break; } case llvm::PassBuilder::OptimizationLevel::O2 : { optLevel = 2; sizeLevel = 0; break; } case llvm::PassBuilder::OptimizationLevel::Os : { optLevel = 2; sizeLevel = 1; break; } case llvm::PassBuilder::OptimizationLevel::Oz : { optLevel = 2; sizeLevel = 2; break; } case llvm::PassBuilder::OptimizationLevel::O3 : { optLevel = 3; sizeLevel = 0; break; } default : {} } #else optLevel = opt.getSpeedupLevel(); sizeLevel = opt.getSizeLevel(); #endif LLVMoptimise(module, optLevel, sizeLevel, verify, TM); } #else void LLVMoptimise(llvm::Module* module, const llvm::PassBuilder::OptimizationLevel optLevel, const bool verify, llvm::TargetMachine* TM) { // use the PassBuilder for optimisation pass management // see llvm's llvm/Passes/PassBuilder.h, tools/opt/NewPMDriver.cpp // and clang's CodeGen/BackEndUtil.cpp for more info/examples llvm::PassBuilder PB(TM); llvm::LoopAnalysisManager LAM; llvm::FunctionAnalysisManager FAM; llvm::CGSCCAnalysisManager cGSCCAM; llvm::ModuleAnalysisManager MAM; // register all of the analysis passes available by default PB.registerModuleAnalyses(MAM); PB.registerCGSCCAnalyses(cGSCCAM); PB.registerFunctionAnalyses(FAM); PB.registerLoopAnalyses(LAM); // the analysis managers above are interdependent so // register dependent managers with each other via proxies PB.crossRegisterProxies(LAM, FAM, cGSCCAM, MAM); // the PassBuilder does not produce -O0 pipelines, so do that ourselves if (optLevel == llvm::PassBuilder::OptimizationLevel::O0) { // matching clang -O0, only add inliner pass // ref: clang CodeGen/BackEndUtil.cpp EmitAssemblyWithNewPassManager llvm::ModulePassManager MPM; MPM.addPass(llvm::AlwaysInlinerPass()); if (verify) MPM.addPass(llvm::VerifierPass()); MPM.run(*module, MAM); } else { // create a clang-like optimisation pipeline for -O1, 2, s, z, 3 llvm::ModulePassManager MPM = PB.buildPerModuleDefaultPipeline(optLevel); if (verify) MPM.addPass(llvm::VerifierPass()); MPM.run(*module, MAM); } } #endif void optimiseAndVerify(llvm::Module* module, const bool verify, const CompilerOptions::OptLevel optLevel, llvm::TargetMachine* TM) { if (verify) { llvm::raw_os_ostream out(std::cout); if (llvm::verifyModule(*module, &out)) { OPENVDB_THROW(AXCompilerError, "Generated LLVM IR is not valid."); } } switch (optLevel) { case CompilerOptions::OptLevel::O0 : { LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O0, verify, TM); break; } case CompilerOptions::OptLevel::O1 : { LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O1, verify, TM); break; } case CompilerOptions::OptLevel::O2 : { LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O2, verify, TM); break; } case CompilerOptions::OptLevel::Os : { LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::Os, verify, TM); break; } case CompilerOptions::OptLevel::Oz : { LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::Oz, verify, TM); break; } case CompilerOptions::OptLevel::O3 : { LLVMoptimise(module, llvm::PassBuilder::OptimizationLevel::O3, verify, TM); break; } case CompilerOptions::OptLevel::NONE : default : {} } } void initializeGlobalFunctions(const codegen::FunctionRegistry& registry, llvm::ExecutionEngine& engine, llvm::Module& module) { /// @note This is a copy of ExecutionEngine::getMangledName. LLVM's ExecutionEngine /// provides two signatures for updating global mappings, one which takes a void* and /// another which takes a uint64_t address. When providing function mappings, /// it is potentially unsafe to cast pointers-to-functions to pointers-to-objects /// as they are not guaranteed to have the same size on some (albiet non "standard") /// platforms. getMangledName is protected, so a copy exists here to allows us to /// call the uint64_t method. /// @note This is only caught by -pendantic so this work around may be overkill auto getMangledName = [](const llvm::GlobalValue* GV, const llvm::ExecutionEngine& E) -> std::string { llvm::SmallString<128> FullName; const llvm::DataLayout& DL = GV->getParent()->getDataLayout().isDefault() ? E.getDataLayout() : GV->getParent()->getDataLayout(); llvm::Mangler::getNameWithPrefix(FullName, GV->getName(), DL); return std::string(FullName.str()); }; /// @note Could use InstallLazyFunctionCreator here instead as follows: /// /// engine.InstallLazyFunctionCreator([](const std::string& name) -> void * { /// // Loop through register and find matching symbol /// }); /// /// However note that if functions have been compiled with mLazyFunctions that the /// below code using addGlobalMapping() only adds mapping for instantiated /// functions anyway. /// /// @note Depending on how functions are inserted into LLVM (Linkage Type) in /// the future, InstallLazyFunctionCreator may be required for (const auto& iter : registry.map()) { const codegen::FunctionGroup* const function = iter.second.function(); if (!function) continue; const codegen::FunctionGroup::FunctionList& list = function->list(); for (const codegen::Function::Ptr& decl : list) { // llvmFunction may not exists if compiled without mLazyFunctions const llvm::Function* llvmFunction = module.getFunction(decl->symbol()); // if the function has an entry block, it's not a C binding - this is a // quick check to improve performance (so we don't call virtual methods // for every function) if (!llvmFunction) continue; if (llvmFunction->size() > 0) continue; const codegen::CFunctionBase* binding = dynamic_cast<const codegen::CFunctionBase*>(decl.get()); if (!binding) { OPENVDB_LOG_WARN("Function with symbol \"" << decl->symbol() << "\" has " "no function body and is not a C binding."); continue; } const uint64_t address = binding->address(); if (address == 0) { OPENVDB_THROW(AXCompilerError, "No available mapping for C Binding " "with symbol \"" << decl->symbol() << "\""); } const std::string mangled = getMangledName(llvm::cast<llvm::GlobalValue>(llvmFunction), engine); // error if updateGlobalMapping returned a previously mapped address, as // we've overwritten something const uint64_t oldAddress = engine.updateGlobalMapping(mangled, address); if (oldAddress != 0 && oldAddress != address) { OPENVDB_THROW(AXCompilerError, "Function registry mapping error - " "multiple functions are using the same symbol \"" << decl->symbol() << "\"."); } } } #ifndef NDEBUG // Loop through all functions and check to see if they have valid engine mappings. // This can occur if lazy functions don't initialize their dependencies properly. // @todo Really we should just loop through the module functions to begin with // to init engine mappings - it would probably be faster but we'd have to do // some string manip and it would assume function names have been set up // correctly const auto& list = module.getFunctionList(); for (const auto& F : list) { if (F.size() > 0) continue; // Some LLVM functions may also not be defined at this stage which is expected if (!F.getName().startswith("ax")) continue; const std::string mangled = getMangledName(llvm::cast<llvm::GlobalValue>(&F), engine); const uint64_t address = engine.getAddressToGlobalIfAvailable(mangled); assert(address != 0 && "Unbound function!"); } #endif } void verifyTypedAccesses(const ast::Tree& tree, openvdb::ax::Logger& logger) { // verify the attributes and external variables requested in the syntax tree // only have a single type. Note that the executer will also throw a runtime // error if the same attribute is accessed with different types, but as that's // currently not a valid state on a PointDataGrid, error in compilation as well // @todo - introduce a framework for supporting custom preprocessors std::unordered_map<std::string, std::string> nameType; auto attributeOp = [&nameType, &logger](const ast::Attribute& node) -> bool { auto iter = nameType.find(node.name()); if (iter == nameType.end()) { nameType[node.name()] = node.typestr(); } else if (iter->second != node.typestr()) { logger.error("failed to compile ambiguous @ parameters. " "\"" + node.name() + "\" has been accessed with different type elsewhere.", &node); } return true; }; ast::visitNodeType<ast::Attribute>(tree, attributeOp); nameType.clear(); auto externalOp = [&nameType, &logger](const ast::ExternalVariable& node) -> bool { auto iter = nameType.find(node.name()); if (iter == nameType.end()) { nameType[node.name()] = node.typestr(); } else if (iter->second != node.typestr()) { logger.error("failed to compile ambiguous $ parameters. " "\"" + node.name() + "\" has been accessed with different type elsewhere.", &node); } return true; }; ast::visitNodeType<ast::ExternalVariable>(tree, externalOp); } inline void registerAccesses(const codegen::SymbolTable& globals, const AttributeRegistry& registry) { std::string name, type; for (const auto& global : globals.map()) { // detect if this global variable is an attribute access const std::string& token = global.first; if (!ast::Attribute::nametypeFromToken(token, &name, &type)) continue; const ast::tokens::CoreType typetoken = ast::tokens::tokenFromTypeString(type); // add the access to the registry - this will force the executables // to always request or create the data type const size_t index = registry.accessIndex(name, typetoken); // should always be a GlobalVariable. assert(llvm::isa<llvm::GlobalVariable>(global.second)); // Assign the attribute index global a valid index. // @note executionEngine->addGlobalMapping() can also be used if the indices // ever need to vary positions without having to force a recompile (previously // was used unnecessarily) llvm::GlobalVariable* variable = llvm::cast<llvm::GlobalVariable>(global.second); assert(variable->getValueType()->isIntegerTy(64)); variable->setInitializer(llvm::ConstantInt::get(variable->getValueType(), index)); variable->setConstant(true); // is not written to at runtime } } template <typename T, typename MetadataType = TypedMetadata<T>> inline llvm::Constant* initializeMetadataPtr(CustomData& data, const std::string& name, llvm::LLVMContext& C) { MetadataType* meta = data.getOrInsertData<MetadataType>(name); if (meta) return codegen::LLVMType<T>::get(C, &(meta->value())); return nullptr; } inline void registerExternalGlobals(const codegen::SymbolTable& globals, CustomData::Ptr& dataPtr, llvm::LLVMContext& C) { auto initializerFromToken = [&](const ast::tokens::CoreType type, const std::string& name, CustomData& data) -> llvm::Constant* { switch (type) { case ast::tokens::BOOL : return initializeMetadataPtr<bool>(data, name, C); case ast::tokens::INT32 : return initializeMetadataPtr<int32_t>(data, name, C); case ast::tokens::INT64 : return initializeMetadataPtr<int64_t>(data, name, C); case ast::tokens::FLOAT : return initializeMetadataPtr<float>(data, name, C); case ast::tokens::DOUBLE : return initializeMetadataPtr<double>(data, name, C); case ast::tokens::VEC2I : return initializeMetadataPtr<math::Vec2<int32_t>>(data, name, C); case ast::tokens::VEC2F : return initializeMetadataPtr<math::Vec2<float>>(data, name, C); case ast::tokens::VEC2D : return initializeMetadataPtr<math::Vec2<double>>(data, name, C); case ast::tokens::VEC3I : return initializeMetadataPtr<math::Vec3<int32_t>>(data, name, C); case ast::tokens::VEC3F : return initializeMetadataPtr<math::Vec3<float>>(data, name, C); case ast::tokens::VEC3D : return initializeMetadataPtr<math::Vec3<double>>(data, name, C); case ast::tokens::VEC4I : return initializeMetadataPtr<math::Vec4<int32_t>>(data, name, C); case ast::tokens::VEC4F : return initializeMetadataPtr<math::Vec4<float>>(data, name, C); case ast::tokens::VEC4D : return initializeMetadataPtr<math::Vec4<double>>(data, name, C); case ast::tokens::MAT3F : return initializeMetadataPtr<math::Mat3<float>>(data, name, C); case ast::tokens::MAT3D : return initializeMetadataPtr<math::Mat3<double>>(data, name, C); case ast::tokens::MAT4F : return initializeMetadataPtr<math::Mat4<float>>(data, name, C); case ast::tokens::MAT4D : return initializeMetadataPtr<math::Mat4<double>>(data, name, C); case ast::tokens::STRING : return initializeMetadataPtr<ax::AXString, ax::AXStringMetadata>(data, name, C); case ast::tokens::UNKNOWN : default : { // grammar guarantees this is unreachable as long as all types are supported OPENVDB_THROW(AXCompilerError, "Attribute type unsupported or not recognised"); } } }; std::string name, typestr; for (const auto& global : globals.map()) { const std::string& token = global.first; if (!ast::ExternalVariable::nametypeFromToken(token, &name, &typestr)) continue; const ast::tokens::CoreType typetoken = ast::tokens::tokenFromTypeString(typestr); // if we have any external variables, the custom data must be initialized to at least hold // zero values (initialized by the default metadata types) if (!dataPtr) dataPtr.reset(new CustomData); // should always be a GlobalVariable. assert(llvm::isa<llvm::GlobalVariable>(global.second)); llvm::GlobalVariable* variable = llvm::cast<llvm::GlobalVariable>(global.second); assert(variable->getValueType() == codegen::LLVMType<uintptr_t>::get(C)); llvm::Constant* initializer = initializerFromToken(typetoken, name, *dataPtr); if (!initializer) { OPENVDB_THROW(AXCompilerError, "Custom data \"" + name + "\" already exists with a " "different type."); } variable->setInitializer(initializer); variable->setConstant(true); // is not written to at runtime } } struct PointDefaultModifier : public openvdb::ax::ast::Visitor<PointDefaultModifier, /*non-const*/false> { using openvdb::ax::ast::Visitor<PointDefaultModifier, false>::traverse; using openvdb::ax::ast::Visitor<PointDefaultModifier, false>::visit; PointDefaultModifier() = default; virtual ~PointDefaultModifier() = default; const std::set<std::string> autoVecAttribs {"P", "v", "N", "Cd"}; bool visit(ast::Attribute* attrib) { if (!attrib->inferred()) return true; if (autoVecAttribs.find(attrib->name()) == autoVecAttribs.end()) return true; openvdb::ax::ast::Attribute::UniquePtr replacement(new openvdb::ax::ast::Attribute(attrib->name(), ast::tokens::VEC3F, true)); if (!attrib->replace(replacement.get())) { OPENVDB_THROW(AXCompilerError, "Auto conversion of inferred attributes failed."); } replacement.release(); return true; } }; } // anonymous namespace ///////////////////////////////////////////////////////////////////////////// Compiler::Compiler(const CompilerOptions& options) : mContext() , mCompilerOptions(options) , mFunctionRegistry() { mContext.reset(new llvm::LLVMContext); mFunctionRegistry = codegen::createDefaultRegistry(&options.mFunctionOptions); } Compiler::UniquePtr Compiler::create(const CompilerOptions &options) { UniquePtr compiler(new Compiler(options)); return compiler; } void Compiler::setFunctionRegistry(std::unique_ptr<codegen::FunctionRegistry>&& functionRegistry) { mFunctionRegistry = std::move(functionRegistry); } template<> PointExecutable::Ptr Compiler::compile<PointExecutable>(const ast::Tree& syntaxTree, Logger& logger, const CustomData::Ptr customData) { openvdb::SharedPtr<ast::Tree> tree(syntaxTree.copy()); PointDefaultModifier modifier; modifier.traverse(tree.get()); verifyTypedAccesses(*tree, logger); // initialize the module and generate LLVM IR std::unique_ptr<llvm::Module> module(new llvm::Module("module", *mContext)); std::unique_ptr<llvm::TargetMachine> TM = initializeTargetMachine(); if (TM) { module->setDataLayout(TM->createDataLayout()); module->setTargetTriple(TM->getTargetTriple().normalize()); } codegen::codegen_internal::PointComputeGenerator codeGenerator(*module, mCompilerOptions.mFunctionOptions, *mFunctionRegistry, logger); AttributeRegistry::Ptr attributes = codeGenerator.generate(*tree); // if there has been a compilation error through user error, exit if (!attributes) { assert(logger.hasError()); return nullptr; } // map accesses (always do this prior to optimising as globals may be removed) registerAccesses(codeGenerator.globals(), *attributes); CustomData::Ptr validCustomData(customData); registerExternalGlobals(codeGenerator.globals(), validCustomData, *mContext); // optimise llvm::Module* modulePtr = module.get(); optimiseAndVerify(modulePtr, mCompilerOptions.mVerify, mCompilerOptions.mOptLevel, TM.get()); // @todo re-constant fold!! although constant folding will work with constant // expressions prior to optimisation, expressions like "int a = 1; cosh(a);" // will still keep a call to cosh. This is because the current AX folding // only checks for an immediate constant expression and for C bindings, // like cosh, llvm its unable to optimise the call out (as it isn't aware // of the function body). What llvm can do, however, is change this example // into "cosh(1)" which we can then handle. // create the llvm execution engine which will build our function pointers std::string error; std::shared_ptr<llvm::ExecutionEngine> executionEngine(llvm::EngineBuilder(std::move(module)) .setEngineKind(llvm::EngineKind::JIT) .setErrorStr(&error) .create()); if (!executionEngine) { OPENVDB_THROW(AXCompilerError, "Failed to create LLVMExecutionEngine: " + error); } // map functions initializeGlobalFunctions(*mFunctionRegistry, *executionEngine, *modulePtr); // finalize mapping executionEngine->finalizeObject(); // get the built function pointers const std::vector<std::string> functionNames { codegen::PointKernel::getDefaultName(), codegen::PointRangeKernel::getDefaultName() }; std::unordered_map<std::string, uint64_t> functionMap; for (const std::string& name : functionNames) { const uint64_t address = executionEngine->getFunctionAddress(name); if (!address) { OPENVDB_THROW(AXCompilerError, "Failed to compile compute function \"" + name + "\""); } functionMap[name] = address; } // create final executable object PointExecutable::Ptr executable(new PointExecutable(mContext, executionEngine, attributes, validCustomData, functionMap)); return executable; } template<> VolumeExecutable::Ptr Compiler::compile<VolumeExecutable>(const ast::Tree& syntaxTree, Logger& logger, const CustomData::Ptr customData) { verifyTypedAccesses(syntaxTree, logger); // initialize the module and generate LLVM IR std::unique_ptr<llvm::Module> module(new llvm::Module("module", *mContext)); std::unique_ptr<llvm::TargetMachine> TM = initializeTargetMachine(); if (TM) { module->setDataLayout(TM->createDataLayout()); module->setTargetTriple(TM->getTargetTriple().normalize()); } codegen::codegen_internal::VolumeComputeGenerator codeGenerator(*module, mCompilerOptions.mFunctionOptions, *mFunctionRegistry, logger); AttributeRegistry::Ptr attributes = codeGenerator.generate(syntaxTree); // if there has been a compilation error through user error, exit if (!attributes) { assert(logger.hasError()); return nullptr; } // map accesses (always do this prior to optimising as globals may be removed) registerAccesses(codeGenerator.globals(), *attributes); CustomData::Ptr validCustomData(customData); registerExternalGlobals(codeGenerator.globals(), validCustomData, *mContext); llvm::Module* modulePtr = module.get(); optimiseAndVerify(modulePtr, mCompilerOptions.mVerify, mCompilerOptions.mOptLevel, TM.get()); std::string error; std::shared_ptr<llvm::ExecutionEngine> executionEngine(llvm::EngineBuilder(std::move(module)) .setEngineKind(llvm::EngineKind::JIT) .setErrorStr(&error) .create()); if (!executionEngine) { OPENVDB_THROW(AXCompilerError, "Failed to create LLVMExecutionEngine: " + error); } // map functions initializeGlobalFunctions(*mFunctionRegistry, *executionEngine, *modulePtr); // finalize mapping executionEngine->finalizeObject(); const std::string name = codegen::VolumeKernel::getDefaultName(); const uint64_t address = executionEngine->getFunctionAddress(name); if (!address) { OPENVDB_THROW(AXCompilerError, "Failed to compile compute function \"" + name + "\""); } std::unordered_map<std::string, uint64_t> functionMap; functionMap[name] = address; // create final executable object VolumeExecutable::Ptr executable(new VolumeExecutable(mContext, executionEngine, attributes, validCustomData, functionMap)); return executable; } } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
32,049
C++
37.801453
120
0.649069
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/PointExecutable.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/PointExecutable.h /// /// @authors Nick Avramoussis, Francisco Gochez, Richard Jones /// /// @brief The PointExecutable, produced by the OpenVDB AX Compiler for /// execution over OpenVDB Points Grids. /// #ifndef OPENVDB_AX_COMPILER_POINT_EXECUTABLE_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_POINT_EXECUTABLE_HAS_BEEN_INCLUDED #include "CustomData.h" #include "AttributeRegistry.h" #include <openvdb/openvdb.h> #include <openvdb/version.h> #include <openvdb/points/PointDataGrid.h> #include <unordered_map> class TestPointExecutable; namespace llvm { class ExecutionEngine; class LLVMContext; } namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { class Compiler; /// @brief Object that encapsulates compiled AX code which can be executed on a target point grid class PointExecutable { public: using Ptr = std::shared_ptr<PointExecutable>; ~PointExecutable(); /// @brief Copy constructor. Shares the LLVM constructs but deep copies the /// settings. Multiple copies of an executor can be used at the same time /// safely. PointExecutable(const PointExecutable& other); //////////////////////////////////////////////////////// /// @brief executes compiled AX code on target grid void execute(points::PointDataGrid& grid) const; //////////////////////////////////////////////////////// /// @brief Set a specific point group to execute over. The default is none, /// which corresponds to all points. Note that this can also be compiled /// into the AX function using the ingroup("mygroup") method. /// @warning If the group does not exist during execute, a runtime error /// will be thrown. /// @param name The name of the group to execute over void setGroupExecution(const std::string& name); /// @return The points group to be processed. Default is empty, which is /// all points. const std::string& getGroupExecution() const; /// @brief Set the behaviour when missing point attributes are accessed. /// Default behaviour is true, which creates them with default initial /// values. If false, a missing attribute runtime error will be thrown /// on missing accesses. /// @param flag Enables or disables the creation of missing attributes void setCreateMissing(const bool flag); /// @return Whether this executable will generate new point attributes. bool getCreateMissing() const; /// @brief Set the threading grain size. Default is 1. A value of 0 has the /// effect of disabling multi-threading. /// @param grain The grain size void setGrainSize(const size_t grain); /// @return The current grain size size_t getGrainSize() const; //////////////////////////////////////////////////////// // foward declaration of settings for this executable struct Settings; private: friend class Compiler; friend class ::TestPointExecutable; /// @brief Constructor, expected to be invoked by the compiler. Should not /// be invoked directly. /// @param context Shared pointer to an llvm:LLVMContext associated with the /// execution engine /// @param engine Shared pointer to an llvm::ExecutionEngine used to build /// functions. Context should be the associated LLVMContext /// @param attributeRegistry Registry of attributes accessed by AX code /// @param customData Custom data which will be shared by this executable. /// It can be used to retrieve external data from within the AX code /// @param functions A map of function names to physical memory addresses /// which were built by llvm using engine PointExecutable(const std::shared_ptr<const llvm::LLVMContext>& context, const std::shared_ptr<const llvm::ExecutionEngine>& engine, const AttributeRegistry::ConstPtr& attributeRegistry, const CustomData::ConstPtr& customData, const std::unordered_map<std::string, uint64_t>& functions); private: // The Context and ExecutionEngine must exist _only_ for object lifetime // management. The ExecutionEngine must be destroyed before the Context const std::shared_ptr<const llvm::LLVMContext> mContext; const std::shared_ptr<const llvm::ExecutionEngine> mExecutionEngine; const AttributeRegistry::ConstPtr mAttributeRegistry; const CustomData::ConstPtr mCustomData; const std::unordered_map<std::string, uint64_t> mFunctionAddresses; std::unique_ptr<Settings> mSettings; }; } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_POINT_EXECUTABLE_HAS_BEEN_INCLUDED
4,845
C
37.15748
97
0.687307
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/Logger.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/Logger.h /// /// @authors Richard Jones /// /// @brief Logging system to collect errors and warnings throughout the /// different stages of parsing and compilation. /// #ifndef OPENVDB_AX_COMPILER_LOGGER_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_LOGGER_HAS_BEEN_INCLUDED #include "../ast/AST.h" #include <openvdb/version.h> #include <functional> #include <string> #include <unordered_map> class TestLogger; namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { /// @brief Logger for collecting errors and warnings that occur during AX /// compilation. /// /// @details Error and warning output can be customised using the function /// pointer arguments. These require a function that takes the formatted error /// or warning string and handles the output, returning void. /// e.g. /// void streamCerr(const std::string& message) { /// std::cerr << message << std::endl; /// } /// /// The Logger handles formatting of messages, tracking of number of errors or /// warnings and retrieval of errored lines of code to be printed if needed. /// Use of the Logger to track new errors or warnings can be done either with /// the line/column numbers directly (e.g during lexing and parsing where the /// code is being iterated through) or referring to the AST node using its /// position in the Tree (e.g. during codegen where only the AST node is known /// directly, not the corresponding line/column numbers). To find the line or /// column numbers for events logged using AST nodes, the Logger stores a map /// of Node* to line and column numbers. This must be populated e.g. during /// parsing, to allow resolution of code locations when they are not /// explicitly available. The Logger also stores a pointer to the AST Tree /// that these nodes belong to and the code used to create it. class Logger { public: using Ptr = std::shared_ptr<Logger>; using CodeLocation = std::pair<size_t, size_t>; using OutputFunction = std::function<void(const std::string&)>; /// @brief Construct a Logger with optional error and warning output /// functions, defaults stream errors to std::cerr and suppress warnings /// @param errors Optional error output function /// @param warnings Optional warning output function Logger(const OutputFunction& errors = [](const std::string& msg){ std::cerr << msg << std::endl; }, const OutputFunction& warnings = [](const std::string&){}); ~Logger(); /// @brief Log a compiler error and its offending code location. /// @param message The error message /// @param lineCol The line/column number of the offending code /// @return true if non-fatal and can continue to capture future messages. /// @todo: add logging of non position specific errors bool error(const std::string& message, const CodeLocation& lineCol); /// @brief Log a compiler error using the offending AST node. Used in AST /// traversal. /// @param message The error message /// @param node The offending AST node causing the error /// @return true if non-fatal and can continue to capture future messages. bool error(const std::string& message, const ax::ast::Node* node); /// @brief Log a compiler warning and its offending code location. /// @param message The warning message /// @param lineCol The line/column number of the offending code /// @return true if non-fatal and can continue to capture future messages. bool warning(const std::string& message, const CodeLocation& lineCol); /// @brief Log a compiler warning using the offending AST node. Used in AST /// traversal. /// @param message The warning message /// @param node The offending AST node causing the warning /// @return true if non-fatal and can continue to capture future messages. bool warning(const std::string& message, const ax::ast::Node* node); /// /// @brief Returns the number of errors that have been encountered inline size_t errors() const { return mNumErrors; } /// @brief Returns the number of warnings that have been encountered inline size_t warnings() const { return mNumWarnings; } /// @brief Returns true if an error has been found, false otherwise inline bool hasError() const { return this->errors() > 0; } /// @brief Returns true if a warning has been found, false otherwise inline bool hasWarning() const { return this->warnings() > 0; } /// @brief Returns true if it has errored and the max errors has been hit inline bool atErrorLimit() const { return this->getMaxErrors() > 0 && this->errors() >= this->getMaxErrors(); } /// @brief Clear the tree-code mapping and reset the number of errors/warnings /// @note The tree-code mapping must be repopulated to retrieve line and /// column numbers during AST traversal i.e. code generation. The /// openvdb::ax::ast::parse() function does this for a given input code /// string. void clear(); /// @brief Set any warnings that are encountered to be promoted to errors /// @param warnAsError If true, warnings will be treated as errors void setWarningsAsErrors(const bool warnAsError = false); /// @brief Returns if warning are promoted to errors bool getWarningsAsErrors() const; /// @brief Sets the maximum number of errors that are allowed before /// compilation should exit /// @param maxErrors The number of allowed errors void setMaxErrors(const size_t maxErrors = 0); /// @brief Returns the number of allowed errors size_t getMaxErrors() const; /// Error/warning formatting options /// @brief Set whether the output should number the errors/warnings /// @param numbered If true, messages will be numbered void setNumberedOutput(const bool numbered = true); /// @brief Set a prefix for each error message void setErrorPrefix(const char* prefix = "error: "); /// @brief Set a prefix for each warning message void setWarningPrefix(const char* prefix = "warning: "); /// @brief Set whether the output should include the offending line of code /// @param print If true, offending lines of code will be appended to the /// output message void setPrintLines(const bool print = true); /// @brief Returns whether the messages will be numbered bool getNumberedOutput() const; /// @brief Returns the prefix for each error message const char* getErrorPrefix() const; /// @brief Returns the prefix for each warning message const char* getWarningPrefix() const; /// @brief Returns whether the messages will include the line of offending code bool getPrintLines() const; /// @brief Set the source code that lines can be printed from if an error or /// warning is raised /// @param code The AX code as a c-style string void setSourceCode(const char* code); /// These functions are only to be used during parsing to allow line and /// column number retrieval during later stages of compilation when working /// solely with an AST /// @brief Set the AST source tree which will be used as reference for the /// locations of nodes when resolving line and column numbers during AST /// traversal /// @note To be used just by ax::parse before any AST modifications to /// ensure traversal of original source tree is possible, when adding /// messages using Node* which may correspond to modified trees /// @param tree Pointer to const AST void setSourceTree(openvdb::ax::ast::Tree::ConstPtr tree); /// @brief Add a node to the code location map /// @param node Pointer to AST node /// @param location Line and column number in code void addNodeLocation(const ax::ast::Node* node, const CodeLocation& location); // forward declaration struct Settings; struct SourceCode; private: friend class ::TestLogger; std::function<void(const std::string&)> mErrorOutput; std::function<void(const std::string&)> mWarningOutput; size_t mNumErrors; size_t mNumWarnings; std::unique_ptr<Settings> mSettings; // components needed for verbose error info i.e. line/column numbers and // lines from source code std::unique_ptr<SourceCode> mCode; ax::ast::Tree::ConstPtr mTreePtr; std::unordered_map<const ax::ast::Node*, CodeLocation> mNodeToLineColMap; }; } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_LOGGER_HAS_BEEN_INCLUDED
8,761
C
40.526066
83
0.696496
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/AttributeRegistry.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0/ /// @file compiler/AttributeRegistry.h /// /// @authors Nick Avramoussis, Francisco Gochez /// /// @brief These classes contain lists of expected attributes and volumes /// which are populated by compiler during its internal code generation. /// These will then be requested from the inputs to the executable /// when execute is called. In this way, accesses are requested at /// execution time, allowing the executable objects to be shared and /// stored. /// #ifndef OPENVDB_AX_COMPILER_TARGET_REGISTRY_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_TARGET_REGISTRY_HAS_BEEN_INCLUDED #include "../ast/AST.h" #include "../ast/Tokens.h" #include "../ast/Scanners.h" #include <openvdb/version.h> #include <unordered_map> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { /// @brief This class stores a list of access names, types and their dependency /// connections. /// class AttributeRegistry { public: using Ptr = std::shared_ptr<AttributeRegistry>; using ConstPtr = std::shared_ptr<const AttributeRegistry>; /// @brief Registered access details, including its name, type and whether /// a write handle is required /// struct AccessData { /// @brief Storage for access name, type and writesTo details /// @param name The name of the access /// @param type The typename of the access /// @param readsFrom Whether the access is read from /// @param writesTo Whether the access is writte to AccessData(const Name& name, const ast::tokens::CoreType type, const bool readsFrom, const bool writesTo) : mAttrib(name, type) , mAccess(readsFrom, writesTo) , mUses() , mDependencies() {} bool reads() const { return mAccess.first; } bool writes() const { return mAccess.second; } const std::string tokenname() const { return mAttrib.tokenname(); } const std::string& name() const { return mAttrib.name(); } ast::tokens::CoreType type() const { return mAttrib.type(); } const std::vector<const AccessData*>& deps() const { return mDependencies; } const std::vector<const AccessData*>& uses() const { return mUses; } bool dependson(const AccessData* data) const { for (auto& dep : mDependencies) { if (dep == data) return true; } return false; } bool affectsothers() const { for (auto& dep : mUses) { if (dep != this) return true; } return false; } private: friend AttributeRegistry; const ast::Attribute mAttrib; const std::pair<bool, bool> mAccess; std::vector<const AccessData*> mUses; // Accesses which depend on this access std::vector<const AccessData*> mDependencies; // Accesses which this access depends on }; using AccessDataVec = std::vector<AccessData>; inline static AttributeRegistry::Ptr create(const ast::Tree& tree); inline bool isReadable(const std::string& name, const ast::tokens::CoreType type) const { return this->accessPattern(name, type).first; } /// @brief Returns whether or not an access is required to be written to. /// If no access with this name has been registered, returns false /// @param name The name of the access /// @param type The type of the access inline bool isWritable(const std::string& name, const ast::tokens::CoreType type) const { return this->accessPattern(name, type).second; } inline std::pair<bool,bool> accessPattern(const std::string& name, const ast::tokens::CoreType type) const { for (const auto& data : mAccesses) { if ((type == ast::tokens::UNKNOWN || data.type() == type) && data.name() == name) { return data.mAccess; } } return std::pair<bool,bool>(false,false); } /// @brief Returns whether or not an access is registered. /// @param name The name of the access /// @param type The type of the access inline bool isRegistered(const std::string& name, const ast::tokens::CoreType type) const { return this->accessIndex(name, type) != -1; } /// @brief Returns whether or not an access is registered. /// @param name The name of the access /// @param type The type of the access inline int64_t accessIndex(const std::string& name, const ast::tokens::CoreType type) const { int64_t i = 0; for (const auto& data : mAccesses) { if (data.type() == type && data.name() == name) { return i; } ++i; } return -1; } /// @brief Returns a const reference to the vector of registered accesss inline const AccessDataVec& data() const { return mAccesses; } void print(std::ostream& os) const; private: AttributeRegistry() : mAccesses() {} /// @brief Add an access to the registry, returns an index into /// the registry for that access /// @param name The name of the access /// @param type The typename of the access /// @param writesTo Whether the access is required to be writeable /// inline void addData(const Name& name, const ast::tokens::CoreType type, const bool readsfrom, const bool writesto) { mAccesses.emplace_back(name, type, readsfrom, writesto); } AccessDataVec mAccesses; }; ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// inline AttributeRegistry::Ptr AttributeRegistry::create(const ast::Tree& tree) { AttributeRegistry::Ptr registry(new AttributeRegistry()); std::vector<std::string> read, write, all; ast::catalogueAttributeTokens(tree, &read, &write, &all); size_t idx = 0; std::unordered_map<std::string, size_t> indexmap; auto dataBuilder = [&](const std::vector<std::string>& attribs, const bool readFlag, const bool writeFlag) { std::string name, type; for (const auto& attrib : attribs) { ast::Attribute::nametypeFromToken(attrib, &name, &type); const ast::tokens::CoreType typetoken = ast::tokens::tokenFromTypeString(type); registry->addData(name, typetoken, readFlag, writeFlag); indexmap[attrib] = idx++; } }; // insert all data dataBuilder(read, true, false); dataBuilder(write, false, true); dataBuilder(all, true, true); auto depBuilder = [&](const std::vector<std::string>& attribs) { std::string name, type; for (const auto& attrib : attribs) { ast::Attribute::nametypeFromToken(attrib, &name, &type); const ast::tokens::CoreType typetoken = ast::tokens::tokenFromTypeString(type); std::vector<std::string> deps; ast::attributeDependencyTokens(tree, name, typetoken, deps); if (deps.empty()) continue; assert(indexmap.find(attrib) != indexmap.cend()); const size_t index = indexmap.at(attrib); AccessData& access = registry->mAccesses[index]; for (const std::string& dep : deps) { assert(indexmap.find(dep) != indexmap.cend()); const size_t depindex = indexmap.at(dep); access.mDependencies.emplace_back(&registry->mAccesses[depindex]); } } }; // initialize dependencies depBuilder(read); depBuilder(write); depBuilder(all); // Update usage from deps for (AccessData& access : registry->mAccesses) { for (const AccessData& next : registry->mAccesses) { // don't skip self depends as it may write to itself // i.e. @a = @a + 1; should add a self usage if (next.dependson(&access)) { access.mUses.emplace_back(&next); } } } return registry; } inline void AttributeRegistry::print(std::ostream& os) const { size_t idx = 0; for (const auto& data : mAccesses) { os << "Attribute: " << data.name() << ", type: " << ast::tokens::typeStringFromToken(data.type()) << '\n'; os << " " << "Index : " << idx << '\n'; os << std::boolalpha; os << " " << "Reads From : " << data.reads() << '\n'; os << " " << "Writes To : " << data.writes() << '\n'; os << std::noboolalpha; os << " " << "Dependencies : " << data.mDependencies.size() << '\n'; for (const auto& dep : data.mDependencies) { os << " " << "Attribute: " << dep->name() << " type: " << ast::tokens::typeStringFromToken(dep->type()) << '\n'; } os << " " << "Usage : " << data.mUses.size() << '\n'; for (const auto& dep : data.mUses) { os << " " << "Attribute: " << dep->name() << " type: " << ast::tokens::typeStringFromToken(dep->type()) << '\n'; } os << '\n'; ++idx; } } } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_TARGET_REGISTRY_HAS_BEEN_INCLUDED
9,597
C
32.915194
94
0.579139
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/compiler/CompilerOptions.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file compiler/CompilerOptions.h /// /// @authors Nick Avramoussis /// /// @brief OpenVDB AX Compiler Options /// #ifndef OPENVDB_AX_COMPILER_COMPILER_OPTIONS_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_COMPILER_OPTIONS_HAS_BEEN_INCLUDED #include <openvdb/openvdb.h> #include <openvdb/version.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { /// @brief Options that control how functions behave struct FunctionOptions { /// @brief Enable the constant folding of C bindings. Functions may use this setting /// to determine whether they are allowed to be called during code generation /// to evaluate call sites with purely constant arguments and replace the call /// with the result. /// @note This does not impact IR functions which we leave to LLVM's CF during /// IR optimization. /// @note We used to bind IR methods to corresponding C bindings, however it can be /// very easy to implement incorrectly, leading to discrepancies in the CF /// results. Fundamentally, LLVM's support for CF IR is far superior and our /// framework only supports some types of folding (see codegen/ConstantFolding.h) bool mConstantFoldCBindings = true; /// @brief When enabled, functions which have IR builder instruction definitions will /// prioritise those over any registered external calls bool mPrioritiseIR = true; /// @brief When enabled, the function registry is only populated on a function visit. /// At the end of code generation, only functions which have been instantiated /// will exist in the function map. bool mLazyFunctions = true; }; /// @brief Settings which control how a Compiler class object behaves struct CompilerOptions { /// @brief Controls the llvm compiler optimization level enum class OptLevel { NONE, // Do not run any optimization passes O0, // Optimization level 0. Similar to clang -O0 O1, // Optimization level 1. Similar to clang -O1 O2, // Optimization level 2. Similar to clang -O2 Os, // Like -O2 with extra optimizations for size. Similar to clang -Os Oz, // Like -Os but reduces code size further. Similar to clang -Oz O3 // Optimization level 3. Similar to clang -O3 }; OptLevel mOptLevel = OptLevel::O3; /// @brief If this flag is true, the generated llvm module will be verified when compilation /// occurs, resulting in an exception being thrown if it is not valid bool mVerify = true; /// @brief Options for the function registry FunctionOptions mFunctionOptions = FunctionOptions(); }; } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_FUNCTION_REGISTRY_OPTIONS_HAS_BEEN_INCLUDED
2,989
C
38.342105
96
0.694881
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/PrintTree.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/PrintTree.cc #include "AST.h" #include "PrintTree.h" #include "Tokens.h" #include "Visitor.h" #include <ostream> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { struct PrintVisitor : public ast::Visitor<PrintVisitor> { PrintVisitor(std::ostream& os, const bool numberStatements = true, const char* indent = " ") : mOs(os) , mLevel(0) , mStatementNumber(numberStatements ? 0 : -1) , mIndent(indent) {} ~PrintVisitor() = default; using ast::Visitor<PrintVisitor>::traverse; using ast::Visitor<PrintVisitor>::visit; inline bool postOrderNodes() const { return false; } inline void indent() { for (int i(0); i < mLevel; ++i) mOs << mIndent; } bool traverse(NodeType<ast::StatementList>* stmntl) { this->visit(stmntl); const size_t children = stmntl->children(); ++mLevel; if (children == 0) { indent(); mOs << "<empty>\n"; } else { for (size_t i = 0; i < children; ++i) { indent(); if (mStatementNumber >= 0) { mOs << '[' << mStatementNumber++ << "] "; } this->derived().traverse(stmntl->child(i)); mOs << '\n'; } } --mLevel; return true; } bool traverse(NodeType<ast::Block>* block) { indent(); this->visit(block); const size_t children = block->children(); ++mLevel; if (children == 0) { indent(); mOs << "<empty>\n"; } else { for (size_t i = 0; i < children; ++i) { indent(); if (mStatementNumber >= 0) { mOs << '[' << mStatementNumber++ << "] "; } this->derived().traverse(block->child(i)); mOs << '\n'; } } --mLevel; return true; } bool traverse(NodeType<ast::CommaOperator>* comma) { this->visit(comma); const size_t children = comma->children(); ++mLevel; if (children == 0) { indent(); mOs << "<empty>\n"; } else { for (size_t i = 0; i < children; ++i) { indent(); this->derived().traverse(comma->child(i)); } } --mLevel; return true; } bool traverse(NodeType<ast::ConditionalStatement>* cond) { this->visit(cond); ++mLevel; indent(); mOs << "condition:\n"; ++mLevel; indent(); this->traverse(cond->condition()); --mLevel; indent(); mOs << "branch [true]:\n"; this->traverse(cond->trueBranch()); if (cond->hasFalse()) { indent(); mOs << "branch [false]:\n"; this->traverse(cond->falseBranch()); } --mLevel; return true; } bool traverse(NodeType<ast::TernaryOperator>* tern) { this->visit(tern); ++mLevel; indent(); mOs << "condition:\n"; ++mLevel; indent(); this->traverse(tern->condition()); --mLevel; indent(); mOs << "true:\n"; if (tern->hasTrue()) { ++mLevel; indent(); this->traverse(tern->trueBranch()); --mLevel; } indent(); mOs << "false:\n"; ++mLevel; indent(); this->traverse(tern->falseBranch()); --mLevel; --mLevel; return true; } bool traverse(NodeType<ast::Loop>* loop) { this->visit(loop); ++mLevel; if (loop->hasInit()) { indent(); mOs << "init:\n"; ++mLevel; indent(); this->traverse(loop->initial()); --mLevel; } indent(); mOs << "conditional:\n"; ++mLevel; indent(); this->traverse(loop->condition()); --mLevel; if (loop->hasIter()) { indent(); mOs << "iterator:\n"; ++mLevel; indent(); this->traverse(loop->iteration()); --mLevel; } indent(); mOs << "body:\n"; this->traverse(loop->body()); --mLevel; return true; } bool traverse(NodeType<ast::AssignExpression>* asgn) { this->visit(asgn); ++mLevel; indent(); this->traverse(asgn->lhs()); indent(); this->traverse(asgn->rhs()); --mLevel; return true; } bool traverse(NodeType<ast::DeclareLocal>* asgn) { this->visit(asgn); ++mLevel; indent(); this->traverse(asgn->local()); if(asgn->hasInit()) { indent(); mOs << "init:\n"; ++mLevel; indent(); this->traverse(asgn->init()); --mLevel; } --mLevel; return true; } bool traverse(NodeType<ast::Crement>* crmt) { this->visit(crmt); ++mLevel; indent(); this->traverse(crmt->expression()); --mLevel; return true; } bool traverse(NodeType<ast::UnaryOperator>* unry) { this->visit(unry); ++mLevel; indent(); this->traverse(unry->expression()); --mLevel; return true; } bool traverse(NodeType<ast::BinaryOperator>* bin) { this->visit(bin); ++mLevel; indent(); this->traverse(bin->lhs()); indent(); this->traverse(bin->rhs()); --mLevel; return true; } bool traverse(NodeType<ast::Cast>* cast) { this->visit(cast); ++mLevel; indent(); this->traverse(cast->expression()); --mLevel; return true; } bool traverse(NodeType<ast::FunctionCall>* call) { this->visit(call); const size_t children = call->children(); ++mLevel; if (children == 0) { indent(); mOs << "<empty>\n"; } else { for (size_t i = 0; i < children; ++i) { indent(); this->derived().traverse(call->child(i)); } } --mLevel; return true; } bool traverse(NodeType<ast::ArrayPack>* pack) { this->visit(pack); const size_t children = pack->children(); ++mLevel; if (children == 0) { indent(); mOs << "<empty>\n"; } else { for (size_t i = 0; i < children; ++i) { indent(); this->derived().traverse(pack->child(i)); } } --mLevel; return true; } bool traverse(NodeType<ast::ArrayUnpack>* pack) { this->visit(pack); ++mLevel; indent(); mOs << "expression: "; this->traverse(pack->expression()); indent(); mOs << "component(s) : "; this->traverse(pack->component0()); this->traverse(pack->component1()); --mLevel; return true; } bool visit(const ast::StatementList* node); bool visit(const ast::Block* node); bool visit(const ast::ConditionalStatement* node); bool visit(const ast::Loop* node); bool visit(const ast::Keyword* node); bool visit(const ast::AssignExpression* node); bool visit(const ast::Crement* node); bool visit(const ast::CommaOperator* node); bool visit(const ast::UnaryOperator* node); bool visit(const ast::BinaryOperator* node); bool visit(const ast::TernaryOperator* node); bool visit(const ast::Cast* node); bool visit(const ast::FunctionCall* node); bool visit(const ast::Attribute* node); bool visit(const ast::ExternalVariable* node); bool visit(const ast::DeclareLocal* node); bool visit(const ast::Local* node); bool visit(const ast::ArrayUnpack* node); bool visit(const ast::ArrayPack* node); bool visit(const ast::Value<bool>* node) { return this->visitValue(node); } bool visit(const ast::Value<int16_t>* node) { return this->visitValue(node); } bool visit(const ast::Value<int32_t>* node) { return this->visitValue(node); } bool visit(const ast::Value<int64_t>* node) { return this->visitValue(node); } bool visit(const ast::Value<float>* node) { return this->visitValue(node); } bool visit(const ast::Value<double>* node) { return this->visitValue(node); } bool visit(const ast::Value<std::string>* node) { return this->visitValue(node); } protected: template <typename T> bool visitValue(const ast::Value<T>* node); private: std::ostream& mOs; int mLevel; int64_t mStatementNumber; const char* mIndent; }; bool PrintVisitor::visit(const ast::StatementList* node) { mOs << node->nodename() << ": " << node->size() << " statement(s)" << '\n'; return true; } bool PrintVisitor::visit(const ast::Block* node) { mOs << node->nodename() << ": " << node->size() << " statement(s)" << '\n'; return true; } bool PrintVisitor::visit(const ast::ConditionalStatement* node) { mOs << node->nodename() << ": " << (node->hasFalse() ? "two branches " : "one branch") << '\n'; return true; } bool PrintVisitor::visit(const ast::AssignExpression* node) { mOs << node->nodename() << ": " << tokens::operatorNameFromToken(node->operation()); if (node->isCompound()) mOs << '='; mOs << '\n'; return true; } bool PrintVisitor::visit(const ast::Loop* node) { mOs << tokens::loopNameFromToken(node->loopType()) <<" "<< node->nodename() << ": " << '\n'; return true; } bool PrintVisitor::visit(const ast::Keyword* node) { mOs << node->nodename() << ": " << tokens::keywordNameFromToken(node->keyword()) << '\n'; return true; } bool PrintVisitor::visit(const ast::Crement* node) { mOs << node->nodename() << ':'; if (node->post()) mOs << " post-"; else mOs << " pre-"; if (node->increment()) mOs << "increment "; else mOs << "decrement "; mOs << '\n'; return true; } bool PrintVisitor::visit(const ast::CommaOperator* node) { mOs << node->nodename() << ": " << node->size() << " element(s)" << '\n'; return true; } bool PrintVisitor::visit(const ast::UnaryOperator* node) { mOs << node->nodename() << ": " << tokens::operatorNameFromToken(node->operation()) << '\n'; return true; } bool PrintVisitor::visit(const ast::BinaryOperator* node) { mOs << node->nodename() << ": " << tokens::operatorNameFromToken(node->operation()) << '\n'; return true; } bool PrintVisitor::visit(const ast::TernaryOperator* node) { mOs << node->nodename() << ":\n"; return true; } bool PrintVisitor::visit(const ast::Cast* node) { mOs << node->nodename() << ": " << tokens::typeStringFromToken(node->type()) << '\n'; return true; } bool PrintVisitor::visit(const ast::FunctionCall* node) { mOs << node->nodename() << ": " << node->name() << '\n'; return true; } bool PrintVisitor::visit(const ast::Attribute* node) { mOs << node->nodename() << ": " << node->symbolseparator() << '(' << node->typestr() << (node->inferred() ? " - inferred": "") << ") " << node->name() << '\n'; return true; } bool PrintVisitor::visit(const ast::DeclareLocal* node) { mOs << node->nodename() << ": "<< node->typestr() << '\n'; return true; } bool PrintVisitor::visit(const ast::Local* node) { mOs << node->nodename() << ' ' << node->name() << '\n'; return true; } bool PrintVisitor::visit(const ast::ArrayUnpack* node) { mOs << node->nodename() << '\n'; return true; } bool PrintVisitor::visit(const ast::ArrayPack* node) { mOs << node->nodename() << ": " << node->children() << " element(s)" << '\n'; return true; } bool PrintVisitor::visit(const ast::ExternalVariable* node) { mOs << node->nodename() << ": " << node->symbolseparator() << '(' << node->typestr() << ") " << node->name() << '\n'; return true; } template <typename T> bool PrintVisitor::visitValue(const ast::Value<T>* node) { mOs << node->nodename() << ": " << node->value() << '\n'; return true; } //////////////////////////////////////////////////////////////////////////////// void print(const ast::Node& node, const bool numberStatements, std::ostream& os, const char* indent) { PrintVisitor visitor(os, numberStatements, indent); visitor.traverse(&node); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// struct ReprintVisitor : public ast::Visitor<ReprintVisitor> { ReprintVisitor(std::ostream& os, const char* indent = " ") : mOs(os) , mLevel(0) , mIndent(indent) {} ~ReprintVisitor() = default; using ast::Visitor<ReprintVisitor>::traverse; using ast::Visitor<ReprintVisitor>::visit; inline bool postOrderNodes() const { return false; } inline void indent() { for (int i = 0; i < mLevel; ++i) mOs << mIndent; } bool traverse(NodeType<ast::Block>* block) { const size_t children = block->children(); indent(); mOs << '{' << '\n'; ++mLevel; for (size_t i = 0; i < children; ++i) { indent(); this->derived().traverse(block->child(i)); const auto type = block->child(i)->nodetype(); if (type != ast::Node::ConditionalStatementNode && type != ast::Node::LoopNode) { mOs << ';' << '\n'; } } --mLevel; indent(); mOs << '}' << '\n'; return true; } bool traverse(NodeType<ast::StatementList>* stmtl) { const size_t children = stmtl->children(); if (children == 0) return true; if (children == 1) { this->derived().traverse(stmtl->child(0)); mOs << ';'; return true; } // multiple statments if (stmtl->child(0)->nodetype() == ast::Node::DeclareLocalNode) { // it's a declaration list, manually handle the child nodes. // This is to handle declarations within loop inits such as // "for (int a = 0, b = 1;;)". Without this, it would be // reprinted as "for (int a=0; int b=1; ;;)" // visit the first child completely this->derived().traverse(stmtl->child(0)); for (size_t i = 1; i < children; ++i) { // all child statements should be declare locals assert(stmtl->child(i)->nodetype() == ast::Node::DeclareLocalNode); mOs << ", "; this->derived().traverse(stmtl->child(i)->child(0)); // local auto* init = stmtl->child(i)->child(1); // init if (init) { mOs << " = "; this->derived().traverse(init); } } return true; } // otherwise traverse as normal for (size_t i = 0; i < children; ++i) { this->derived().traverse(stmtl->child(i)); if (i != children-1) mOs << ';' << ' '; } return true; } bool traverse(NodeType<ast::CommaOperator>* exprl) { mOs << '('; const size_t children = exprl->children(); for (size_t i = 0; i < children; ++i) { this->derived().traverse(exprl->child(i)); if (i != children-1) mOs << ',' << ' '; } mOs << ')'; return true; } bool traverse(NodeType<ast::ConditionalStatement>* cond) { mOs << "if ("; this->traverse(cond->condition()); mOs << ")\n"; this->traverse(cond->trueBranch()); if (cond->hasFalse()) { indent(); mOs << "else\n"; this->traverse(cond->falseBranch()); } return true; } bool traverse(NodeType<ast::Loop>* loop) { const ast::tokens::LoopToken loopType = loop->loopType(); if (loopType == ast::tokens::LoopToken::FOR) { mOs << "for ("; if (loop->hasInit()) this->traverse(loop->initial()); mOs << "; "; this->traverse(loop->condition()); mOs << "; "; if (loop->hasIter()) this->traverse(loop->iteration()); mOs << ")\n"; this->traverse(loop->body()); } else if (loopType == ast::tokens::LoopToken::DO) { mOs << "do\n"; this->traverse(loop->body()); indent(); mOs << "while ("; this->traverse(loop->condition()); mOs << ")\n"; } else { mOs << "while ("; this->traverse(loop->condition()); mOs << ")\n"; this->traverse(loop->body()); } return true; } bool traverse(NodeType<ast::AssignExpression>* asgn) { this->traverse(asgn->lhs()); this->visit(asgn); this->traverse(asgn->rhs()); return true; } bool traverse(NodeType<ast::DeclareLocal>* decl) { this->visit(decl); this->visit(decl->local()); if (decl->hasInit()) { mOs <<" = "; this->traverse(decl->init()); } return true; } bool traverse(NodeType<ast::Crement>* crmt) { if (crmt->pre()) this->visit(crmt); this->traverse(crmt->expression()); if (crmt->post()) this->visit(crmt); return true; } bool traverse(NodeType<ast::UnaryOperator>* unry) { this->visit(unry); this->traverse(unry->expression()); return true; } bool traverse(NodeType<ast::BinaryOperator>* bin) { // The AST currently doesn't store what expressions were encapsulated // by parenthesis and instead infers precedences from the token order // set out in the parser. This means that traversal determines precedence. // Unfortunately, statements like "a+b+c" and "a+(b+c)" both get re-printed // as "a+b+c". For now, every binary expression is encapsulated to // ensure the operation order is preserved, resulting in (a+(b+c)) for // the above example. mOs << '('; this->traverse(bin->lhs()); this->visit(bin); this->traverse(bin->rhs()); mOs << ')'; return true; } bool traverse(NodeType<ast::TernaryOperator>* tern) { this->traverse(tern->condition()); mOs << " ?"; if (tern->hasTrue()) { mOs << ' '; this->traverse(tern->trueBranch()); mOs << ' '; } mOs << ": "; this->traverse(tern->falseBranch()); return true; } bool traverse(NodeType<ast::Cast>* cast) { this->visit(cast); mOs << '('; this->traverse(cast->expression()); mOs << ')'; return true; } bool traverse(NodeType<ast::FunctionCall>* call) { this->visit(call); mOs << '('; const size_t children = call->children(); for (size_t i = 0; i < children; ++i) { this->derived().traverse(call->child(i)); if (i != children-1) mOs << ',' << ' '; } mOs << ')'; return true; } bool traverse(NodeType<ast::ArrayPack>* pack) { mOs << '{'; const size_t children = pack->children(); for (size_t i = 0; i < children; ++i) { this->derived().traverse(pack->child(i)); if (i != children-1) mOs << ',' << ' '; } mOs << '}'; return true; } bool traverse(NodeType<ast::ArrayUnpack>* pack) { this->traverse(pack->expression()); mOs << '['; this->traverse(pack->component0()); if (pack->component1()) { mOs << ',' << ' '; this->traverse(pack->component1()); } mOs << ']'; return true; } bool visit(const ast::AssignExpression* node); bool visit(const ast::Crement* node); bool visit(const ast::UnaryOperator* node); bool visit(const ast::BinaryOperator* node); bool visit(const ast::Cast* node); bool visit(const ast::FunctionCall* node); bool visit(const ast::Attribute* node); bool visit(const ast::ExternalVariable* node); bool visit(const ast::DeclareLocal* node); bool visit(const ast::Local* node); bool visit(const ast::Keyword* node); bool visit(const ast::Value<bool>* node) { return this->visitValue(node); } bool visit(const ast::Value<int16_t>* node) { return this->visitValue(node); } bool visit(const ast::Value<int32_t>* node) { return this->visitValue(node); } bool visit(const ast::Value<int64_t>* node) { return this->visitValue(node); } bool visit(const ast::Value<float>* node) { return this->visitValue(node); } bool visit(const ast::Value<double>* node) { return this->visitValue(node); } bool visit(const ast::Value<std::string>* node) { return this->visitValue(node); } protected: template <typename T> bool visitValue(const ast::Value<T>* node); private: std::ostream& mOs; int mLevel; const char* mIndent; }; bool ReprintVisitor::visit(const ast::AssignExpression* node) { mOs << ' ' << tokens::operatorNameFromToken(node->operation()); if (node->isCompound()) mOs << '='; mOs << ' '; return true; } bool ReprintVisitor::visit(const ast::Crement* node) { if (node->increment()) mOs << "++"; if (node->decrement()) mOs << "--"; return true; } bool ReprintVisitor::visit(const ast::UnaryOperator* node) { mOs << tokens::operatorNameFromToken(node->operation()); return true; } bool ReprintVisitor::visit(const ast::BinaryOperator* node) { mOs << ' ' << tokens::operatorNameFromToken(node->operation()) << ' '; return true; } bool ReprintVisitor::visit(const ast::Cast* node) { mOs << node->typestr(); return true; } bool ReprintVisitor::visit(const ast::FunctionCall* node) { mOs << node->name(); return true; } bool ReprintVisitor::visit(const ast::Attribute* node) { mOs << node->typestr() << node->symbolseparator() << node->name(); return true; } bool ReprintVisitor::visit(const ast::DeclareLocal* node) { mOs << node->typestr() << " "; return true; } bool ReprintVisitor::visit(const ast::Local* node) { mOs << node->name(); return true; } bool ReprintVisitor::visit(const ast::Keyword* node) { mOs << tokens::keywordNameFromToken(node->keyword()); return true; } bool ReprintVisitor::visit(const ast::ExternalVariable* node) { mOs << node->typestr() << node->symbolseparator() << node->name(); return true; } template <typename T> bool ReprintVisitor::visitValue(const ast::Value<T>* node) { if (std::is_same<T, bool>::value) mOs << std::boolalpha; if (std::is_same<T, std::string>::value) mOs << '"'; mOs << node->value(); if (std::is_same<T, bool>::value) mOs << std::noboolalpha; if (std::is_same<T, std::string>::value) mOs << '"'; if (std::is_same<T, int16_t>::value) mOs << 's'; if (std::is_same<T, int64_t>::value) mOs << 'l'; if (std::is_same<T, float>::value) mOs << 'f'; return true; } //////////////////////////////////////////////////////////////////////////////// void reprint(const ast::Node& node, std::ostream& os, const char* indent) { ReprintVisitor visitor(os, indent); visitor.traverse(&node); } } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
24,244
C++
25.81969
99
0.5139
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/PrintTree.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/PrintTree.h /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief Various tools which traverse an AX AST and report information /// back to a std::ostream. /// #ifndef OPENVDB_AX_AST_PRINT_TREE_HAS_BEEN_INCLUDED #define OPENVDB_AX_AST_PRINT_TREE_HAS_BEEN_INCLUDED #include <openvdb/version.h> #include <ostream> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { struct Node; /// @brief Writes a descriptive printout of a Node hierarchy into a target /// stream /// @param node Node to print /// @param numberStatements Whether to number the line statements /// @param os Stream to write into /// @param indent The indent to print on each child traversal void print(const ast::Node& node, const bool numberStatements = true, std::ostream& os = std::cout, const char* indent = " "); /// @brief Using the provided AST, print corresponding AX code which /// may have been used to create it. /// @note The result is not guaranteed to be exactly equal to the /// code that was original parsed. A few potential key differences worth /// mentioning include whitespace matching, component indexing and inferred /// attribute types. /// @param node Node to print /// @param os Stream to write into /// @param indent The indent to print on each child traversal void reprint(const ast::Node& node, std::ostream& os = std::cout, const char* indent = " "); } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_AST_PRINT_TREE_HAS_BEEN_INCLUDED
1,753
C
28.233333
82
0.701084
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/Parse.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "Parse.h" #include "../Exceptions.h" // if OPENVDB_AX_REGENERATE_GRAMMAR is defined, we've re-generated the // grammar - include path should be set up to pull in from the temp dir // @note We need to include this to get access to axlloc. Should look to // re-work this so we don't have to (would require a reentrant parser) #ifdef OPENVDB_AX_REGENERATE_GRAMMAR #include "axparser.h" #else #include "../grammar/generated/axparser.h" #endif #include <tbb/mutex.h> #include <string> #include <memory> namespace { // Declare this at file scope to ensure thread-safe initialization. tbb::mutex sInitMutex; } openvdb::ax::Logger* axlog = nullptr; using YY_BUFFER_STATE = struct yy_buffer_state*; extern int axparse(openvdb::ax::ast::Tree**); extern YY_BUFFER_STATE ax_scan_string(const char * str); extern void ax_delete_buffer(YY_BUFFER_STATE buffer); extern void axerror (openvdb::ax::ast::Tree**, char const *s) { //@todo: add check for memory exhaustion assert(axlog); axlog->error(/*starts with 'syntax error, '*/s + 14, {axlloc.first_line, axlloc.first_column}); } openvdb::ax::ast::Tree::ConstPtr openvdb::ax::ast::parse(const char* code, openvdb::ax::Logger& logger) { tbb::mutex::scoped_lock lock(sInitMutex); axlog = &logger; // for lexer errs logger.setSourceCode(code); // reset all locations axlloc.first_line = axlloc.last_line = 1; axlloc.first_column = axlloc.last_column = 1; YY_BUFFER_STATE buffer = ax_scan_string(code); openvdb::ax::ast::Tree* tree(nullptr); axparse(&tree); axlog = nullptr; openvdb::ax::ast::Tree::ConstPtr ptr(const_cast<const openvdb::ax::ast::Tree*>(tree)); ax_delete_buffer(buffer); logger.setSourceTree(ptr); return ptr; } openvdb::ax::ast::Tree::Ptr openvdb::ax::ast::parse(const char* code) { openvdb::ax::Logger logger( [](const std::string& error) { OPENVDB_THROW(openvdb::AXSyntaxError, error); }); openvdb::ax::ast::Tree::ConstPtr constTree = openvdb::ax::ast::parse(code, logger); return std::const_pointer_cast<openvdb::ax::ast::Tree>(constTree); }
2,223
C++
27.883117
90
0.68466
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/Visitor.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/Visitor.h /// /// @authors Nick Avramoussis /// /// @brief Contains the AX AST Node Visitor, providing default and /// customizable traversal and visitation methods on a AST hierarchy. /// Using the visitor pattern is the recommended way to implement /// custom operations on AST nodes. /// #ifndef OPENVDB_AX_AST_VISITOR_HAS_BEEN_INCLUDED #define OPENVDB_AX_AST_VISITOR_HAS_BEEN_INCLUDED #include "AST.h" #include "Tokens.h" #include <openvdb/version.h> #include <type_traits> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { /// @brief The Visitor class uses the Curiously Recursive Template Pattern /// (CRTP) to provide a customizable interface intended to be used by /// clients wishing to perform custom operations over an AX Abstract /// Syntax Tree (AST). By default the Visitor implements simple /// traversal of all nodes, ensuring that each node on a well formed /// AST is visited at least once. By deriving from the Visitor, users /// are able to customize this default behavior and further manually /// override specific node behavior to their needs. The function /// options at the top of visitor can be overridden using CRTP to /// control the prior default behavior, with the ability to override /// the traverse() and visit() methods for the latter more granular /// control. /// /// @details To commence a full visit of an AST, begin by calling traverse() on /// a Node pointer. A visit is defined as one of the visit() methods /// being called and accepting a Node type. Each node is is guaranteed /// to be visited exactly once at its lowest concrete derived type. /// Node inheritance hierarchies can also be visited (disable by /// default, see Visitor::visitNodeHierarchies) The traverse() methods /// define how each AST node accesses its children. The default /// implementation is for each node to traverses its child pointers in /// the order returned by the derived Node::child() method /// (see Visitor::reverseChildVisits). You'll typically only require /// overriding of the visit() methods for achieving most goals, however /// you can utilize the traverse methods if you find that you require /// more control over how the node hierarchy is accessed. The default /// visit order is post order, where by nodes traverse and visit their /// children first (see Visitor::postOrderNodes). Each visit method /// returns a boolean value which, if false, allows for early /// termination of the traversal. In the below example, we show a /// Visitor capable of visiting every Local node type exactly once, /// terminating if the Local variable is called "var". /// /// @par Example: /// @code /// struct LocalVisitor : public Visitor<LocalVisitor> /// { /// // Bring in all base methods to avoid hiding /// using ast::Visitor<LocalVisitor>::traverse; /// using ast::Visitor<LocalVisitor>::visit; /// /// // override the visit for Local AST nodes /// inline bool visit(const Local* node) { /// if (!node) return true; /// if (node->name() == "var") return false; /// return true; /// } /// }; /// /// LocalVisitor visitor; /// visitor.traverse(&tree); /// @endcode /// /// @note The second template argument, ConstVisit, allows you to perform /// non-const traversals over the AST. In this case, the visit and /// traversal function signatures change to non-const pointers. /// @note This design is heavily influenced by Clang's RecursiveVisitor. /// /// @tparam Derived The derived visitor to template on the base visitor, /// using CRTP /// @tparam ConstVisit Whether to visit const or non-const versions of the AST /// nodes. Note that this value changes the class function /// signatures. template <typename Derived, bool ConstVisit=true> struct Visitor { /// @brief Templated conditional which resolves to a const NodeT if /// ConstVisit is true, or a non-const NodeT if ConstVisit is false template <typename NodeT> using NodeType = typename std::conditional<ConstVisit, const NodeT, NodeT>::type; /// @brief Accesses the derived class by static casting the current object. /// Assumes use of the Curiously Recursive Template Pattern (CRTP). inline Derived& derived() { return *static_cast<Derived*>(this); } /// @name Options /// @{ /// @brief Default behavior option. If true, this results in post-order /// traversal, where node children are traversed and visited before /// their parent node. If false, this results in pre-order /// traversal, where by the current node is visited before the /// node's children. /// @details Post-order traversal (for each node): /// 1. Traverse all children. /// 2. Visit the current node. /// Pre-order traversal (for each node): /// 1. Visit the current node. /// 2. Traverse all children. inline bool postOrderNodes() const { return true; } /// @brief Default behavior option. Reverses the traversal order of child /// nodes. If true, child nodes are accessed from last to first /// index .i.e. Node::children() -> 0. If false, child nodes are /// accessed from first to last .i.e. 0 -> Node::children() inline bool reverseChildVisits() const { return false; } /// @brief Default behavior option. Controls whether nodes visit themselves /// at each stage of their class hierarchy. If true, nodes perform /// multiple visits on their potentially abstract base classes. If /// false, only the concrete derived types are visited. /// @details When disabled, abstract node visitor methods are never accessed /// directly through the default Visitor implementation. These /// types include Node, Statement, Expression, etc AST nodes. /// If true, for each linearly inherited AST node, a visit is /// performed on the entire hierarchy. For example, for a Local AST /// node which derives from Variable -> Expression -> Statement -> /// Node, 5 visits will be performed at each level. inline bool visitNodeHierarchies() const { return false; } /// @brief Default behavior option. Reverses the traversal order of node /// hierarchies. If true, hierarchical visits start at the very top /// of their inheritance structure (always a Node AST node) and /// visit downwards until the lowest derived concrete node is /// reached. If false, hierarchical visits start at the lowest /// derived concrete node and visit upwards until the very top of /// their inheritance structure (always a Node AST node) is reached. /// @note Has no effect if visitNodeHierarchies() is false inline bool reverseHierarchyVisits() const { return false; } /// @} /// @name Traversals /// @{ /// @brief Default traversals for a given concrete AST node type /// @return True if traversal should continue, false to terminate bool traverse(NodeType<ast::Tree>* tree) { return this->defaultTraversal<ast::Tree>(tree); } bool traverse(NodeType<ast::StatementList>* cond) { return this->defaultTraversal<ast::StatementList>(cond); } bool traverse(NodeType<ast::Block>* block) { return this->defaultTraversal<ast::Block>(block); } bool traverse(NodeType<ast::CommaOperator>* comma) { return this->defaultTraversal<ast::CommaOperator>(comma); } bool traverse(NodeType<ast::Loop>* loop) { return this->defaultTraversal<ast::Loop>(loop); } bool traverse(NodeType<ast::Keyword>* keyw) { return this->defaultTraversal<ast::Keyword>(keyw); } bool traverse(NodeType<ast::ConditionalStatement>* cond) { return this->defaultTraversal<ast::ConditionalStatement>(cond); } bool traverse(NodeType<ast::AssignExpression>* asgn) { return this->defaultTraversal<ast::AssignExpression>(asgn); } bool traverse(NodeType<ast::Crement>* crmt) { return this->defaultTraversal<ast::Crement>(crmt); } bool traverse(NodeType<ast::UnaryOperator>* unry) { return this->defaultTraversal<ast::UnaryOperator>(unry); } bool traverse(NodeType<ast::BinaryOperator>* bin) { return this->defaultTraversal<ast::BinaryOperator>(bin); } bool traverse(NodeType<ast::TernaryOperator>* tern) { return this->defaultTraversal<ast::TernaryOperator>(tern); } bool traverse(NodeType<ast::Cast>* cast) { return this->defaultTraversal<ast::Cast>(cast); } bool traverse(NodeType<ast::FunctionCall>* call) { return this->defaultTraversal<ast::FunctionCall>(call); } bool traverse(NodeType<ast::Attribute>* attr) { return this->defaultTraversal<ast::Attribute>(attr); } bool traverse(NodeType<ast::ExternalVariable>* ext) { return this->defaultTraversal<ast::ExternalVariable>(ext); } bool traverse(NodeType<ast::DeclareLocal>* decl) { return this->defaultTraversal<ast::DeclareLocal>(decl); } bool traverse(NodeType<ast::Local>* loc) { return this->defaultTraversal<ast::Local>(loc); } bool traverse(NodeType<ast::ArrayPack>* pack) { return this->defaultTraversal<ast::ArrayPack>(pack); } bool traverse(NodeType<ast::ArrayUnpack>* pack) { return this->defaultTraversal<ast::ArrayUnpack>(pack); } bool traverse(NodeType<ast::Value<bool>>* val) { return this->defaultTraversal<ast::Value<bool>>(val); } bool traverse(NodeType<ast::Value<int16_t>>* val) { return this->defaultTraversal<ast::Value<int16_t>>(val); } bool traverse(NodeType<ast::Value<int32_t>>* val) { return this->defaultTraversal<ast::Value<int32_t>>(val); } bool traverse(NodeType<ast::Value<int64_t>>* val) { return this->defaultTraversal<ast::Value<int64_t>>(val); } bool traverse(NodeType<ast::Value<float>>* val) { return this->defaultTraversal<ast::Value<float>>(val); } bool traverse(NodeType<ast::Value<double>>* val) { return this->defaultTraversal<ast::Value<double>>(val); } bool traverse(NodeType<ast::Value<std::string>>* val) { return this->defaultTraversal<ast::Value<std::string>>(val); } /// @brief The default traversal method which is hit for all child /// traversals. The correct derived traversal scheme is selected by /// using the node enumerated type. /// @note Only handles traversal on concrete node types. bool traverse(NodeType<ast::Node>* node) { if (!node) return true; switch (node->nodetype()) { case Node::TreeNode : return this->derived().traverse(static_cast<NodeType<ast::Tree>*>(node)); case Node::StatementListNode : return this->derived().traverse(static_cast<NodeType<ast::StatementList>*>(node)); case Node::BlockNode : return this->derived().traverse(static_cast<NodeType<ast::Block>*>(node)); case Node::CommaOperatorNode : return this->derived().traverse(static_cast<NodeType<ast::CommaOperator>*>(node)); case Node::LoopNode : return this->derived().traverse(static_cast<NodeType<ast::Loop>*>(node)); case Node::KeywordNode : return this->derived().traverse(static_cast<NodeType<ast::Keyword>*>(node)); case Node::ConditionalStatementNode : return this->derived().traverse(static_cast<NodeType<ast::ConditionalStatement>*>(node)); case Node::AssignExpressionNode : return this->derived().traverse(static_cast<NodeType<ast::AssignExpression>*>(node)); case Node::CrementNode : return this->derived().traverse(static_cast<NodeType<ast::Crement>*>(node)); case Node::UnaryOperatorNode : return this->derived().traverse(static_cast<NodeType<ast::UnaryOperator>*>(node)); case Node::BinaryOperatorNode : return this->derived().traverse(static_cast<NodeType<ast::BinaryOperator>*>(node)); case Node::TernaryOperatorNode : return this->derived().traverse(static_cast<NodeType<ast::TernaryOperator>*>(node)); case Node::CastNode : return this->derived().traverse(static_cast<NodeType<ast::Cast>*>(node)); case Node::AttributeNode : return this->derived().traverse(static_cast<NodeType<ast::Attribute>*>(node)); case Node::FunctionCallNode : return this->derived().traverse(static_cast<NodeType<ast::FunctionCall>*>(node)); case Node::ExternalVariableNode : return this->derived().traverse(static_cast<NodeType<ast::ExternalVariable>*>(node)); case Node::DeclareLocalNode : return this->derived().traverse(static_cast<NodeType<ast::DeclareLocal>*>(node)); case Node::ArrayPackNode : return this->derived().traverse(static_cast<NodeType<ast::ArrayPack>*>(node)); case Node::ArrayUnpackNode : return this->derived().traverse(static_cast<NodeType<ast::ArrayUnpack>*>(node)); case Node::LocalNode : return this->derived().traverse(static_cast<NodeType<ast::Local>*>(node)); case Node::ValueBoolNode : return this->derived().traverse(static_cast<NodeType<ast::Value<bool>>*>(node)); case Node::ValueInt16Node : return this->derived().traverse(static_cast<NodeType<ast::Value<int16_t>>*>(node)); case Node::ValueInt32Node : return this->derived().traverse(static_cast<NodeType<ast::Value<int32_t>>*>(node)); case Node::ValueInt64Node : return this->derived().traverse(static_cast<NodeType<ast::Value<int64_t>>*>(node)); case Node::ValueFloatNode : return this->derived().traverse(static_cast<NodeType<ast::Value<float>>*>(node)); case Node::ValueDoubleNode : return this->derived().traverse(static_cast<NodeType<ast::Value<double>>*>(node)); case Node::ValueStrNode : return this->derived().traverse(static_cast<NodeType<ast::Value<std::string>>*>(node)); default : return true; } } /// @} /// @name Visits /// @{ /// @brief Visits for abstract (pure-virtual) Node types. /// @note These are only hit through the default behavior if /// Visitor::visitNodeHierarchies is enabled. /// @return True if traversal should continue, false to terminate inline bool visit(NodeType<ast::Node>*) { return true; } inline bool visit(NodeType<ast::Statement>*) { return true; } inline bool visit(NodeType<ast::Expression>*) { return true; } inline bool visit(NodeType<ast::Variable>*) { return true; } inline bool visit(NodeType<ast::ValueBase>*) { return true; } /// @brief Visits for concrete Node types. /// @return True if traversal should continue, false to terminate inline bool visit(NodeType<ast::Tree>*) { return true; } inline bool visit(NodeType<ast::StatementList>*) { return true; } inline bool visit(NodeType<ast::Block>*) { return true; } inline bool visit(NodeType<ast::CommaOperator>*) { return true; } inline bool visit(NodeType<ast::Loop>*) { return true; } inline bool visit(NodeType<ast::Keyword>*) { return true; } inline bool visit(NodeType<ast::ConditionalStatement>*) { return true; } inline bool visit(NodeType<ast::AssignExpression>*) { return true; } inline bool visit(NodeType<ast::Crement>*) { return true; } inline bool visit(NodeType<ast::UnaryOperator>*) { return true; } inline bool visit(NodeType<ast::BinaryOperator>*) { return true; } inline bool visit(NodeType<ast::TernaryOperator>*) { return true; } inline bool visit(NodeType<ast::Cast>*) { return true; } inline bool visit(NodeType<ast::FunctionCall>*) { return true; } inline bool visit(NodeType<ast::Attribute>*) { return true; } inline bool visit(NodeType<ast::ExternalVariable>*) { return true; } inline bool visit(NodeType<ast::DeclareLocal>*) { return true; } inline bool visit(NodeType<ast::Local>*) { return true; } inline bool visit(NodeType<ast::ArrayPack>*) { return true; } inline bool visit(NodeType<ast::ArrayUnpack>*) { return true; } inline bool visit(NodeType<ast::Value<bool>>*) { return true; } inline bool visit(NodeType<ast::Value<int16_t>>*) { return true; } inline bool visit(NodeType<ast::Value<int32_t>>*) { return true; } inline bool visit(NodeType<ast::Value<int64_t>>*) { return true; } inline bool visit(NodeType<ast::Value<float>>*) { return true; } inline bool visit(NodeType<ast::Value<double>>*) { return true; } inline bool visit(NodeType<ast::Value<std::string>>*) { return true; } /// @} private: /// @brief Enabled for const traversals, where by the node pointer is /// returned /// @param Const reference to an AST node /// @return Const pointer to the node template <bool V, typename NodeT> inline typename std::enable_if<V, const NodeT*>::type strip(const NodeT& node) { return &node; } /// @brief Enabled for non-const traversals, where by a const stripped node /// pointer is returned /// @param Const reference to an AST node /// @return Non-const pointer to the node template <bool V, typename NodeT> inline typename std::enable_if<!V, typename std::remove_const<NodeT>::type*>::type strip(const NodeT& node) { return &(const_cast<NodeT&>(node)); } /// @brief Implements recursive hierarchical visits to a given AST node /// @tparam NodeT The node type /// @param node The node to perform class hierarchy visits on /// @return True if traversal should continue, false to terminate template <typename NodeT> bool hierarchyVisits(NodeT& node) { if (this->derived().reverseHierarchyVisits()) { if (auto base = node.NodeT::basetype()) { if (!hierarchyVisits(*base)) return false; } if (!this->derived().visit(this->strip<ConstVisit>(node))) return false; } else { if (!this->derived().visit(this->strip<ConstVisit>(node))) return false; if (auto base = node.NodeT::basetype()) { return hierarchyVisits(*base); } } return true; } /// @brief Implements the default behavior for a traversal to a given AST /// node /// @tparam NodeT The node type /// @param node The node to traverse /// @return True if traversal should continue, false to terminate template <typename NodeT> inline bool defaultTraversal(NodeType<NodeT>* node) { if (!node) return true; const size_t children = node->children(); if (this->derived().postOrderNodes()) { if (this->derived().reverseChildVisits()) { if (children != 0) { for (int64_t i = static_cast<int64_t>(children - 1); i >= 0; --i) { auto child = this->strip<ConstVisit>(*(node->child(i))); if (!this->derived().traverse(child)) { return false; } } } } else { for (size_t i = 0; i < children; ++i) { auto child = this->strip<ConstVisit>(*(node->child(i))); if (!this->derived().traverse(child)) { return false; } } } if (this->derived().visitNodeHierarchies()) { return this->hierarchyVisits(*node); } else { return this->derived().visit(node); } } else { if (this->derived().visitNodeHierarchies()) { if (!this->hierarchyVisits(*node)) return false; } else { if (!this->derived().visit(node)) return false; } if (this->derived().reverseChildVisits()) { if (children != 0) { for (int64_t i = static_cast<int64_t>(children - 1); i >= 0; --i) { auto child = this->strip<ConstVisit>(*(node->child(i))); if (!this->derived().traverse(child)) { return false; } } } } else { for (size_t i = 0; i < children; ++i) { auto child = this->strip<ConstVisit>(*(node->child(i))); if (!this->derived().traverse(child)) { return false; } } } return true; } } }; } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_AST_VISITOR_HAS_BEEN_INCLUDED
21,791
C
45.169491
139
0.619338
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/Scanners.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/Scanners.h /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief Retrieve intrinsic information from AX AST by performing /// various traversal algorithms. /// #ifndef OPENVDB_AX_COMPILER_AST_SCANNERS_HAS_BEEN_INCLUDED #define OPENVDB_AX_COMPILER_AST_SCANNERS_HAS_BEEN_INCLUDED #include "AST.h" #include "Visitor.h" #include <openvdb/version.h> #include <string> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { /// @brief Returns whether or not a given branch of an AST reads from or writes /// to a given attribute. /// /// @param node The AST to analyze /// @param name the name of the attribute to search for /// @param type the type of the attribute to search for. If UNKNOWN, any /// attribute with the given name is checked. /// bool usesAttribute(const ast::Node& node, const std::string& name, const tokens::CoreType type = tokens::UNKNOWN); /// @brief Returns whether or not a given branch of an AST writes to a given /// attribute. /// /// @param node The AST to analyze /// @param name the name of the attribute to search for /// @param type the type of the attribute to search for. If UNKNOWN, the first /// attribute encountered with the given name is checked. /// bool writesToAttribute(const ast::Node& node, const std::string& name, const tokens::CoreType type = tokens::UNKNOWN); /// @brief Returns whether or not a given branch of an AST calls a function /// /// @param node The AST to analyze /// @param name the name of the function to search for /// bool callsFunction(const ast::Node& node, const std::string& name); /// @brief todo void catalogueVariables(const ast::Node& node, std::vector<const ast::Variable*>* readOnly, std::vector<const ast::Variable*>* writeOnly, std::vector<const ast::Variable*>* readWrite, const bool locals = true, const bool attributes = true); /// @brief Parse all attributes into three unique vectors which represent how they /// are accessed within the syntax tree. Read only attributes are stored /// within the 'readOnly' container (for example @code int a=@a; @endcode), /// write only attributes in the 'writeOnly' container @code @a=1; @endcode /// and readWrite attributes in the 'readWrite' container @code @a+=1; @endcode /// @note Note that the code generator is able to do this far more efficiently, however /// this provides simple front-end support for detecting these types of operations /// /// @param node The AST to analyze /// @param readOnly The unique list of attributes which are only read from /// @param writeOnly The unique list of attributes which are only written too /// @param readWrite The unique list of attributes which both read from and written too /// void catalogueAttributeTokens(const ast::Node& node, std::vector<std::string>* readOnly, std::vector<std::string>* writeOnly, std::vector<std::string>* readWrite); /// @brief Populate a list of attribute names which the given attribute depends on void attributeDependencyTokens(const ast::Tree& tree, const std::string& name, const tokens::CoreType type, std::vector<std::string>& dependencies); /// @brief For an AST node of a given type, search for and call a custom /// const operator() which takes a const reference to every occurrence /// of the specified node type. /// /// @param node The AST to run over /// @param op The operator to call on every found AST node of type NodeT /// template <typename NodeT, typename OpT> inline void visitNodeType(const ast::Node& node, const OpT& op); /// @brief Visit all nodes of a given type and store pointers to them in a /// provided compatible container template<typename NodeT, typename ContainerType = std::vector<const NodeT*>> inline void collectNodeType(const ast::Node& node, ContainerType& array); /// @brief Visit all nodes of the given types and store pointers to them in a /// container of base ast::Node pointers /// @note NodeTypeList is expected to be a an openvdb::TypeList object with a /// list of node types. For example, to collect all Attribute and /// External Variable ast Nodes: /// /// using ListT = openvdb::TypeList<ast::Attribute, ast::ExternalVariable>; /// std::vector<const ast::Node*> nodes; /// ast::collectNodeTypes<ListT>(tree, nodes); /// template <typename NodeTypeList, typename ContainerType = std::vector<const Node*>> inline void collectNodeTypes(const ast::Node& node, ContainerType& array); /// @brief Flatten the provided AST branch into a linear list using post order traversal /// void linearize(const ast::Node& node, std::vector<const ast::Node*>& list); const ast::Variable* firstUse(const ast::Node& node, const std::string& token); const ast::Variable* lastUse(const ast::Node& node, const std::string& token); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// namespace internal { template<typename ContainerType, typename T, typename ...Ts> struct CollectForEach { static void exec(const ast::Node&, ContainerType&) {} }; template<typename ContainerType, typename T, typename ...Ts> struct CollectForEach<ContainerType, TypeList<T, Ts...>> { static void exec(const ast::Node& node, ContainerType& C) { collectNodeType<T, ContainerType>(node, C); CollectForEach<ContainerType, TypeList<Ts...>>::exec(node, C); } }; } template<typename NodeT, typename ContainerType> inline void collectNodeType(const ast::Node& node, ContainerType& array) { visitNodeType<NodeT>(node, [&](const NodeT& node) -> bool { array.push_back(&node); return true; }); } template <typename NodeTypeList, typename ContainerType> inline void collectNodeTypes(const ast::Node& node, ContainerType& array) { internal::CollectForEach<ContainerType, NodeTypeList>::exec(node, array); } template <typename NodeT, typename OpT, typename Derived = void> struct VisitNodeType : public ast::Visitor<typename std::conditional< std::is_same<Derived, void>::value, VisitNodeType<NodeT, OpT>, Derived>::type> { using VisitorT = typename std::conditional< std::is_same<Derived, void>::value, VisitNodeType<NodeT, OpT>, Derived>::type; using ast::Visitor<VisitorT>::traverse; using ast::Visitor<VisitorT>::visit; inline bool visitNodeHierarchies() const { return std::is_abstract<NodeT>::value; } VisitNodeType(const OpT& op) : mOp(op) {} ~VisitNodeType() = default; inline bool visit(const NodeT* node) { if (node) return mOp(*node); return true; } private: const OpT& mOp; }; template <typename NodeT, typename OpT> inline void visitNodeType(const ast::Node& node, const OpT& op) { VisitNodeType<NodeT, OpT> visitOp(op); visitOp.traverse(&node); } } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_COMPILER_AST_SCANNERS_HAS_BEEN_INCLUDED
7,375
C
34.805825
90
0.678915
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/Scanners.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/Scanners.cc #include "Scanners.h" #include "Visitor.h" #include <string> #include <unordered_map> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { namespace { template <typename NodeT, typename OpT> struct VariableDependencyVisitor : public ast::VisitNodeType<NodeT, OpT, VariableDependencyVisitor<NodeT, OpT>> { using BaseT = ast::VisitNodeType<NodeT, OpT, VariableDependencyVisitor<NodeT, OpT>>; using BaseT::traverse; using BaseT::visit; VariableDependencyVisitor(const OpT& op) : BaseT(op) {} ~VariableDependencyVisitor() = default; bool traverse(const ast::Loop* loop) { if (!loop) return true; if (!this->traverse(loop->initial())) return false; if (!this->traverse(loop->condition())) return false; if (!this->traverse(loop->iteration())) return false; if (!this->traverse(loop->body())) return false; if (!this->visit(loop)) return false; return true; } }; /// @brief For a given variable at a particular position in an AST, find all /// attributes, locals and external variables which it depends on (i.e. any /// Attribute, Local or ExternalVariable AST nodes which impacts the given /// variables value) by recursively traversing through all connected paths. /// This includes both direct and indirect influences; for example, a direct /// assignment "@b = @a;" and an indirect code branch "if (@a) @b = 1"; /// @note This is position dependent in regards to the given variables location. /// Any code which writes to this variable after the given usage will not be /// cataloged in the output dependency vector. /// @warning This does not currently handle scoped local variable re-declarations /// and instead will end up adding matching names as extra dependencies /// @todo: fix this for scoped variables, capturing of all instances, and not adding /// dependencies between different branches of conditionals void variableDependencies(const ast::Variable& var, std::vector<const ast::Variable*>& dependencies) { // external variables are read-only i.e. have no dependencies if (var.nodetype() == ast::Node::ExternalVariableNode) return; // Get the root node const ast::Node* root = &var; while (const ast::Node* parent = root->parent()) { root = parent; } // collect all occurrences of this var up to and including // it's current usage, terminating traversal afterwards const bool attributeVisit = (var.nodetype() == ast::Node::AttributeNode); std::vector<const ast::Variable*> usage; auto collect = [&var, &usage, attributeVisit] (const ast::Variable& use) -> bool { if (attributeVisit) { if (use.nodetype() != ast::Node::AttributeNode) return true; const auto& attrib = static_cast<const ast::Attribute&>(var); const auto& useAttrib = static_cast<const ast::Attribute&>(use); if (attrib.tokenname() != useAttrib.tokenname()) return true; } else { if (use.nodetype() != ast::Node::LocalNode) return true; if (use.name() != var.name()) return true; } usage.emplace_back(&use); return &use != &var; }; VariableDependencyVisitor<ast::Variable, decltype(collect)> depVisitor(collect); depVisitor.traverse(root); // The list of nodes which can be considered dependencies to collect using ListT = openvdb::TypeList< ast::Attribute, ast::Local, ast::ExternalVariable>; // small lambda to check to see if a dep is already being tracked auto hasDep = [&](const ast::Variable* dep) -> bool { return (std::find(dependencies.cbegin(), dependencies.cend(), dep) != dependencies.cend()); }; // recursively traverse all usages and resolve dependencies for (const auto& use : usage) { const ast::Node* child = use; // track writable for conditionals bool written = false; while (const ast::Node* parent = child->parent()) { const ast::Node::NodeType type = parent->nodetype(); if (type == ast::Node::CrementNode) { written = true; if (!hasDep(use)) { dependencies.emplace_back(use); } } else if (type == ast::Node::ConditionalStatementNode) { const ast::ConditionalStatement* conditional = static_cast<const ast::ConditionalStatement*>(parent); const ast::Expression* condition = conditional->condition(); // traverse down and collect variables if (child != condition){ std::vector<const ast::Variable*> vars; collectNodeTypes<ListT>(*condition, vars); // find next deps for (const ast::Variable* dep : vars) { // don't add this dep if it's not being written to. Unlike // all other visits, the conditionals dictate program flow. // Values in the conditional expression only link to the // current usage if the current usage is being modified if (!written || hasDep(dep)) continue; dependencies.emplace_back(dep); variableDependencies(*dep, dependencies); } } } else if (type == ast::Node::TernaryOperatorNode) { const ast::TernaryOperator* ternary = static_cast<const ast::TernaryOperator*>(parent); const ast::Expression* condition = ternary->condition(); // traverse down and collect variables if (child != condition) { std::vector<const ast::Variable*> vars; collectNodeTypes<ListT>(*condition, vars); // find next deps for (const ast::Variable* dep : vars) { // don't add this dep if it's not being written to. Unlike // all other visits, the conditionals dictate program flow. // Values in the conditional expression only link to the // current usage if the current usage is being modified if (!written || hasDep(dep)) continue; dependencies.emplace_back(dep); variableDependencies(*dep, dependencies); } } } else if (type == ast::Node::LoopNode) { const ast::Loop* loop = static_cast<const ast::Loop*>(parent); const ast::Statement* condition = loop->condition(); // traverse down and collect variables if (child != condition) { std::vector<const ast::Variable*> vars; // if the condition is a comma operator the last element determines flow if (condition->nodetype() == ast::Node::NodeType::CommaOperatorNode) { const ast::CommaOperator* comma = static_cast<const ast::CommaOperator*>(condition); if (!comma->empty()) { const ast::Expression* lastExpression = comma->child(comma->size()-1); collectNodeTypes<ListT>(*lastExpression, vars); } } else { collectNodeTypes<ListT>(*condition, vars); } // find next deps for (const ast::Variable* dep : vars) { // don't add this dep if it's not being written to. Unlike // all other visits, the conditionals dictate program flow. // Values in the conditional expression only link to the // current usage if the current usage is being modified if (!written || hasDep(dep)) continue; dependencies.emplace_back(dep); variableDependencies(*dep, dependencies); } } } else if (type == ast::Node::AssignExpressionNode) { const ast::AssignExpression* assignment = static_cast<const ast::AssignExpression*>(parent); if (assignment->lhs() == child) { written = true; // add self dependency if compound if (assignment->isCompound()) { if (!hasDep(use)) { dependencies.emplace_back(use); } } // traverse down and collect variables std::vector<const ast::Variable*> vars; collectNodeTypes<ListT>(*assignment->rhs(), vars); // find next deps for (const ast::Variable* dep : vars) { if (hasDep(dep)) continue; dependencies.emplace_back(dep); variableDependencies(*dep, dependencies); } } } else if (type == ast::Node::DeclareLocalNode) { const ast::DeclareLocal* declareLocal = static_cast<const ast::DeclareLocal*>(parent); if (declareLocal->local() == child && declareLocal->hasInit()) { std::vector<const ast::Variable*> vars; written = true; // traverse down and collect variables collectNodeTypes<ListT>(*declareLocal->init(), vars); for (const ast::Variable* dep : vars) { if (hasDep(dep)) continue; dependencies.emplace_back(dep); variableDependencies(*dep, dependencies); } } } else if (type == ast::Node::FunctionCallNode) { written = true; // @todo We currently can't detect if attributes are being passed by // pointer and being modified automatically. We have to link this // attribute to any other attribute passes into the function const ast::FunctionCall* call = static_cast<const ast::FunctionCall*>(parent); // traverse down and collect variables std::vector<const ast::Variable*> vars; for (size_t i = 0; i < call->children(); ++i) { collectNodeTypes<ListT>(*call->child(i), vars); } // only append dependencies here if they havent already been visited // due to recursion issues for (const ast::Variable* dep : vars) { // make sure the dep doesn't already exist in the container, otherwise // we can get into issues where functions with multiple arguments // constantly try to check themselves // @note should be removed with function refactoring if (hasDep(dep)) continue; dependencies.emplace_back(dep); variableDependencies(*dep, dependencies); } } child = parent; } } } } // anonymous namespace bool usesAttribute(const ast::Node& node, const std::string& name, const tokens::CoreType type) { bool found = false; visitNodeType<ast::Attribute>(node, [&](const ast::Attribute& attrib) -> bool { assert(!found); if (type != tokens::UNKNOWN) { if (attrib.type() != type) return true; } if (attrib.name() != name) return true; found = true; return false; }); return found; } bool writesToAttribute(const ast::Node& node, const std::string& name, const tokens::CoreType type) { std::vector<const ast::Variable*> vars; catalogueVariables(node, nullptr, &vars, &vars, false, true); // See if any attributes in the result vec match the given name/type for (const ast::Variable* var : vars) { assert(var->isType<ast::Attribute>()); const ast::Attribute* attrib = static_cast<const ast::Attribute*>(var); if (type != tokens::UNKNOWN) { if (attrib->type() != type) continue; } if (attrib->name() != name) continue; return true; } return false; } void catalogueVariables(const ast::Node& node, std::vector<const ast::Variable*>* readOnly, std::vector<const ast::Variable*>* writeOnly, std::vector<const ast::Variable*>* readWrite, const bool locals, const bool attributes) { std::vector<const ast::Variable*> vars; if (locals) { collectNodeTypes<ast::Local>(node, vars); } if (attributes) { collectNodeType<ast::Attribute>(node, vars); } for (const ast::Variable* var : vars) { // traverse upwards, see if we're embedded in an assign or crement expression const ast::Node* child = var; const ast::Node* parent = child->parent(); bool read = false, write = false; while (parent && !(write && read)) { const ast::Node::NodeType type = parent->nodetype(); // crement operations read and write if (type == ast::Node::CrementNode) { read = write = true; } else if (type == ast::Node::AssignExpressionNode) { const ast::AssignExpression* assignment = static_cast<const ast::AssignExpression*>(parent); if (assignment->lhs() == child) { if (assignment->isCompound()) { // +=, *=, /= etc read = write = true; } else { // op = op write = true; } } else { read = true; } } else if (type == ast::Node::DeclareLocalNode) { const ast::DeclareLocal* declareLocal = static_cast<const ast::DeclareLocal*>(parent); if (declareLocal->local() == child) { if (declareLocal->hasInit()) { write = true; } } } else if (type == ast::Node::FunctionCallNode) { // @todo We currently can't detect if attributes are being passed by // pointer and being modified automatically. This is a major limitation // as it means any attribute passed into any function directly must // be marked as writeable read = write = true; } else { read = true; } child = parent; parent = child->parent(); } assert(read || write); if (readWrite && read && write) readWrite->emplace_back(var); if (readOnly && read && !write) readOnly->emplace_back(var); if (writeOnly && !read && write) writeOnly->emplace_back(var); } } void catalogueAttributeTokens(const ast::Node& node, std::vector<std::string>* readOnly, std::vector<std::string>* writeOnly, std::vector<std::string>* readWrite) { std::vector<const ast::Variable*> readOnlyVars; std::vector<const ast::Variable*> writeOnlyVars; std::vector<const ast::Variable*> readWriteVars; catalogueVariables(node, (readOnly ? &readOnlyVars : nullptr), (writeOnly ? &writeOnlyVars : nullptr), (readWrite ? &readWriteVars : nullptr), false, // locals true); // attributes // fill a single map with the access patterns for all attributes // .first = read, .second = write std::unordered_map<std::string, std::pair<bool,bool>> accessmap; auto addAccesses = [&](const std::vector<const ast::Variable*>& vars, const bool read, const bool write) { for (const ast::Variable* var : vars) { assert(var->isType<ast::Attribute>()); const ast::Attribute* attrib = static_cast<const ast::Attribute*>(var); auto& access = accessmap[attrib->tokenname()]; access.first |= read; access.second |= write; } }; addAccesses(readWriteVars, true, true); addAccesses(writeOnlyVars, false, true); addAccesses(readOnlyVars, true, false); // set the results from the access map for (const auto& result : accessmap) { const std::pair<bool,bool>& pair = result.second; if (readWrite && pair.first && pair.second) { readWrite->emplace_back(result.first); } else if (writeOnly && !pair.first && pair.second) { writeOnly->emplace_back(result.first); } else if (readOnly && pair.first && !pair.second) { readOnly->emplace_back(result.first); } } } template <bool First> struct UseVisitor : public ast::Visitor<UseVisitor<First>> { using ast::Visitor<UseVisitor<First>>::traverse; using ast::Visitor<UseVisitor<First>>::visit; // reverse the ast traversal if !First inline bool reverseChildVisits() const { return !First; } UseVisitor(const std::string& tokenOrName) : mToken(tokenOrName) , mAttribute(false) , mVar(nullptr) { // rebuild the expected token if necessary std::string name, type; mAttribute = ast::Attribute::nametypeFromToken(mToken, &name, &type); if (mAttribute) { mToken = type + ast::Attribute::symbolseparator() + name; } } ~UseVisitor() = default; bool traverse(const ast::Loop* loop) { if (!loop) return true; const ast::tokens::LoopToken type = loop->loopType(); if (type == ast::tokens::DO) { if (!this->reverseChildVisits()) { if (!this->traverse(loop->body())) return false; if (!this->traverse(loop->condition())) return false; } else { if (!this->traverse(loop->condition())) return false; if (!this->traverse(loop->body())) return false; } assert(!loop->initial()); assert(!loop->iteration()); } else { if (!this->reverseChildVisits()) { if (!this->traverse(loop->initial())) return false; if (!this->traverse(loop->condition())) return false; if (!this->traverse(loop->iteration())) return false; if (!this->traverse(loop->body())) return false; } else { if (!this->traverse(loop->body())) return false; if (!this->traverse(loop->iteration())) return false; if (!this->traverse(loop->condition())) return false; if (!this->traverse(loop->initial())) return false; } } if (!this->visit(loop)) return false; return true; } inline bool visit(const ast::Attribute* node) { if (!mAttribute) return true; if (node->tokenname() != mToken) return true; mVar = node; return false; } inline bool visit(const ast::Local* node) { if (mAttribute) return true; if (node->name() != mToken) return true; mVar = node; return false; } const ast::Variable* var() const { return mVar; } private: std::string mToken; bool mAttribute; const ast::Variable* mVar; }; void attributeDependencyTokens(const ast::Tree& tree, const std::string& name, const tokens::CoreType type, std::vector<std::string>& dependencies) { const std::string token = ast::Attribute::tokenFromNameType(name, type); const ast::Variable* var = lastUse(tree, token); if (!var) return; assert(var->isType<ast::Attribute>()); std::vector<const ast::Variable*> deps; variableDependencies(*var, deps); for (const auto& dep : deps) { if (dep->nodetype() != ast::Node::AttributeNode) continue; dependencies.emplace_back(static_cast<const ast::Attribute*>(dep)->tokenname()); } std::sort(dependencies.begin(), dependencies.end()); auto iter = std::unique(dependencies.begin(), dependencies.end()); dependencies.erase(iter, dependencies.end()); } const ast::Variable* firstUse(const ast::Node& node, const std::string& tokenOrName) { UseVisitor<true> visitor(tokenOrName); visitor.traverse(&node); return visitor.var(); } const ast::Variable* lastUse(const ast::Node& node, const std::string& tokenOrName) { UseVisitor<false> visitor(tokenOrName); visitor.traverse(&node); return visitor.var(); } bool callsFunction(const ast::Node& node, const std::string& name) { bool found = false; visitNodeType<ast::FunctionCall>(node, [&](const ast::FunctionCall& call) -> bool { if (call.name() != name) return true; found = true; return false; }); return found; } void linearize(const ast::Node& node, std::vector<const ast::Node*>& list) { collectNodeType<ast::Node>(node, list); } } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
22,138
C++
37.840351
98
0.547023
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/Tokens.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/Tokens.h /// /// @authors Nick Avramoussis /// /// @brief Various function and operator tokens used throughout the /// AST and code generation /// #ifndef OPENVDB_AX_AST_TOKENS_HAS_BEEN_INCLUDED #define OPENVDB_AX_AST_TOKENS_HAS_BEEN_INCLUDED #include "../Exceptions.h" #include <openvdb/version.h> #include <openvdb/Types.h> #include <stdexcept> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { namespace tokens { enum CoreType { BOOL = 0, CHAR, INT16, INT32, INT64, FLOAT, DOUBLE, // VEC2I, VEC2F, VEC2D, // VEC3I, VEC3F, VEC3D, // VEC4I, VEC4F, VEC4D, // MAT3F, MAT3D, // MAT4F, MAT4D, // QUATF, QUATD, // STRING, UNKNOWN }; inline CoreType tokenFromTypeString(const std::string& type) { if (type[0] == 'v') { if (type == "vec2i") return VEC2I; if (type == "vec2f") return VEC2F; if (type == "vec2d") return VEC2D; if (type == "vec3i") return VEC3I; if (type == "vec3f") return VEC3F; if (type == "vec3d") return VEC3D; if (type == "vec4i") return VEC4I; if (type == "vec4f") return VEC4F; if (type == "vec4d") return VEC4D; } else if (type[0] == 'm') { if (type == "mat3f") return MAT3F; if (type == "mat3d") return MAT3D; if (type == "mat4f") return MAT4F; if (type == "mat4d") return MAT4D; } else if (type[0] == 'q') { if (type == "quatf") return QUATF; if (type == "quatd") return QUATD; } else if (type[0] == 'i') { if (type == "int16") return INT16; if (type == "int") return INT32; if (type == "int32") return INT32; if (type == "int64") return INT64; } else if (type == "bool") return BOOL; else if (type == "char") return CHAR; else if (type == "float") return FLOAT; else if (type == "double") return DOUBLE; else if (type == "string") return STRING; // also handle vdb types that have different type strings to our tokens // @todo These should probably be separated out. The executables currently // use this function to guarantee conversion if (type[0] == 'v') { if (type == "vec2s") return VEC2F; if (type == "vec3s") return VEC3F; if (type == "vec4s") return VEC4F; } else if (type[0] == 'm') { if (type == "mat3s") return MAT3F; if (type == "mat4s") return MAT4F; } else if (type == "quats") return QUATF; return UNKNOWN; } inline std::string typeStringFromToken(const CoreType type) { switch (type) { case BOOL : return "bool"; case CHAR : return "char"; case INT16 : return "int16"; case INT32 : return "int32"; case INT64 : return "int64"; case FLOAT : return "float"; case DOUBLE : return "double"; case VEC2I : return "vec2i"; case VEC2F : return "vec2f"; case VEC2D : return "vec2d"; case VEC3I : return "vec3i"; case VEC3F : return "vec3f"; case VEC3D : return "vec3d"; case VEC4I : return "vec4i"; case VEC4F : return "vec4f"; case VEC4D : return "vec4d"; case MAT3F : return "mat3f"; case MAT3D : return "mat3d"; case MAT4F : return "mat4f"; case MAT4D : return "mat4d"; case QUATF : return "quatf"; case QUATD : return "quatd"; case STRING : return "string"; case UNKNOWN : default : return "unknown"; } } enum OperatorToken { //////////////////////////////////////////////////////////////// /// ARITHMETIC //////////////////////////////////////////////////////////////// PLUS = 0, MINUS, MULTIPLY, DIVIDE, MODULO, //////////////////////////////////////////////////////////////// /// LOGICAL //////////////////////////////////////////////////////////////// AND, OR, NOT, //////////////////////////////////////////////////////////////// /// RELATIONAL //////////////////////////////////////////////////////////////// EQUALSEQUALS, NOTEQUALS, MORETHAN, LESSTHAN, MORETHANOREQUAL, LESSTHANOREQUAL, //////////////////////////////////////////////////////////////// /// BITWISE //////////////////////////////////////////////////////////////// SHIFTLEFT, SHIFTRIGHT, BITAND, BITOR, BITXOR, BITNOT, //////////////////////////////////////////////////////////////// /// ASSIGNMENT //////////////////////////////////////////////////////////////// EQUALS, PLUSEQUALS, MINUSEQUALS, MULTIPLYEQUALS, DIVIDEEQUALS, MODULOEQUALS, SHIFTLEFTEQUALS, SHIFTRIGHTEQUALS, BITANDEQUALS, BITXOREQUALS, BITOREQUALS }; enum OperatorType { ARITHMETIC = 0, LOGICAL, RELATIONAL, BITWISE, ASSIGNMENT, UNKNOWN_OPERATOR }; inline OperatorType operatorType(const OperatorToken token) { const size_t idx = static_cast<size_t>(token); if (idx <= static_cast<size_t>(MODULO)) return ARITHMETIC; if (idx <= static_cast<size_t>(NOT)) return LOGICAL; if (idx <= static_cast<size_t>(LESSTHANOREQUAL)) return RELATIONAL; if (idx <= static_cast<size_t>(BITNOT)) return BITWISE; if (idx <= static_cast<size_t>(BITOREQUALS)) return ASSIGNMENT; return UNKNOWN_OPERATOR; } inline OperatorToken operatorTokenFromName(const std::string& name) { if (name == "+") return PLUS; if (name == "-") return MINUS; if (name == "*") return MULTIPLY; if (name == "/") return DIVIDE; if (name == "%") return MODULO; if (name == "&&") return AND; if (name == "||") return OR; if (name == "!") return NOT; if (name == "==") return EQUALSEQUALS; if (name == "!=") return NOTEQUALS; if (name == ">") return MORETHAN; if (name == "<") return LESSTHAN; if (name == ">=") return MORETHANOREQUAL; if (name == "<=") return LESSTHANOREQUAL; if (name == "<<") return SHIFTLEFT; if (name == ">>") return SHIFTRIGHT; if (name == "&") return BITAND; if (name == "|") return BITOR; if (name == "^") return BITXOR; if (name == "~") return BITNOT; if (name == "=") return EQUALS; if (name == "+=") return PLUSEQUALS; if (name == "-=") return MINUSEQUALS; if (name == "*=") return MULTIPLYEQUALS; if (name == "/=") return DIVIDEEQUALS; if (name == "%=") return MODULOEQUALS; if (name == "<<=") return SHIFTLEFTEQUALS; if (name == ">>=") return SHIFTRIGHTEQUALS; if (name == "&=") return BITANDEQUALS; if (name == "^=") return BITXOREQUALS; if (name == "|=") return BITOREQUALS; OPENVDB_THROW(AXTokenError, "Unsupported op \"" + name + "\""); } inline std::string operatorNameFromToken(const OperatorToken token) { switch (token) { case PLUS : return "+"; case MINUS : return "-"; case MULTIPLY : return "*"; case DIVIDE : return "/"; case MODULO : return "%"; case AND : return "&&"; case OR : return "||"; case NOT : return "!"; case EQUALSEQUALS : return "=="; case NOTEQUALS : return "!="; case MORETHAN : return ">"; case LESSTHAN : return "<"; case MORETHANOREQUAL : return ">="; case LESSTHANOREQUAL : return "<="; case SHIFTLEFT : return "<<"; case SHIFTRIGHT : return ">>"; case BITAND : return "&"; case BITOR : return "|"; case BITXOR : return "^"; case BITNOT : return "~"; case EQUALS : return "="; case PLUSEQUALS : return "+="; case MINUSEQUALS : return "-="; case MULTIPLYEQUALS : return "*="; case DIVIDEEQUALS : return "/="; case MODULOEQUALS : return "%="; case SHIFTLEFTEQUALS : return "<<="; case SHIFTRIGHTEQUALS : return ">>="; case BITANDEQUALS : return "&="; case BITXOREQUALS : return "^="; case BITOREQUALS : return "|="; default : OPENVDB_THROW(AXTokenError, "Unsupported op"); } } enum LoopToken { FOR = 0, DO, WHILE }; inline std::string loopNameFromToken(const LoopToken loop) { switch (loop) { case FOR : return "for"; case DO : return "do"; case WHILE : return "while"; default : OPENVDB_THROW(AXTokenError, "Unsupported loop"); } } enum KeywordToken { RETURN = 0, BREAK, CONTINUE }; inline std::string keywordNameFromToken(const KeywordToken keyw) { switch (keyw) { case RETURN : return "return"; case BREAK : return "break"; case CONTINUE : return "continue"; default : OPENVDB_THROW(AXTokenError, "Unsupported keyword"); } } } // namespace tokens } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_AST_TOKENS_HAS_BEEN_INCLUDED
9,644
C
27.201754
79
0.496786
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/Parse.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/Parse.h /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief Parsing methods for creating abstract syntax trees out of AX code /// #ifndef OPENVDB_AX_PARSE_HAS_BEEN_INCLUDED #define OPENVDB_AX_PARSE_HAS_BEEN_INCLUDED #include "AST.h" #include "../compiler/Logger.h" #include <openvdb/version.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { /// @brief Construct an abstract syntax tree from a code snippet. If the code is /// not well formed, as defined by the AX grammar, this will simply return /// nullptr, with the logger collecting the errors. /// @note The returned AST is const as the logger uses this to determine line /// and column numbers of errors/warnings in later stages. If you need to /// modify the tree, take a copy. /// /// @return A shared pointer to a valid const AST, or nullptr if errored. /// /// @param code The code to parse /// @param logger The logger to collect syntax errors /// openvdb::ax::ast::Tree::ConstPtr parse(const char* code, ax::Logger& logger); /// @brief Construct an abstract syntax tree from a code snippet. /// A runtime exception will be thrown with the first syntax error. /// /// @return A shared pointer to a valid AST. /// /// @param code The code to parse /// openvdb::ax::ast::Tree::Ptr parse(const char* code); } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_AST_HAS_BEEN_INCLUDED
1,642
C
27.824561
82
0.699147
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ast/AST.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ast/AST.h /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief Provides the definition for every abstract and concrete derived /// class which represent a particular abstract syntax tree (AST) node /// type. /// /// AST nodes represents a particular branch of a complete AST. Concrete /// nodes can be thought of as leaf node types which hold semantic /// information of a partial or complete statement or expression. A /// string of AX can be fully represented by building the correct /// AST structure. The AX grammar defined in axparser.y represents the /// valid mapping of a tokenized string to AST nodes. /// /// AST node classes can either represent a "leaf-level" semantic /// component of a given AX AST, or an abstract base type. The latter are /// used by the parser and leaf-level AST nodes for storage of compatible /// child nodes, and provide grouping of various nodes which share common /// semantics. The main two types of abstract AST nodes are statements /// and expressions. /// #ifndef OPENVDB_AX_AST_HAS_BEEN_INCLUDED #define OPENVDB_AX_AST_HAS_BEEN_INCLUDED #include "Tokens.h" #include <openvdb/version.h> #include <memory> #include <utility> #include <vector> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace ast { /// @brief Forward declaration of the base Abstract Syntax Tree type. /// @note Not to be confused with ast::Node types, which are the base abstract /// type for all AST nodes. Tree nodes are the highest possible concrete /// node type (in terms of hierarchy) which represent a full AX file. /// They are always returned from the parser. struct Tree; //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @details A reference list of all abstract and concrete AST nodes in /// hierarchical order (non-linear) /// Abstract nodes: /// - Node /// - Statement /// - Expression /// - Variable /// - ValueBase /// /// Concrete nodes: /// - Tree /// - StatementList /// - Block /// - Loop /// - Keyword /// - ConditionalStatement /// - CommaOperator /// - BinaryOperator /// - TernaryOperator /// - AssignExpression /// - Crement /// - UnaryOperator /// - Cast /// - FunctionCall /// - ArrayUnpack /// - ArrayPack /// - Attribute /// - ExternalVariable /// - DeclareLocal /// - Local /// - Value<double/float/int32_t/int16_t/int64_t/bool> /// - Value<std::string> //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @brief The base abstract node which determines the interface and required /// methods for all derived concrete nodes which comprise a valid AST. /// @note All AST nodes share a few common characteristics. All constructors /// typically take pointers to the abstract (pure-virtual) node types /// and assume ownership of this data on successful construction. Deep /// copy methods propagate down through all children of a given AST node /// but have the unique behavior of ensuring parent data is updated to /// the newly created parent nodes. Due to this behavior and the fact /// that most nodes store unique pointers to other nodes, we've omitted /// comparison and equality operators. struct Node { using Ptr = std::shared_ptr<Node>; using UniquePtr = std::unique_ptr<Node>; /// @brief An enumerated list of node types for all concrete node types. /// These can be used for faster evaluation of a given concrete node /// using the virtual function table via Node::nodetype() rather /// than performing a dynamic_cast/calling Node::isType. /// @note This is sometimes referred to as "manual RTTI". We use this /// technique combine with single dispatch due to opting for CRTP on /// the main visitor and no templated virtual method support in C++. /// i.e. no way to double dispatch: visit<template T>(Visitor<T>*) /// @note Abstract (pure-virtual) nodes are not listed here. Node::isType /// should be used to determine if a node is of a given abstract /// type. enum NodeType { TreeNode, StatementListNode, BlockNode, ConditionalStatementNode, CommaOperatorNode, LoopNode, KeywordNode, AssignExpressionNode, CrementNode, UnaryOperatorNode, BinaryOperatorNode, TernaryOperatorNode, CastNode, AttributeNode, FunctionCallNode, ExternalVariableNode, DeclareLocalNode, ArrayPackNode, ArrayUnpackNode, LocalNode, ValueBoolNode, ValueInt16Node, ValueInt32Node, ValueInt64Node, ValueFloatNode, ValueDoubleNode, ValueStrNode }; Node() = default; virtual ~Node() = default; /// @brief The deep copy method for a Node /// @return A deep copy of the current node and all its children virtual Node* copy() const = 0; /// @name Name/Type /// @{ /// @brief Virtual method for accessing node type information /// @note This method should be used when querying a concrete nodes type. /// @return Returns the enumerated node type from the NodeType list virtual NodeType nodetype() const = 0; /// @brief Virtual method for accessing node name information /// @return Returns the node class name virtual const char* nodename() const = 0; /// @brief Virtual method for accessing node name information /// @return Returns the short node class name virtual const char* subname() const = 0; /// @brief Virtual method for accessing a node's base class. Note that if /// this is called explicitly on an instance of ast::Node (the top /// most base class) a nullptr is returned. This is primarily used /// by the Visitor to support hierarchical visits. /// @return Returns the current node as its base class type. virtual const Node* basetype() const { return nullptr; } /// @brief Query whether or not this node is of a specific (derived) type. /// This method should be used to check if a node is of a particular /// abstract type. When checking concrete types, it's generally /// more efficient to check the return value of Node::nodetype() /// @tparam NodeT The node type to query against. /// @return True if this node is of the given type, false otherwise. template <typename NodeT> inline bool isType() const { return dynamic_cast<const NodeT*>(this); } /// @} /// @name Child Queries /// @{ /// @brief Virtual method for accessing child information. Returns the /// number of children a given AST node owns. /// @return The number of children this node owns. virtual size_t children() const = 0; /// @brief Virtual method for accessing child information. Returns a const /// pointer to a child node at the given index. If the index is out /// of range, a nullptr is returned. /// @note This may still return a nullptr even if the given index is valid /// if the child node has not been created. /// @param index The child index to query /// @return A Pointer to the child node, or a nullptr if none exists. virtual const Node* child(const size_t index) const = 0; /// @brief Returns the child index of this node in relation to its parent, /// or -1 if no valid index is found (usually representing the top /// most node (i.e. Tree) /// @return The child index of this node inline int64_t childidx() const { const Node* p = this->parent(); if (!p) return -1; size_t i = 0; const size_t count = p->children(); for (; i < count; ++i) { if (p->child(i) == this) break; } if (i == count) return -1; return static_cast<int64_t>(i); } /// @} /// @name Replacement /// @{ /// @brief In place replacement. Attempts to replace this node at its /// specific location within its Abstract Syntax Tree. On a /// successful replacement, this node is destroyed, the provided /// node is inserted in its place and ownership is transferred to the /// parent node. No further calls to this node can be made on /// successful replacements. /// @note A replacement will fail if this node is the top most node within /// an AST hierarchy or if the provided node type is not a /// compatible type for the required abstract storage. For example, /// if this node is an Attribute being held on a BinaryOperator, /// only concrete nodes derived from an Expression can be used as a /// replacement. /// @note This method will dynamic_cast the provided node to check to see /// if it's a compatible type. /// @param node The node to insert on a successful replacement. /// @return True if the replacement was successful, resulting in destruction /// of this class and ownership transferal of the provided node. /// False otherwise, where this and the provided node are unchanged. inline bool replace(Node* node) { const int64_t idx = this->childidx(); if (idx == -1) return false; // avoid second vcall return this->parent()->replacechild(idx, node); } /// @brief Virtual method that attempted to replace a child at a given /// index with a provided node type. /// @note See Node::replace for a more detailed description /// @param index The child index where a replacement should be attempted /// @param node The node to insert on a successful replacement. /// @return True if the replacement was successful, false otherwise inline virtual bool replacechild(const size_t index, Node* node); /// @} /// @name Parent /// @{ /// @brief Access a const pointer to this nodes parent /// @note Can be a nullptr if this is the top most node in an AST (usually /// a Tree) /// @return A const pointer to this node's parent node inline const Node* parent() const { return mParent; } /// @brief Set this node's parent. This is used during construction of an /// AST and should not be used. @todo Make this private. /// @param parent The parent to set inline void setParent(Node* parent) { #ifndef NDEBUG bool hasChild = false; for (size_t i = 0; i < parent->children(); ++i) hasChild |= parent->child(i) == this; assert(hasChild); #endif mParent = parent; } private: /// @brief Access a non const pointer to this nodes parent. Used by /// replacement methods. /// @note Can be a nullptr if this is the top most node in an AST (usually /// a Tree) /// @return A non-const pointer to this nodes parent node inline Node* parent() { return mParent; } /// @} Node* mParent = nullptr; }; inline bool Node::replacechild(const size_t, Node*) { return false; } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// Abstract (pure-virtual) AST nodes /// @brief Statements are anything that can make up a line, i.e. everything /// in between semicolons. Likewise to their base ast::Node class, /// currently every concrete AST node is either directly or indirectly /// a derived statement type. They hold no class data. struct Statement : public Node { using UniquePtr = std::unique_ptr<Statement>; ~Statement() override = default; virtual Statement* copy() const override = 0; const Node* basetype() const override { return this; } }; /// @brief Expressions are comprised of full or potentially partial parts of a /// full statement that may not necessary make up an entire valid /// statement on their own. For example, while a Binary Operator such as /// "3 + 5;"" is a valid statement on its own, the full statement /// "3 + 5 + 6;" must be broken down into two expressions which together /// form the statement as well as determining precedence. struct Expression : public Statement { using UniquePtr = std::unique_ptr<Expression>; ~Expression() override = default; virtual Expression* copy() const override = 0; const Statement* basetype() const override { return this; } }; /// @brief Variables are a base type for Locals, Attributes and /// ExternalVariables. Unlike other abstract types, they also consolidate /// data for the derived types. struct Variable : public Expression { using UniquePtr = std::unique_ptr<Variable>; Variable(const std::string& name) : Expression(), mName(name) {} Variable(const Variable& other) : Expression(), mName(other.mName) {} ~Variable() override = default; virtual Variable* copy() const override = 0; const Expression* basetype() const override { return this; } // size_t children() const override { return 0; } const Node* child(const size_t) const override { return nullptr; } // inline const std::string& name() const { return mName; } private: const std::string mName; }; /// @brief ValueBases are a base class for anything that holds a value (literal). /// Derived classes store the actual typed values struct ValueBase : public Expression { using UniquePtr = std::unique_ptr<ValueBase>; ~ValueBase() override = default; virtual Expression* copy() const override = 0; const Expression* basetype() const override { return this; } // size_t children() const override { return 0; } const Node* child(const size_t) const override { return nullptr; } }; //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// Concrete AST nodes /// @brief A StatementList is derived from a Statement and comprises of /// combinations of multiple statements. This could represent either /// a list of statements of different types but in practice will likely /// represent a ',' separated list of the same type i.e. /// 'int i = 1, j = 1;'. /// @note Statements held by the list are guaranteed to be valid (non null). /// nullptrs added to the list are implicitly dropped. /// @todo Consider combination with Block struct StatementList : public Statement { using UniquePtr = std::unique_ptr<StatementList>; /// @brief Construct a new StatementList with an empty list StatementList() : mList() {} /// @brief Construct a new StatementList with a single statement, /// transferring ownership of the statement to the statement list /// and updating parent data on the statement. If the statement is a /// nullptr, it is ignored. /// @param statement The statement to construct from StatementList(Statement* statement) : mList() { this->addStatement(statement); } /// @brief Construct a new StatementList from a vector of statements, /// transferring ownership of all valid statements to the statement /// list and updating parent data on the statement. Only valid (non /// null) statements are added to the statement list. /// @param statements The vector of statements to construct from StatementList(const std::vector<Statement*>& statements) : mList() { for (Statement* statement : statements) { this->addStatement(statement); } } /// @brief Deep copy constructor for a StatementList, performing a deep /// copy on every held statement, ensuring parent information is /// updated. /// @param other A const reference to another statement list to deep copy StatementList(const StatementList& other) : mList() { for (const Statement::UniquePtr& stmnt : other.mList) { this->addStatement(stmnt->copy()); } } ~StatementList() override = default; /// @copybrief Node::copy() StatementList* copy() const override { return new StatementList(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::StatementListNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "statement list"; } /// @copybrief Node::subname() const char* subname() const override { return "stml"; } /// @copybrief Node::basetype() const Statement* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return this->size(); } /// @copybrief Node::child() const Statement* child(const size_t i) const override final { if (i >= mList.size()) return nullptr; return mList[i].get(); } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (mList.size() <= i) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; mList[i].reset(expr); mList[i]->setParent(this); return true; } /// @brief Alias for StatementList::children inline size_t size() const { return mList.size(); } /// @brief Adds a statement to this statement list, transferring ownership to the /// statement list and updating parent data on the statement. If the /// statement is a nullptr, it is ignored. inline void addStatement(Statement* stmnt) { if (stmnt) { mList.emplace_back(stmnt); stmnt->setParent(this); } } private: std::vector<Statement::UniquePtr> mList; }; /// @brief A Block node represents a scoped list of statements. It may comprise /// of 0 or more statements, and specifically indicates that a new scope /// is activated, typically represented by curly braces. Note that a /// block does not alway have to be encapsulated by curly braces, but /// always represents a new scope. /// @note Statements held by the block are guaranteed to be valid (non null). /// nullptrs added to the block are implicitly dropped. /// @note While closely linked, it's important to differentiate between this /// class and an llvm::BasicBlock. /// @todo Consider combination with StatementList struct Block : public Statement { using UniquePtr = std::unique_ptr<Block>; /// @brief Construct a new Block with an empty list Block() : mList() {} /// @brief Construct a new Block with a single statement, transferring /// ownership of the statement to the block and updating parent /// data on the statement. If the statement is a nullptr, it is /// ignored. /// @param statement The statement to construct from Block(Statement* statement) : mList() { this->addStatement(statement); } /// @brief Construct a new Block from a vector of statements, transferring /// ownership of all valid statements to the block and updating /// parent data on the statement. Only valid (non null) statements /// are added to the block. /// @param statements The vector of statements to construct from Block(const std::vector<Statement*>& statements) : mList() { for (Statement* statement : statements) { this->addStatement(statement); } } /// @brief Deep copy constructor for a Block, performing a deep copy on /// every held statement, ensuring parent information is updated. /// @param other A const reference to another block to deep copy Block(const Block& other) : mList() { for (const Statement::UniquePtr& stmnt : other.mList) { this->addStatement(stmnt->copy()); } } ~Block() override = default; /// @copybrief Node::copy() Block* copy() const override final { return new Block(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::BlockNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "scoped block"; } /// @copybrief Node::subname() const char* subname() const override { return "blk"; } /// @copybrief Node::basetype() const Statement* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return this->size(); } /// @copybrief Node::child() const Statement* child(const size_t i) const override final { if (i >= mList.size()) return nullptr; return mList[i].get(); } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (mList.size() <= i) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; mList[i].reset(expr); mList[i]->setParent(this); return true; } /// @brief Alias for Block::children inline size_t size() const { return mList.size(); } /// @brief Adds a statement to this block, transferring ownership to the /// block and updating parent data on the statement. If the /// statement is a nullptr, it is ignored. inline void addStatement(Statement* stmnt) { if (stmnt) { mList.emplace_back(stmnt); stmnt->setParent(this); } } private: std::vector<Statement::UniquePtr> mList; }; /// @brief A Tree is the highest concrete (non-abstract) node in the entire AX /// AST hierarchy. It represents an entire conversion of a valid AX /// string. /// @note A tree is the only node type which has typedefs for use as a shared /// pointer. All other nodes are expected to be handled through unique /// pointers to infer ownership. /// @todo Replace block with StatementList struct Tree : public Node { using Ptr = std::shared_ptr<Tree>; using ConstPtr = std::shared_ptr<const Tree>; using UniquePtr = std::unique_ptr<Tree>; /// @brief Construct a new Tree from a given Block, transferring ownership /// of the Block to the tree and updating parent data on the Block. /// @note The provided Block must be a valid pointer (non-null) /// @param block The Block to construct from Tree(Block* block = new Block()) : mBlock(block) { mBlock->setParent(this); } /// @brief Deep copy constructor for a Tree, performing a deep copy on /// the held Block, ensuring parent information is updated. /// @param other A const reference to another Tree to deep copy Tree(const Tree& other) : mBlock(new Block(*other.mBlock)) { mBlock->setParent(this); } ~Tree() override = default; /// @copybrief Node::copy() Tree* copy() const override final { return new Tree(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::TreeNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "tree"; } /// @copybrief Node::subname() const char* subname() const override { return "tree"; } /// @copybrief Node::basetype() const Node* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 1; } /// @copybrief Node::child() const Block* child(const size_t i) const override final { if (i == 0) return mBlock.get(); return nullptr; } private: Block::UniquePtr mBlock; }; struct CommaOperator : public Expression { using UniquePtr = std::unique_ptr<CommaOperator>; /// @brief Construct a new CommaOperator with an expr set CommaOperator() : mExpressions() {} /// @brief Construct a new CommaOperator with a single expression, /// transferring ownership of the expression to the CommaOperator /// and updating parent data on the expression. If the expression is /// a nullptr, it is ignored. /// @param expression The Expression to construct from CommaOperator(Expression* expression) : mExpressions() { this->append(expression); } /// @brief Construct a new CommaOperator from a vector of expression, /// transferring ownership of all valid expression to the /// CommaOperator and updating parent data on the statement. Only /// valid (non null) expression are added to the block. /// @param expressions The vector of expressions to construct from CommaOperator(const std::vector<Expression*>& expressions) : mExpressions() { mExpressions.reserve(expressions.size()); for (Expression* expression : expressions) { this->append(expression); } } /// @brief Deep copy constructor for an CommaOperator, performing a deep /// copy on every held expression, ensuring parent information is /// updated. /// @param other A const reference to another CommaOperator to deep copy CommaOperator(const CommaOperator& other) : mExpressions() { mExpressions.reserve(other.mExpressions.size()); for (const Expression::UniquePtr& expr : other.mExpressions) { this->append(expr->copy()); } } ~CommaOperator() override = default; /// @copybrief Node::copy() CommaOperator* copy() const override final { return new CommaOperator(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::CommaOperatorNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "comma"; } /// @copybrief Node::subname() const char* subname() const override { return "comma"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return this->size(); } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i >= mExpressions.size()) return nullptr; return mExpressions[i].get(); } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (mExpressions.size() <= i) return false; Expression* expr = dynamic_cast<Expression*>(node); mExpressions[i].reset(expr); mExpressions[i]->setParent(this); return true; } /// @brief Alias for CommaOperator::children inline size_t size() const { return mExpressions.size(); } /// @brief Query whether this Expression list holds any valid expressions /// @return True if this node if empty, false otherwise inline bool empty() const { return mExpressions.empty(); } /// @brief Append an expression to this CommaOperator, transferring /// ownership to the CommaOperator and updating parent data on the /// expression. If the expression is a nullptr, it is ignored. inline void append(Expression* expr) { if (expr) { mExpressions.emplace_back(expr); expr->setParent(this); } } private: std::vector<Expression::UniquePtr> mExpressions; }; /// @brief Loops represent for, while and do-while loop constructs. /// These all consist of a condition - evaluated to determine if loop /// iteration should continue, and a body which is the logic to be /// repeated. For loops also have initial statements which are evaluated /// prior to loop execution (at loop scope) and commonly used to /// set up iterators, and iteration expressions which are evaluated /// between iterations after the body and before the condition. /// Both conditions and initial statements can be declarations or /// expressions, so are Statements, and iteration expressions can /// consist of multiple expressions. The loop body is a Block defining /// its own scope (encapsulated by initial statement scope for for-loops). /// @note Only for-loops should have initial statements and/or iteration /// expressions. Also for-loops allow empty conditions to be given by /// the user, this is replaced with a 'true' expression in the parser. struct Loop : public Statement { using UniquePtr = std::unique_ptr<Loop>; /// @brief Construct a new Loop with the type defined by a /// tokens::LoopToken, a condition Statement, a Block representing /// the body and for for-loops an optional initial Statement and /// iteration Expression. Ownership of all arguments is /// transferred to the Loop. All arguments have their parent data /// updated. /// @param loopType The type of loop - for, while or do-while. /// @param condition The condition Statement to determine loop repetition /// @param body The Block to be repeated /// @param init The (optional) for-loop initial Statement. /// @param iter The (optional) for-loop iteration Expression. Loop(const tokens::LoopToken loopType, Statement* condition, Block* body, Statement* init = nullptr, Expression* iter = nullptr) : mLoopType(loopType) , mConditional(condition) , mBody(body) , mInitial(init) , mIteration(iter) { assert(mConditional); assert(mBody); mConditional->setParent(this); mBody->setParent(this); if (mInitial) { assert(mLoopType == tokens::LoopToken::FOR); mInitial->setParent(this); } if (mIteration) { assert(mLoopType == tokens::LoopToken::FOR); mIteration->setParent(this); } } /// @brief Deep copy constructor for an Loop, performing a deep copy on the /// condition, body and initial Statement/iteration Expression /// if they exist, ensuring parent information is updated. /// @param other A const reference to another Loop to deep copy Loop(const Loop& other) : mLoopType(other.mLoopType) , mConditional(other.mConditional->copy()) , mBody(other.mBody->copy()) , mInitial(other.hasInit() ? other.mInitial->copy() : nullptr) , mIteration(other.hasIter() ? other.mIteration->copy() : nullptr) { mConditional->setParent(this); mBody->setParent(this); if (mInitial) { assert(mLoopType == tokens::LoopToken::FOR); mInitial->setParent(this); } if (mIteration) { assert(mLoopType == tokens::LoopToken::FOR); mIteration->setParent(this); } } ~Loop() override = default; /// @copybrief Node::copy() Loop* copy() const override final { return new Loop(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::LoopNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "loop"; } /// @copybrief Node::subname() const char* subname() const override { return "loop"; } /// @copybrief Node::basetype() const Statement* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 4; } /// @copybrief Node::child() const Statement* child(const size_t i) const override final { if (i == 0) return mConditional.get(); if (i == 1) return mBody.get(); if (i == 2) return mInitial.get(); if (i == 3) return mIteration.get(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i == 0 || i == 2) { Statement* stmt = dynamic_cast<Statement*>(node); if (!stmt) return false; if (i == 0) { mConditional.reset(stmt); mConditional->setParent(this); } else { mInitial.reset(stmt); mInitial->setParent(this); } return true; } else if (i == 1) { Block* blk = dynamic_cast<Block*>(node); if (!blk) return false; mBody.reset(blk); mBody->setParent(this); return true; } else if (i == 3) { Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; mIteration.reset(expr); mIteration->setParent(expr); return true; } return false; } /// @brief Query the type of loop held on this node. /// @return The loop type as a tokens::LoopToken inline tokens::LoopToken loopType() const { return mLoopType; } /// @brief Query if this Loop has a valid initial statement /// @return True if a valid initial statement exists, false otherwise inline bool hasInit() const { return static_cast<bool>(this->initial()); } /// @brief Query if this Loop has a valid iteration expression list /// @return True if a valid iteration list exists, false otherwise inline bool hasIter() const { return static_cast<bool>(this->iteration()); } /// @brief Access a const pointer to the Loop condition as an abstract /// statement. /// @return A const pointer to the condition as a statement const Statement* condition() const { return mConditional.get(); } /// @brief Access a const pointer to the Loop body as a Block. /// @return A const pointer to the body Block const Block* body() const { return mBody.get(); } /// @brief Access a const pointer to the Loop initial statement as an /// abstract statement. /// @return A const pointer to the initial statement as a statement const Statement* initial() const { return mInitial.get(); } /// @brief Access a const pointer to the Loop iteration Expression /// @return A const pointer to the iteration Expression const Expression* iteration() const { return mIteration.get(); } private: const tokens::LoopToken mLoopType; Statement::UniquePtr mConditional; Block::UniquePtr mBody; Statement::UniquePtr mInitial; Expression::UniquePtr mIteration; }; /// @brief ConditionalStatements represents all combinations of 'if', 'else' /// and 'else if' syntax and semantics. A single ConditionalStatement /// only ever represents up to two branches; an 'if' (true) and an /// optional 'else' (false). ConditionalStatements are nested within /// the second 'else' branch to support 'else if' logic. As well as both /// 'if' and 'else' branches, a ConditionalStatement also holds an /// Expression related to its primary condition. /// @note The first 'if' branch is referred to as the 'true' branch. The /// second 'else' branch is referred to as the 'false' branch. struct ConditionalStatement : public Statement { using UniquePtr = std::unique_ptr<ConditionalStatement>; /// @brief Construct a new ConditionalStatement with an Expression /// representing the primary condition, a Block representing the /// 'true' branch and an optional Block representing the 'false' /// branch. Ownership of all arguments is transferred to the /// ConditionalStatement. All arguments have their parent data /// updated. /// @param conditional The Expression to construct the condition from /// @param trueBlock The Block to construct the true branch from /// @param falseBlock The (optional) Block to construct the false branch /// from ConditionalStatement(Expression* conditional, Block* trueBlock, Block* falseBlock = nullptr) : mConditional(conditional) , mTrueBranch(trueBlock) , mFalseBranch(falseBlock) { assert(mConditional); assert(mTrueBranch); mConditional->setParent(this); mTrueBranch->setParent(this); if (mFalseBranch) mFalseBranch->setParent(this); } /// @brief Deep copy constructor for an ConditionalStatement, performing a /// deep copy on the condition and both held branches (Blocks), /// ensuring parent information is updated. /// @param other A const reference to another ConditionalStatement to deep /// copy ConditionalStatement(const ConditionalStatement& other) : mConditional(other.mConditional->copy()) , mTrueBranch(other.mTrueBranch->copy()) , mFalseBranch(other.hasFalse() ? other.mFalseBranch->copy() : nullptr) { mConditional->setParent(this); mTrueBranch->setParent(this); if (mFalseBranch) mFalseBranch->setParent(this); } ~ConditionalStatement() override = default; /// @copybrief Node::copy() ConditionalStatement* copy() const override final { return new ConditionalStatement(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::ConditionalStatementNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "conditional statement"; } /// @copybrief Node::subname() const char* subname() const override { return "cond"; } /// @copybrief Node::basetype() const Statement* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 3; } /// @copybrief Node::child() const Statement* child(const size_t i) const override final { if (i == 0) return this->condition(); if (i == 1) return this->trueBranch(); if (i == 2) return this->falseBranch(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i == 0) { Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; mConditional.reset(expr); mConditional->setParent(this); return true; } else if (i == 1 || i == 2) { Block* blk = dynamic_cast<Block*>(node); if (!blk) return false; if (i == 1) { mTrueBranch.reset(blk); mTrueBranch->setParent(this); } else { mFalseBranch.reset(blk); mFalseBranch->setParent(this); } return true; } return false; } /// @brief Query if this ConditionalStatement has a valid 'false' branch /// @return True if a valid 'false' branch exists, false otherwise inline bool hasFalse() const { return static_cast<bool>(this->falseBranch()); } /// @brief Query the number of branches held by this ConditionalStatement. /// This is only ever 1 or 2. /// @return 2 if a valid 'true' and 'false' branch exist, 1 otherwise size_t branchCount() const { return this->hasFalse() ? 2 : 1; } /// @brief Access a const pointer to the ConditionalStatements condition /// as an abstract expression. /// @return A const pointer to the condition as an expression const Expression* condition() const { return mConditional.get(); } /// @brief Access a const pointer to the ConditionalStatements 'true' /// branch as a Block /// @return A const pointer to the 'true' branch const Block* trueBranch() const { return mTrueBranch.get(); } /// @brief Access a const pointer to the ConditionalStatements 'false' /// branch as a Block /// @return A const pointer to the 'false' branch const Block* falseBranch() const { return mFalseBranch.get(); } private: Expression::UniquePtr mConditional; Block::UniquePtr mTrueBranch; Block::UniquePtr mFalseBranch; }; /// @brief A BinaryOperator represents a single binary operation between a /// left hand side (LHS) and right hand side (RHS) expression. The /// operation type is stored as a tokens::OperatorToken enumerated type /// on the node. AX grammar guarantees that this token will only ever /// be a valid binary operator token type when initialized by the /// parser. struct BinaryOperator : public Expression { using UniquePtr = std::unique_ptr<BinaryOperator>; /// @brief Construct a new BinaryOperator with a given /// tokens::OperatorToken and a valid LHS and RHS expression, /// transferring ownership of the expressions to the BinaryOperator /// and updating parent data on the expressions. /// @param left The left hand side of the binary expression /// @param right The right hand side of the binary expression /// @param op The binary token representing the operation to perform. /// Should not be an assignment token. BinaryOperator(Expression* left, Expression* right, const tokens::OperatorToken op) : mLeft(left) , mRight(right) , mOperation(op) { assert(mLeft); assert(mRight); mLeft->setParent(this); mRight->setParent(this); } /// @brief Construct a new BinaryOperator with a string, delegating /// construction to the above BinaryOperator constructor. /// @param left The left hand side of the binary expression /// @param right The right hand side of the binary expression /// @param op A string representing the binary operation to perform BinaryOperator(Expression* left, Expression* right, const std::string& op) : BinaryOperator(left, right, tokens::operatorTokenFromName(op)) {} /// @brief Deep copy constructor for a BinaryOperator, performing a /// deep copy on both held expressions, ensuring parent information /// is updated. /// @param other A const reference to another BinaryOperator to deep copy BinaryOperator(const BinaryOperator& other) : mLeft(other.mLeft->copy()) , mRight(other.mRight->copy()) , mOperation(other.mOperation) { mLeft->setParent(this); mRight->setParent(this); } ~BinaryOperator() override = default; /// @copybrief Node::copy() BinaryOperator* copy() const override final { return new BinaryOperator(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::BinaryOperatorNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "binary"; } /// @copybrief Node::subname() const char* subname() const override { return "bin"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 2; } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i == 0) return mLeft.get(); if (i == 1) return mRight.get(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i > 1) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; if (i == 0) { mLeft.reset(expr); mLeft->setParent(this); } else if (i == 1) { mRight.reset(expr); mRight->setParent(this); } return true; } /// @brief Query the type of binary operation held on this node. /// @return The binary operation as a tokens::OperatorToken inline tokens::OperatorToken operation() const { return mOperation; } /// @brief Access a const pointer to the BinaryOperator LHS as an abstract /// expression /// @return A const pointer to the LHS expression const Expression* lhs() const { return mLeft.get(); } /// @brief Access a const pointer to the BinaryOperator RHS as an abstract /// expression /// @return A const pointer to the RHS expression const Expression* rhs() const { return mRight.get(); } private: Expression::UniquePtr mLeft; Expression::UniquePtr mRight; const tokens::OperatorToken mOperation; }; /// @brief A TernaryOperator represents a ternary (conditional) expression /// 'a ? b : c' which evaluates to 'b' if 'a' is true and 'c' if 'a' is false. /// Requires 'b' and 'c' to be convertibly typed expressions, or both void. /// The 'true' expression ('b') is optional with the conditional expression 'a' /// returned if it evaluates to true, otherwise returning 'c'. Note that 'a' /// will only be evaluated once in this case. struct TernaryOperator : public Expression { using UniquePtr = std::unique_ptr<TernaryOperator>; /// @brief Construct a new TernaryOperator with a conditional expression /// and true (optional) and false expressions, transferring /// ownership of the expressions to the TernaryOperator /// and updating parent data on the expressions. /// @param conditional The conditional expression determining the expression /// selection /// @param trueExpression The (optional) expression evaluated if the condition /// is true /// @param falseExpression The expression evaluated if the condition is false TernaryOperator(Expression* conditional, Expression* trueExpression, Expression* falseExpression) : mConditional(conditional) , mTrueBranch(trueExpression) , mFalseBranch(falseExpression) { assert(mConditional); assert(mFalseBranch); mConditional->setParent(this); if (mTrueBranch) mTrueBranch->setParent(this); mFalseBranch->setParent(this); } /// @brief Deep copy constructor for a TernaryOperator, performing a /// deep copy on held expressions, ensuring parent information /// is updated. /// @param other A const reference to another TernaryOperator to deep copy TernaryOperator(const TernaryOperator& other) : mConditional(other.mConditional->copy()) , mTrueBranch(other.hasTrue() ? other.mTrueBranch->copy() : nullptr) , mFalseBranch(other.mFalseBranch->copy()) { mConditional->setParent(this); if (mTrueBranch) mTrueBranch->setParent(this); mFalseBranch->setParent(this); } ~TernaryOperator() override = default; /// @copybrief Node::copy() TernaryOperator* copy() const override final { return new TernaryOperator(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::TernaryOperatorNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "ternary"; } /// @copybrief Node::subname() const char* subname() const override { return "tern"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 3; } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i == 0) return mConditional.get(); if (i == 1) return mTrueBranch.get(); if (i == 2) return mFalseBranch.get(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i > 2) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; if (i == 0) { mConditional.reset(expr); mConditional->setParent(this); } else if (i == 1) { mTrueBranch.reset(expr); mTrueBranch->setParent(this); } else if (i == 2) { mFalseBranch.reset(expr); mFalseBranch->setParent(this); } return true; } /// @brief Query whether or not this has an optional if-true branch. bool hasTrue() const { return static_cast<bool>(this->trueBranch()); } /// @brief Access a const pointer to the TernaryOperator conditional as /// an abstract expression /// @return A const pointer to the conditional expression const Expression* condition() const { return mConditional.get(); } /// @brief Access a const pointer to the TernaryOperator true expression as /// an abstract expression /// @return A const pointer to the true expression const Expression* trueBranch() const { return mTrueBranch.get(); } /// @brief Access a const pointer to the TernaryOperator false expression as /// an abstract expression /// @return A const pointer to the false expression const Expression* falseBranch() const { return mFalseBranch.get(); } private: Expression::UniquePtr mConditional; Expression::UniquePtr mTrueBranch; Expression::UniquePtr mFalseBranch; }; /// @brief AssignExpressions represents a similar object construction to a /// BinaryOperator. AssignExpressions can be chained together and are /// thus derived as Expressions rather than Statements. /// @note AssignExpressions can either be direct or compound assignments. The /// latter is represented by the last argument in the primary /// constructor which is expected to be a valid binary token. struct AssignExpression : public Expression { using UniquePtr = std::unique_ptr<AssignExpression>; /// @brief Construct a new AssignExpression with valid LHS and RHS /// expressions, transferring ownership of the expressions to the /// AssignExpression and updating parent data on the expressions. /// @param lhs The left hand side of the assign expression /// @param rhs The right hand side of the assign expression /// @param op The compound assignment token, if any AssignExpression(Expression* lhs, Expression* rhs, const tokens::OperatorToken op = tokens::EQUALS) : mLHS(lhs) , mRHS(rhs) , mOperation(op) { assert(mLHS); assert(mRHS); mLHS->setParent(this); mRHS->setParent(this); } /// @brief Deep copy constructor for an AssignExpression, performing a /// deep copy on both held expressions, ensuring parent information /// is updated. /// @param other A const reference to another AssignExpression to deep /// copy AssignExpression(const AssignExpression& other) : mLHS(other.mLHS->copy()) , mRHS(other.mRHS->copy()) , mOperation(other.mOperation) { mLHS->setParent(this); mRHS->setParent(this); } ~AssignExpression() override = default; /// @copybrief Node::copy() AssignExpression* copy() const override final { return new AssignExpression(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::AssignExpressionNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "assignment expression"; } /// @copybrief Node::subname() const char* subname() const override { return "asgn"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 2; } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i == 0) return this->lhs(); if (i == 1) return this->rhs(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i > 1) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; if (i == 0) { mLHS.reset(expr); mLHS->setParent(this); } else if (i == 1) { mRHS.reset(expr); mRHS->setParent(this); } return true; } /// @brief Query whether or not this is a compound AssignExpression. /// Compound AssignExpressions are assignments which read and write /// to the LHS value. i.e. +=, -=, *= etc /// @return The binary operation as a tokens::OperatorToken inline bool isCompound() const { return mOperation != tokens::EQUALS; } /// @brief Query the actual operational type of this AssignExpression. For /// simple (non-compound) AssignExpressions, tokens::EQUALS is /// returned. inline tokens::OperatorToken operation() const { return mOperation; } /// @brief Access a const pointer to the AssignExpression LHS as an /// abstract expression /// @return A const pointer to the LHS expression const Expression* lhs() const { return mLHS.get(); } /// @brief Access a const pointer to the AssignExpression RHS as an //// abstract expression /// @return A const pointer to the RHS expression const Expression* rhs() const { return mRHS.get(); } private: Expression::UniquePtr mLHS; Expression::UniquePtr mRHS; const tokens::OperatorToken mOperation; }; /// @brief A Crement node represents a single increment '++' and decrement '--' /// operation. As well as it's crement type, it also stores whether /// the semantics constructed a post or pre-crement i.e. ++a or a++. struct Crement : public Expression { using UniquePtr = std::unique_ptr<Crement>; /// @brief A simple enum representing the crement type. enum Operation { Increment, Decrement }; /// @brief Construct a new Crement with a valid expression, transferring /// ownership of the expression to the Crement node and updating /// parent data on the expression. /// @param expr The expression to crement /// @param op The type of crement operation; Increment or Decrement /// @param post True if the crement operation is a post crement i.e. a++, /// false if the operation is a pre crement i.e. ++a Crement(Expression* expr, const Operation op, bool post) : mExpression(expr) , mOperation(op) , mPost(post) { mExpression->setParent(this); } /// @brief Deep copy constructor for a Crement, performing a deep copy on /// the underlying expressions, ensuring parent information is /// updated. /// @param other A const reference to another Crement to deep copy Crement(const Crement& other) : mExpression(other.mExpression->copy()) , mOperation(other.mOperation) , mPost(other.mPost) { mExpression->setParent(this); } ~Crement() override = default; /// @copybrief Node::copy() Crement* copy() const override final { return new Crement(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::CrementNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "crement"; } /// @copybrief Node::subname() const char* subname() const override { return "crmt"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } // /// @copybrief Node::children() size_t children() const override final { return 1; } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i == 0) return this->expression(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i != 0) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; mExpression.reset(expr); mExpression->setParent(this); return true; } /// @brief Query the type of the Crement operation. This does not hold /// post or pre-crement information. /// @return The Crement operation being performed. This is either an /// Crement::Increment or Crement::Decrement. inline Operation operation() const { return mOperation; } /// @brief Query if this Crement node represents an incrementation ++ /// @return True if this node is performing an increment inline bool increment() const { return mOperation == Increment; } /// @brief Query if this Crement node represents an decrement -- /// @return True if this node is performing an decrement inline bool decrement() const { return mOperation == Decrement; } /// @brief Query if this Crement node represents a pre crement ++a /// @return True if this node is performing a pre crement inline bool pre() const { return !mPost; } /// @brief Query if this Crement node represents a post crement a++ /// @return True if this node is performing a post crement inline bool post() const { return mPost; } /// @brief Access a const pointer to the expression being crements as an /// abstract Expression /// @return A const pointer to the expression const Expression* expression() const { return mExpression.get(); } private: Expression::UniquePtr mExpression; const Operation mOperation; const bool mPost; }; /// @brief A UnaryOperator represents a single unary operation on an /// expression. The operation type is stored as a tokens::OperatorToken /// enumerated type on the node. AX grammar guarantees that this token /// will only every be a valid unary operator token type when /// initialized by the parser. struct UnaryOperator : public Expression { using UniquePtr = std::unique_ptr<UnaryOperator>; /// @brief Construct a new UnaryOperator with a given tokens::OperatorToken /// and a valid expression, transferring ownership of the expression /// to the UnaryOperator and updating parent data on the expression. /// @param expr The expression to perform the unary operator on /// @param op The unary token representing the operation to perform. UnaryOperator(Expression* expr, const tokens::OperatorToken op) : mExpression(expr) , mOperation(op) { assert(mExpression); mExpression->setParent(this); } /// @brief Construct a new UnaryOperator with a string, delegating /// construction to the above UnaryOperator constructor. /// @param op A string representing the unary operation to perform /// @param expr The expression to perform the unary operator on UnaryOperator(Expression* expr, const std::string& op) : UnaryOperator(expr, tokens::operatorTokenFromName(op)) {} /// @brief Deep copy constructor for a UnaryOperator, performing a deep /// copy on the underlying expressions, ensuring parent information /// is updated. /// @param other A const reference to another UnaryOperator to deep copy UnaryOperator(const UnaryOperator& other) : mExpression(other.mExpression->copy()) , mOperation(other.mOperation) { mExpression->setParent(this); } ~UnaryOperator() override = default; /// @copybrief Node::copy() UnaryOperator* copy() const override final { return new UnaryOperator(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::UnaryOperatorNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "unary"; } /// @copybrief Node::subname() const char* subname() const override { return "unry"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 1; } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i == 0) return this->expression(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i != 0) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; mExpression.reset(expr); mExpression->setParent(this); return true; } /// @brief Query the type of unary operation held on this node. /// @return The unary operation as a tokens::OperatorToken inline tokens::OperatorToken operation() const { return mOperation; } /// @brief Access a const pointer to the UnaryOperator expression as an /// abstract expression /// @return A const pointer to the expression const Expression* expression() const { return mExpression.get(); } private: Expression::UniquePtr mExpression; const tokens::OperatorToken mOperation; }; /// @brief Cast nodes represent the conversion of an underlying expression to /// a target type. Cast nodes are typically constructed from functional /// notation and do not represent construction of the target type, /// rather a type-casted conversion. struct Cast : public Expression { using UniquePtr = std::unique_ptr<Cast>; /// @brief Construct a new Cast with a valid expression and a target /// tokens::CoreType, transferring ownership of the expression to /// the Cast and updating parent data on the expression. /// @param expr The expression to perform the cast operator on /// @param type The target cast type Cast(Expression* expr, const tokens::CoreType type) : Expression() , mType(type) , mExpression(expr) { assert(mExpression); mExpression->setParent(this); } /// @brief Deep copy constructor for a Cast node, performing a deep copy on /// the underlying expressions, ensuring parent information is /// updated. /// @param other A const reference to another Cast node to deep copy Cast(const Cast& other) : Expression() , mType(other.mType) , mExpression(other.mExpression->copy()) { mExpression->setParent(this); } ~Cast() override = default; /// @copybrief Node::copy() Cast* copy() const override final { return new Cast(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::CastNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "cast"; } /// @copybrief Node::subname() const char* subname() const override { return "cast"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 1; } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i == 0) return this->expression(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i != 0) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; mExpression.reset(expr); mExpression->setParent(this); return true; } /// @brief Access to the target type /// @return a tokens::CoreType enumerable type therepresenting the target type inline tokens::CoreType type() const { return mType; } /// @brief Get the target type as a front end AX type/token string /// @note This returns the associated token to the type, not necessarily /// equal to the OpenVDB type string /// @return A string representing the type/token inline std::string typestr() const { return ast::tokens::typeStringFromToken(mType); } /// @brief Access a const pointer to the Cast node's expression as an /// abstract expression /// @return A const pointer to the expression const Expression* expression() const { return mExpression.get(); } private: const tokens::CoreType mType; Expression::UniquePtr mExpression; }; /// @brief FunctionCalls represent a single call to a function and any provided /// arguments. The argument list can be empty. The function name is /// expected to exist in the AX function registry. struct FunctionCall : public Expression { using UniquePtr = std::unique_ptr<FunctionCall>; /// @brief Construct a new FunctionCall with a given function identifier /// and an optional argument, transferring ownership of any /// provided argument to the FunctionCall and updating parent data /// on the arguments. /// @param function The name/identifier of the function /// @param argument Function argument FunctionCall(const std::string& function, Expression* argument = nullptr) : mFunctionName(function) , mArguments() { this->append(argument); } /// @brief Construct a new FunctionCall with a given function identifier /// and optional argument list, transferring ownership of any /// provided arguments to the FunctionCall and updating parent data /// on the arguments. /// @param function The name/identifier of the function /// @param arguments Function arguments FunctionCall(const std::string& function, const std::vector<Expression*>& arguments) : mFunctionName(function) , mArguments() { mArguments.reserve(arguments.size()); for (Expression* arg : arguments) { this->append(arg); } } /// @brief Deep copy constructor for a FunctionCall, performing a deep copy /// on all held function arguments, ensuring parent information is /// updated. /// @param other A const reference to another FunctionCall to deep copy FunctionCall(const FunctionCall& other) : mFunctionName(other.mFunctionName) , mArguments() { mArguments.reserve(other.mArguments.size()); for (const Expression::UniquePtr& expr : other.mArguments) { this->append(expr->copy()); } } ~FunctionCall() override = default; /// @copybrief Node::copy() FunctionCall* copy() const override final { return new FunctionCall(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::FunctionCallNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "function call"; } /// @copybrief Node::subname() const char* subname() const override { return "call"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return this->size(); } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i >= mArguments.size()) return nullptr; return mArguments[i].get(); } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (mArguments.size() <= i) return false; Expression* expr = dynamic_cast<Expression*>(node); mArguments[i].reset(expr); mArguments[i]->setParent(this); return true; } /// @brief Access the function name/identifier /// @return A const reference to the function name inline const std::string& name() const { return mFunctionName; } /// @brief Query the total number of arguments stored on this function /// @return The number of arguments. Can be 0 inline size_t numArgs() const { return mArguments.size(); } /// @brief Alias for FunctionCall::children inline size_t size() const { return mArguments.size(); } /// @brief Query whether this Expression list holds any valid expressions /// @return True if this node if empty, false otherwise inline bool empty() const { return mArguments.empty(); } /// @brief Appends an argument to this function call, transferring /// ownership to the FunctionCall and updating parent data on the /// expression. If the expression is a nullptr, it is ignored. inline void append(Expression* expr) { if (expr) { mArguments.emplace_back(expr); expr->setParent(this); } } private: const std::string mFunctionName; std::vector<Expression::UniquePtr> mArguments; }; /// @brief Keywords represent keyword statements defining changes in execution. /// These include those that define changes in loop execution such as /// break and continue, as well as return statements. struct Keyword : public Statement { using UniquePtr = std::unique_ptr<Keyword>; /// @brief Construct a new Keyword with a given tokens::KeywordToken. /// @param keyw The keyword token. Keyword(const tokens::KeywordToken keyw) : mKeyword(keyw) {} /// @brief Deep copy constructor for a Keyword. /// @param other A const reference to another Keyword to deep copy Keyword(const Keyword& other) : mKeyword(other.mKeyword) {} ~Keyword() override = default; /// @copybrief Node::copy() Keyword* copy() const override final { return new Keyword(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::KeywordNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "keyword"; } /// @copybrief Node::subname() const char* subname() const override { return "keyw"; } /// @copybrief Node::basetype() const Statement* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 0; } /// @copybrief Node::child() const Node* child(const size_t) const override final { return nullptr; } /// @brief Query the keyword held on this node. /// @return The keyword as a tokens::KeywordToken inline tokens::KeywordToken keyword() const { return mKeyword; } private: const tokens::KeywordToken mKeyword; }; /// @brief ArrayUnpack represent indexing operations into AX container types, /// primarily vectors and matrices indexed by the square brackets [] /// syntax. Multiple levels of indirection (multiple components) can /// be specified but current construction is limited to either a single /// or double component lookup. Providing two components infers a matrix /// indexing operation. /// @note Single indexing operations are still valid for matrix indexing struct ArrayUnpack : public Expression { using UniquePtr = std::unique_ptr<ArrayUnpack>; /// @brief Construct a new ArrayUnpack with a valid expression, an initial /// component (as an expression) to the first access and an optional /// second component (as an expression) to a second access. /// @note Providing a second component automatically infers this /// ArrayUnpack as a matrix indexing operation. Ownership is /// transferred and parent data is updated for all arguments. /// @param expr The expression to perform the unpacking operation on /// @param component0 The first component access /// @param component1 The second component access ArrayUnpack(Expression* expr, Expression* component0, Expression* component1 = nullptr) : mIdx0(component0) , mIdx1(component1) , mExpression(expr) { assert(mIdx0); assert(mExpression); mIdx0->setParent(this); if(mIdx1) mIdx1->setParent(this); mExpression->setParent(this); } /// @brief Deep copy constructor for a ArrayUnpack, performing a deep /// copy on the expression being indexed and all held components, /// ensuring parent information is updated. /// @param other A const reference to another ArrayUnpack to deep copy ArrayUnpack(const ArrayUnpack& other) : ArrayUnpack(other.mExpression->copy(), other.mIdx0->copy(), other.mIdx1 ? other.mIdx1->copy() : nullptr) {} ~ArrayUnpack() override = default; /// @copybrief Node::copy() ArrayUnpack* copy() const override final { return new ArrayUnpack(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::ArrayUnpackNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "array unpack"; } /// @copybrief Node::subname() const char* subname() const override { return "unpk"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 3; } /// @copybrief Node::child() const Statement* child(const size_t i) const override final { if (i == 0) return this->component0(); if (i == 1) return this->component1(); if (i == 2) return this->expression(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i > 2) return false; Expression* expr = dynamic_cast<Expression*>(node); if (!expr) return false; if (i == 0) mIdx0.reset(expr); if (i == 1) mIdx1.reset(expr); if (i == 2) mExpression.reset(expr); expr->setParent(this); return true; } /// @brief Access a const pointer to the first component being used as an /// abstract Expression /// @return A const pointer to the first component inline const Expression* component0() const { return mIdx0.get(); } /// @brief Access a const pointer to the second component being used as an /// abstract Expression /// @note This can be a nullptr for single indexing operations /// @return A const pointer to the second component inline const Expression* component1() const { return mIdx1.get(); } /// @brief Access a const pointer to the expression being indexed as an /// abstract Expression /// @return A const pointer to the expression inline const Expression* expression() const { return mExpression.get(); } /// @brief Query whether this ArrayUnpack operation must be a matrix /// indexing operation by checking the presence of a second /// component access. /// @note This method only guarantees that the indexing operation must be /// a matrix index. Single indexing is also valid for matrices and /// other multi dimensional containers /// @return True if this is a double indexing operation, only valid for /// matrices inline bool isMatrixIndex() const { // assumes that component0 is always valid return static_cast<bool>(this->component1()); } private: Expression::UniquePtr mIdx0, mIdx1; Expression::UniquePtr mExpression; }; /// @brief ArrayPacks represent temporary container creations of arbitrary /// sizes, typically generated through the use of curly braces {}. struct ArrayPack : public Expression { using UniquePtr = std::unique_ptr<ArrayPack>; /// @brief Construct a new ArrayPack with a single expression, transferring /// ownership of the expression to the ArrayPack and updating parent /// data on the expression. If the expression is a nullptr, it is /// ignored. /// @param expression The Expression to construct from ArrayPack(Expression* expression) : mExpressions() { this->append(expression); } /// @brief Construct a new ArrayPack transferring ownership of any /// provided arguments to the ArrayPack and updating parent data /// on the arguments. /// @param arguments ArrayPack arguments ArrayPack(const std::vector<Expression*>& arguments) : mExpressions() { mExpressions.reserve(arguments.size()); for (Expression* arg : arguments) { this->append(arg); } } /// @brief Deep copy constructor for a ArrayPack, performing a deep copy /// on all held arguments, ensuring parent information is updated. /// @param other A const reference to another ArrayPack to deep copy ArrayPack(const ArrayPack& other) : mExpressions() { mExpressions.reserve(other.mExpressions.size()); for (const Expression::UniquePtr& expr : other.mExpressions) { this->append(expr->copy()); } } ~ArrayPack() override = default; /// @copybrief Node::copy() ArrayPack* copy() const override final { return new ArrayPack(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::ArrayPackNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "array pack"; } /// @copybrief Node::subname() const char* subname() const override { return "pack"; } /// @copybrief Node::basetype() const Expression* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return this->size(); } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i >= mExpressions.size()) return nullptr; return mExpressions[i].get(); } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (mExpressions.size() <= i) return false; Expression* expr = dynamic_cast<Expression*>(node); mExpressions[i].reset(expr); mExpressions[i]->setParent(this); return true; } /// @brief Alias for ArrayPack::children inline size_t size() const { return mExpressions.size(); } /// @brief Query whether this Expression list holds any valid expressions /// @return True if this node if empty, false otherwise inline bool empty() const { return mExpressions.empty(); } /// @brief Appends an argument to this ArrayPack, transferring ownership /// to the ArrayPack and updating parent data on the expression. /// If the expression is a nullptr, it is ignored. inline void append(Expression* expr) { if (expr) { mExpressions.emplace_back(expr); expr->setParent(this); } } private: std::vector<Expression::UniquePtr> mExpressions; }; /// @brief Attributes represent any access to a primitive value, typically /// associated with the '@' symbol syntax. Note that the AST does not /// store any additional information on the given attribute other than /// its name and type, which together form a unique Attribute identifier /// known as the Attribute 'token'. A 'primitive value' in this instance /// refers to a value on an OpenVDB Volume or OpenVDB Points tree. /// @note The ExternalVariable AST node works in a similar way /// @note An Attribute is a complete "leaf-level" AST node. It has no children /// and nothing derives from it. struct Attribute : public Variable { using UniquePtr = std::unique_ptr<Attribute>; /// @brief Construct a new Attribute with a given name and type. Optionally /// also mark it as inferred type creation (no type was directly /// specified) /// @param name The name of the attribute /// @param type The type of the attribute /// @param inferred Whether the provided type was directly specified /// (false). Attribute(const std::string& name, const tokens::CoreType type, const bool inferred = false) : Variable(name) , mType(type) , mTypeInferred(inferred) {} /// @brief Construct a new Attribute with a given name and type/token /// string, delegating construction to the above Attribute /// constructor. /// @param name The name of the attribute /// @param token The type/token string of the attribute /// @param inferred Whether the provided type was directly specified /// (false). Attribute(const std::string& name, const std::string& token, const bool inferred = false) : Attribute(name, tokens::tokenFromTypeString(token), inferred) {} /// @brief Deep copy constructor for a Attribute /// @note No parent information needs updating as an Attribute is a /// "leaf level" node (contains no children) /// @param other A const reference to another Attribute to deep copy Attribute(const Attribute& other) : Variable(other) , mType(other.mType) , mTypeInferred(other.mTypeInferred) {} ~Attribute() override = default; /// @copybrief Node::copy() Attribute* copy() const override final { return new Attribute(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::AttributeNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "attribute"; } /// @copybrief Node::subname() const char* subname() const override { return "atr"; } /// @copybrief Node::basetype() const Variable* basetype() const override { return this; } /// @brief Query whether this attribute was accessed via inferred syntax /// i.e. \@P or \@myattribute /// @return True if inferred syntax was used inline bool inferred() const { return mTypeInferred; } /// @brief Access the type that was used to access this attribute /// @return The type used to access this attribute as a tokens::CoreType inline tokens::CoreType type() const { return mType; } /// @brief Get the access type as a front end AX type/token string /// @note This returns the associated token to the type, not necessarily /// equal to the OpenVDB type string /// @return A string representing the type/token inline std::string typestr() const { return ast::tokens::typeStringFromToken(mType); } /// @brief Construct and return the full attribute token identifier. See /// Attribute::tokenFromNameType /// @return A string representing the attribute token. inline std::string tokenname() const { return Attribute::tokenFromNameType(this->name(), this->type()); } /// @brief Static method returning the symbol associated with an Attribute /// access as defined by AX Grammar /// @return The '@' character as a char static inline char symbolseparator() { return '@'; } /// @brief Static method returning the full unique attribute token /// identifier by consolidating its name and type such that /// token = tokenstr + '\@' + name, where tokenstr is the AX type /// token as a string, converted from the provided CoreType. /// @note This identifier is unique for accesses to the same attribute /// @note Due to inferred and single character accesses in AX, this return /// value does not necessarily represent the original syntax used to /// access this attribute. For example, \@myattrib will be stored /// and returned as float\@myattrib. /// @param name The name of the attribute /// @param type The CoreType of the attribute /// @return A string representing the attribute token. static inline std::string tokenFromNameType(const std::string& name, const tokens::CoreType type) { return ast::tokens::typeStringFromToken(type) + Attribute::symbolseparator() + name; } /// @brief Static method which splits a valid attribute token into its name /// and type counterparts. If the token cannot be split, neither /// name or type are updated and false is returned. /// @param token The token to split. /// @param name Set to the second part of the attribute token, /// representing the name. If a nullptr, it is ignored /// @param type Set to the first part of the attribute token, /// representing the type. If a nullptr, it is ignored. Note /// that this can be empty if the attribute token has an /// inferred type or a single character. /// @return True if the provided attribute token could be split static inline bool nametypeFromToken(const std::string& token, std::string* name, std::string* type) { const size_t at = token.find(symbolseparator()); if (at == std::string::npos) return false; if (type) { *type = token.substr(0, at); if (type->empty()) { *type = ast::tokens::typeStringFromToken(tokens::CoreType::FLOAT); } } if (name) *name = token.substr(at + 1, token.size()); return true; } private: const tokens::CoreType mType; const bool mTypeInferred; }; /// @brief ExternalVariable represent any access to external (custom) data, /// typically associated with the '$' symbol syntax. Note that the AST /// does not store any additional information on the given external /// other than its name and type, which together form a unique external /// identifier known as the ExternalVariable 'token'. This token is used /// by the compiler to map user provided values to these external /// values. /// @note The Attribute AST node works in a similar way /// @note An ExternalVariable is a complete "leaf-level" AST node. It has no /// children and nothing derives from it. struct ExternalVariable : public Variable { using UniquePtr = std::unique_ptr<ExternalVariable>; /// @brief Construct a new ExternalVariable with a given name and type /// @param name The name of the attribute /// @param type The type of the attribute ExternalVariable(const std::string& name, const tokens::CoreType type) : Variable(name) , mType(type) {} /// @brief Construct a new ExternalVariable with a given name and type/token /// string, delegating construction to the above ExternalVariable /// constructor. /// @param name The name of the attribute /// @param token The type/token string of the attribute ExternalVariable(const std::string& name, const std::string& token) : ExternalVariable(name, tokens::tokenFromTypeString(token)) {} /// @brief Deep copy constructor for a ExternalVariable /// @note No parent information needs updating as an ExternalVariable is a /// "leaf level" node (contains no children) /// @param other A const reference to another ExternalVariable to deep /// copy ExternalVariable(const ExternalVariable& other) : Variable(other) , mType(other.mType) {} ~ExternalVariable() override = default; /// @copybrief Node::copy() ExternalVariable* copy() const override final { return new ExternalVariable(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::ExternalVariableNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "external"; } /// @copybrief Node::subname() const char* subname() const override { return "ext"; } /// @copybrief Node::basetype() const Variable* basetype() const override { return this; } /// @brief Access the type that was used to access this external variable /// @return The type used to access this external as a tokens::CoreType inline tokens::CoreType type() const { return mType; } /// @brief Get the access type as a front end AX type/token string /// @note This returns the associated token to the type, not necessarily /// equal to the OpenVDB type string /// @return A string representing the type/token inline std::string typestr() const { return ast::tokens::typeStringFromToken(mType); } /// @brief Construct and return the full external token identifier. See /// ExternalVariable::tokenFromNameType /// @return A string representing the external variable token. inline const std::string tokenname() const { return ExternalVariable::tokenFromNameType(this->name(), this->type()); } /// @brief Static method returning the symbol associated with an /// ExternalVariable access as defined by AX Grammar /// @return The '$' character as a char static inline char symbolseparator() { return '$'; } /// @brief Static method returning the full unique external token /// identifier by consolidating its name and type such that /// token = tokenstr + '$' + name, where tokenstr is the AX type /// token as a string, converted from the provided CoreType. /// @note This identifier is unique for accesses to the same external /// @note Due to inferred and single character accesses in AX, this return /// value does not necessarily represent the original syntax used to /// access this external. For example, v$data will be stored and /// returned as vec3f$data. /// @param name The name of the external /// @param type The CoreType of the external /// @return A string representing the external token. static inline std::string tokenFromNameType(const std::string& name, const tokens::CoreType type) { return ast::tokens::typeStringFromToken(type) + ExternalVariable::symbolseparator() + name; } /// @brief Static method which splits a valid external token into its name /// and type counterparts. If the token cannot be split, neither /// name or type are updated and false is returned. /// @param token The token to split. /// @param name Set to the second part of the external token, /// representing the name. If a nullptr, it is ignored /// @param type Set to the first part of the external token, /// representing the type. If a nullptr, it is ignored. Note /// that this can be empty if the external token has an /// inferred type or a single character. /// @return True if the provided external token could be split static inline bool nametypeFromToken(const std::string& token, std::string* name, std::string* type) { const size_t at = token.find(symbolseparator()); if (at == std::string::npos) return false; if (type) { *type = token.substr(0, at); if (type->empty()) { *type = ast::tokens::typeStringFromToken(tokens::CoreType::FLOAT); } } if (name) *name = token.substr(at + 1, token.size()); return true; } private: const tokens::CoreType mType; }; /// @brief Local AST nodes represent a single accesses to a local variable. /// The only store the name of the variable being accessed. /// @note A Local is a complete "leaf-level" AST node. It has no children and /// nothing derives from it. struct Local : public Variable { using UniquePtr = std::unique_ptr<Local>; /// @brief Construct a Local with a given name /// @param name The name of the local variable being accessed Local(const std::string& name) : Variable(name) {} ~Local() override = default; /// @copybrief Node::copy() Local* copy() const override final { return new Local(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::LocalNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "local"; } /// @copybrief Node::subname() const char* subname() const override { return "lcl"; } /// @copybrief Node::basetype() const Variable* basetype() const override { return this; } }; /// @brief DeclareLocal AST nodes symbolize a single type declaration of a /// local variable. These store the local variables that They also however store its /// specified type. These have the important distinction of representing /// the initial creation and allocation of a variable, in comparison to /// a Local node which only represents access. struct DeclareLocal : public Statement { using UniquePtr = std::unique_ptr<DeclareLocal>; /// @brief Construct a new DeclareLocal with a given name and type /// @param type The type of the declaration /// @param local The local variable being declared /// @param init The initialiser expression of the local DeclareLocal(const tokens::CoreType type, Local* local, Expression* init = nullptr) : mType(type) , mLocal(local) , mInit(init) { assert(mLocal); mLocal->setParent(this); if (mInit) mInit->setParent(this); } /// @brief Deep copy constructor for a DeclareLocal /// @note No parent information needs updating as an DeclareLocal is a /// "leaf level" node (contains no children) /// @param other A const reference to another DeclareLocal to deep copy DeclareLocal(const DeclareLocal& other) : mType(other.mType) , mLocal(other.mLocal->copy()) , mInit(other.hasInit() ? other.mInit->copy() : nullptr) { mLocal->setParent(this); if (mInit) mInit->setParent(this); } ~DeclareLocal() override = default; /// @copybrief Node::copy() DeclareLocal* copy() const override final { return new DeclareLocal(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { return Node::DeclareLocalNode; } /// @copybrief Node::nodename() const char* nodename() const override { return "declaration"; } /// @copybrief Node::subname() const char* subname() const override { return "dcl"; } /// @copybrief Node::basetype() const Statement* basetype() const override { return this; } /// @copybrief Node::children() size_t children() const override final { return 2; } /// @copybrief Node::child() const Expression* child(const size_t i) const override final { if (i == 0) return this->local(); if (i == 1) return this->init(); return nullptr; } /// @copybrief Node::replacechild() inline bool replacechild(const size_t i, Node* node) override final { if (i > 1) return false; if (i == 0) { Local* local = dynamic_cast<Local*>(node); if (!local) return false; mLocal.reset(local); mLocal->setParent(this); } else { Expression* init = dynamic_cast<Expression*>(node); if (!init) return false; mInit.reset(init); mInit->setParent(this); } return true; } /// @brief Access the type that was specified at which to create the given /// local /// @return The declaration type inline tokens::CoreType type() const { return mType; } /// @brief Get the declaration type as a front end AX type/token string /// @note This returns the associated token to the type, not necessarily /// equal to the OpenVDB type string /// @return A string representing the type/token inline std::string typestr() const { return ast::tokens::typeStringFromToken(mType); } /// @brief Query if this declaration has an initialiser /// @return True if an initialiser exists, false otherwise inline bool hasInit() const { return static_cast<bool>(this->init()); } /// @brief Access a const pointer to the Local /// @return A const pointer to the local const Local* local() const { return mLocal.get(); } /// @brief Access a const pointer to the initialiser /// @return A const pointer to the initialiser const Expression* init() const { return mInit.get(); } private: const tokens::CoreType mType; Local::UniquePtr mLocal; // could be Variable for attribute declaration Expression::UniquePtr mInit; }; /// @brief A Value (literal) AST node holds either literal text or absolute /// value information on all numerical, string and boolean constants. /// A single instance of a Value is templated on the requested scalar, /// boolean or string type. If scalar or boolean value is constructed /// from a string (as typically is the case in the parser), the value is /// automatically converted to its numerical representation. If this /// fails, the original text is stored instead. /// @note All numerical values are stored as their highest possible precision /// type to support overflowing without storing the original string /// data. The original string data is only required if the value is too /// large to be stored in these highest precision types (usually a /// uint64_t for scalars or double for floating points). /// @note Numerical values are guaranteed to be positive (if constructed from /// the AX parser). Negative values are represented by a combination of /// a UnaryOperator holding a Value AST node. /// @note Note that Value AST nodes representing strings are specialized and /// are guranteed to be "well-formed" (there is no numerical conversion) /// @note A Value is a complete "leaf-level" AST node. It has no children and /// nothing derives from it. template <typename T> struct Value : public ValueBase { using UniquePtr = std::unique_ptr<Value<T>>; using Type = T; /// @brief Integers and Floats store their value as ContainerType, which is /// guaranteed to be at least large enough to represent the maximum /// possible supported type for the requested precision. using ContainerType = typename std::conditional< std::is_integral<T>::value, uint64_t, T>::type; /// @brief The list of supported numerical constants. /// @note Strings are specialized and handled separately static constexpr bool IsSupported = std::is_same<T, bool>::value || std::is_same<T, int16_t>::value || std::is_same<T, int32_t>::value || std::is_same<T, int64_t>::value || std::is_same<T, float>::value || std::is_same<T, double>::value; static_assert(IsSupported, "Incompatible ast::Value node instantiated."); /// @brief Directly construct a Value from a source integer, float or /// boolean, guaranteeing valid construction. Note that the provided /// argument should not be negative Value(const ContainerType value) : mValue(value) {} /// @brief Deep copy constructor for a Value /// @note No parent information needs updating as a Value is a "leaf /// level" node (contains no children) /// @param other A const reference to another Value to deep copy Value(const Value<T>& other) : mValue(other.mValue) {} ~Value() override = default; /// @copybrief Node::copy() Value<Type>* copy() const override final { return new Value<Type>(*this); } /// @copybrief Node::nodetype() NodeType nodetype() const override { if (std::is_same<T, bool>::value) return Node::ValueBoolNode; if (std::is_same<T, int16_t>::value) return Node::ValueInt16Node; if (std::is_same<T, int32_t>::value) return Node::ValueInt32Node; if (std::is_same<T, int64_t>::value) return Node::ValueInt64Node; if (std::is_same<T, float>::value) return Node::ValueFloatNode; if (std::is_same<T, double>::value) return Node::ValueDoubleNode; } /// @copybrief Node::nodename() const char* nodename() const override { if (std::is_same<T, bool>::value) return "boolean literal"; if (std::is_same<T, int16_t>::value) return "int16 literal"; if (std::is_same<T, int32_t>::value) return "int32 literal"; if (std::is_same<T, int64_t>::value) return "int64 literal"; if (std::is_same<T, float>::value) return "float (32bit) literal"; if (std::is_same<T, double>::value) return "double (64bit) literal"; } /// @copybrief Node::subname() const char* subname() const override { if (std::is_same<T, bool>::value) return "bool"; if (std::is_same<T, int16_t>::value) return "i16"; if (std::is_same<T, int32_t>::value) return "i32"; if (std::is_same<T, int64_t>::value) return "i64"; if (std::is_same<T, float>::value) return "flt"; if (std::is_same<T, double>::value) return "dbl"; } /// @copybrief Node::basetype() const ValueBase* basetype() const override { return this; } /// @brief Access the value as its stored type /// @return The value as its stored ContainerType inline ContainerType asContainerType() const { return mValue; } /// @brief Access the value as its requested (templated) type /// @return The value as its templed type T inline T value() const { return static_cast<T>(mValue); } private: // A container of a max size defined by LiteralValueContainer to hold values // which may be out of scope. This is only used for warnings const ContainerType mValue; }; /// @brief Specialization of Values for strings template <> struct Value<std::string> : public ValueBase { using UniquePtr = std::unique_ptr<Value<std::string>>; using Type = std::string; /// @brief Construct a new Value string from a string /// @param value The string to copy onto this Value Value(const Type& value) : mValue(value) {} /// @brief Deep copy constructor for a Value string /// @note No parent information needs updating as a Value is a "leaf /// level" node (contains no children) /// @param other A const reference to another Value string to deep copy Value(const Value<Type>& other) : mValue(other.mValue) {} ~Value() override = default; Value<Type>* copy() const override final { return new Value<Type>(*this); } NodeType nodetype() const override { return Node::ValueStrNode; } const char* nodename() const override { return "string value"; } const char* subname() const override { return "str"; } const ValueBase* basetype() const override { return this; } /// @brief Access the string /// @return A const reference to the string inline const std::string& value() const { return mValue; } private: const Type mValue; }; // fwd declaration for backwards compatibility, see Parse.h/.cc for definition openvdb::ax::ast::Tree::Ptr parse(const char* code); } // namespace ast } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_AST_HAS_BEEN_INCLUDED
105,414
C
43.422672
92
0.633369
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/grammar/generated/axparser.cc
/* A Bison parser, made by GNU Bison 3.0.5. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.0.5" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* "%code top" blocks. */ #include "openvdb_ax/ast/AST.h" #include "openvdb_ax/ast/Parse.h" #include "openvdb_ax/ast/Tokens.h" #include "openvdb_ax/compiler/Logger.h" #include <openvdb/Platform.h> // for OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN #include <vector> /// @note Bypasses bison conversion warnings in yyparse OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN extern int axlex(); extern openvdb::ax::Logger* axlog; using namespace openvdb::ax::ast; using namespace openvdb::ax; void axerror(Tree** tree, const char* s); using ExpList = std::vector<openvdb::ax::ast::Expression*>; /* Substitute the type names. */ #define YYSTYPE AXSTYPE #define YYLTYPE AXLTYPE /* Substitute the variable and function names. */ #define yyparse axparse #define yylex axlex #define yyerror axerror #define yydebug axdebug #define yynerrs axnerrs #define yylval axlval #define yychar axchar #define yylloc axlloc /* Copy the first part of user declarations. */ # ifndef YY_NULLPTR # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* In a future release of Bison, this section will be replaced by #include "axparser.h". */ #ifndef YY_AX_OPENVDB_AX_GRAMMAR_AXPARSER_H_INCLUDED # define YY_AX_OPENVDB_AX_GRAMMAR_AXPARSER_H_INCLUDED /* Debug traces. */ #ifndef AXDEBUG # if defined YYDEBUG #if YYDEBUG # define AXDEBUG 1 # else # define AXDEBUG 0 # endif # else /* ! defined YYDEBUG */ # define AXDEBUG 0 # endif /* ! defined YYDEBUG */ #endif /* ! defined AXDEBUG */ #if AXDEBUG extern int axdebug; #endif /* Token type. */ #ifndef AXTOKENTYPE # define AXTOKENTYPE enum axtokentype { TRUE = 258, FALSE = 259, SEMICOLON = 260, AT = 261, DOLLAR = 262, IF = 263, ELSE = 264, FOR = 265, DO = 266, WHILE = 267, RETURN = 268, BREAK = 269, CONTINUE = 270, LCURLY = 271, RCURLY = 272, LSQUARE = 273, RSQUARE = 274, STRING = 275, DOUBLE = 276, FLOAT = 277, INT32 = 278, INT64 = 279, BOOL = 280, VEC2I = 281, VEC2F = 282, VEC2D = 283, VEC3I = 284, VEC3F = 285, VEC3D = 286, VEC4I = 287, VEC4F = 288, VEC4D = 289, F_AT = 290, I_AT = 291, V_AT = 292, S_AT = 293, I16_AT = 294, MAT3F = 295, MAT3D = 296, MAT4F = 297, MAT4D = 298, M3F_AT = 299, M4F_AT = 300, F_DOLLAR = 301, I_DOLLAR = 302, V_DOLLAR = 303, S_DOLLAR = 304, DOT_X = 305, DOT_Y = 306, DOT_Z = 307, L_INT32 = 308, L_INT64 = 309, L_FLOAT = 310, L_DOUBLE = 311, L_STRING = 312, IDENTIFIER = 313, COMMA = 314, QUESTION = 315, COLON = 316, EQUALS = 317, PLUSEQUALS = 318, MINUSEQUALS = 319, MULTIPLYEQUALS = 320, DIVIDEEQUALS = 321, MODULOEQUALS = 322, BITANDEQUALS = 323, BITXOREQUALS = 324, BITOREQUALS = 325, SHIFTLEFTEQUALS = 326, SHIFTRIGHTEQUALS = 327, OR = 328, AND = 329, BITOR = 330, BITXOR = 331, BITAND = 332, EQUALSEQUALS = 333, NOTEQUALS = 334, MORETHAN = 335, LESSTHAN = 336, MORETHANOREQUAL = 337, LESSTHANOREQUAL = 338, SHIFTLEFT = 339, SHIFTRIGHT = 340, PLUS = 341, MINUS = 342, MULTIPLY = 343, DIVIDE = 344, MODULO = 345, UMINUS = 346, NOT = 347, BITNOT = 348, PLUSPLUS = 349, MINUSMINUS = 350, LPARENS = 351, RPARENS = 352, LOWER_THAN_ELSE = 353 }; #endif /* Value type. */ #if ! defined AXSTYPE && ! defined AXSTYPE_IS_DECLARED union AXSTYPE { /// @brief Temporary storage for comma separated expressions using ExpList = std::vector<openvdb::ax::ast::Expression*>; const char* string; uint64_t index; double flt; openvdb::ax::ast::Tree* tree; openvdb::ax::ast::ValueBase* value; openvdb::ax::ast::Statement* statement; openvdb::ax::ast::StatementList* statementlist; openvdb::ax::ast::Block* block; openvdb::ax::ast::Expression* expression; openvdb::ax::ast::FunctionCall* function; openvdb::ax::ast::ArrayPack* arraypack; openvdb::ax::ast::CommaOperator* comma; openvdb::ax::ast::Variable* variable; openvdb::ax::ast::ExternalVariable* external; openvdb::ax::ast::Attribute* attribute; openvdb::ax::ast::DeclareLocal* declare_local; openvdb::ax::ast::Local* local; ExpList* explist; }; typedef union AXSTYPE AXSTYPE; # define AXSTYPE_IS_TRIVIAL 1 # define AXSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined AXLTYPE && ! defined AXLTYPE_IS_DECLARED typedef struct AXLTYPE AXLTYPE; struct AXLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define AXLTYPE_IS_DECLARED 1 # define AXLTYPE_IS_TRIVIAL 1 #endif extern AXSTYPE axlval; extern AXLTYPE axlloc; int axparse (openvdb::ax::ast::Tree** tree); #endif /* !YY_AX_OPENVDB_AX_GRAMMAR_AXPARSER_H_INCLUDED */ /* Copy the second part of user declarations. */ /* Unqualified %code blocks. */ template<typename T, typename... Args> T* newNode(AXLTYPE* loc, const Args&... args) { T* ptr = new T(args...); assert(axlog); axlog->addNodeLocation(ptr, {loc->first_line, loc->first_column}); return ptr; } #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif #if !defined _Noreturn \ && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) # if defined _MSC_VER && 1200 <= _MSC_VER # define _Noreturn __declspec (noreturn) # else # define _Noreturn YY_ATTRIBUTE ((__noreturn__)) # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined AXLTYPE_IS_TRIVIAL && AXLTYPE_IS_TRIVIAL \ && defined AXSTYPE_IS_TRIVIAL && AXSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 126 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 898 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 99 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 37 /* YYNRULES -- Number of rules. */ #define YYNRULES 155 /* YYNSTATES -- Number of states. */ #define YYNSTATES 263 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 353 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 }; #if AXDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 238, 238, 241, 247, 248, 249, 252, 258, 259, 265, 266, 267, 268, 269, 270, 271, 272, 275, 276, 281, 282, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 303, 305, 311, 316, 321, 327, 338, 339, 344, 345, 351, 352, 357, 358, 362, 363, 368, 369, 370, 375, 376, 381, 383, 384, 389, 390, 395, 396, 397, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 439, 440, 445, 446, 447, 448, 452, 453, 457, 458, 463, 464, 465, 466, 467, 468, 469, 481, 487, 488, 493, 494, 495, 496, 497, 498, 499, 500, 501, 506, 507, 508, 509, 510, 511, 518, 525, 526, 527, 528, 529, 530, 531, 535, 536, 537, 538, 543, 544, 545, 546, 551, 552, 553, 554, 555, 560, 561, 562, 563, 564, 565, 566, 567, 568 }; #endif #if AXDEBUG || YYERROR_VERBOSE || 1 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "TRUE", "FALSE", "SEMICOLON", "AT", "DOLLAR", "IF", "ELSE", "FOR", "DO", "WHILE", "RETURN", "BREAK", "CONTINUE", "LCURLY", "RCURLY", "LSQUARE", "RSQUARE", "STRING", "DOUBLE", "FLOAT", "INT32", "INT64", "BOOL", "VEC2I", "VEC2F", "VEC2D", "VEC3I", "VEC3F", "VEC3D", "VEC4I", "VEC4F", "VEC4D", "F_AT", "I_AT", "V_AT", "S_AT", "I16_AT", "MAT3F", "MAT3D", "MAT4F", "MAT4D", "M3F_AT", "M4F_AT", "F_DOLLAR", "I_DOLLAR", "V_DOLLAR", "S_DOLLAR", "DOT_X", "DOT_Y", "DOT_Z", "L_INT32", "L_INT64", "L_FLOAT", "L_DOUBLE", "L_STRING", "IDENTIFIER", "COMMA", "QUESTION", "COLON", "EQUALS", "PLUSEQUALS", "MINUSEQUALS", "MULTIPLYEQUALS", "DIVIDEEQUALS", "MODULOEQUALS", "BITANDEQUALS", "BITXOREQUALS", "BITOREQUALS", "SHIFTLEFTEQUALS", "SHIFTRIGHTEQUALS", "OR", "AND", "BITOR", "BITXOR", "BITAND", "EQUALSEQUALS", "NOTEQUALS", "MORETHAN", "LESSTHAN", "MORETHANOREQUAL", "LESSTHANOREQUAL", "SHIFTLEFT", "SHIFTRIGHT", "PLUS", "MINUS", "MULTIPLY", "DIVIDE", "MODULO", "UMINUS", "NOT", "BITNOT", "PLUSPLUS", "MINUSMINUS", "LPARENS", "RPARENS", "LOWER_THAN_ELSE", "$accept", "tree", "body", "block", "statement", "expressions", "comma_operator", "expression", "declaration", "declaration_list", "declarations", "block_or_statement", "conditional_statement", "loop_condition", "loop_condition_optional", "loop_init", "loop_iter", "loop", "function_start_expression", "function_call_expression", "assign_expression", "binary_expression", "ternary_expression", "unary_expression", "pre_crement", "post_crement", "variable_reference", "array", "variable", "attribute", "external", "local", "literal", "type", "matrix_type", "scalar_type", "vector_type", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353 }; # endif #define YYPACT_NINF -225 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-225))) #define YYTABLE_NINF -1 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 525, -225, -225, -225, -54, -51, -85, -62, 525, -49, 48, 72, 83, 337, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, 31, 34, 35, 36, 40, -225, -225, -225, -225, 41, 64, 65, 66, 85, 86, -225, -225, -225, -225, -225, -6, 713, 713, 713, 713, 790, 790, 713, 145, 525, -225, -225, 154, 87, 233, 102, 103, 158, -225, -225, -56, -225, -225, -225, -225, -225, -225, -225, 533, -225, -8, -225, -225, -225, -225, 20, -225, 70, -225, -225, -225, 713, 713, -225, -225, 152, 713, -225, -225, -225, -225, 431, -11, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, 242, 713, -57, 22, -225, -225, -225, -225, -225, 161, -225, -225, 73, -225, -225, -225, -225, 713, 713, 619, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 111, 113, -225, 713, -225, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, -225, -225, 713, -225, -225, -225, 114, 115, 112, 713, 78, -225, -225, 171, 81, -225, -225, 106, -225, -225, -225, 421, -11, 233, -225, 421, 421, 713, 327, 607, 697, 773, 787, 808, 68, 68, -70, -70, -70, -70, -7, -7, -57, -57, -225, -225, -225, 116, 137, 421, 421, 421, 421, 421, 421, 421, 421, 421, 421, 421, 421, -14, -225, -225, 713, 108, 525, 713, 713, 525, 421, 713, 713, 713, -225, 713, 421, -225, 195, -225, 201, 110, -225, 421, 421, 421, 141, 525, 713, -225, -225, -225, -225, 135, 525, -225 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 2, 132, 133, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 137, 146, 145, 143, 144, 142, 147, 148, 149, 150, 151, 152, 153, 154, 155, 0, 0, 0, 0, 0, 138, 139, 140, 141, 0, 0, 0, 0, 0, 0, 127, 128, 129, 130, 131, 126, 0, 0, 0, 0, 0, 0, 0, 0, 3, 7, 6, 0, 19, 18, 39, 40, 0, 12, 13, 0, 26, 25, 22, 24, 23, 102, 29, 31, 30, 101, 109, 28, 110, 27, 0, 136, 134, 135, 119, 125, 0, 51, 41, 42, 0, 0, 14, 15, 16, 9, 0, 19, 114, 113, 115, 116, 112, 117, 118, 122, 121, 123, 124, 0, 0, 93, 0, 94, 96, 95, 126, 97, 0, 134, 98, 0, 1, 5, 4, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 99, 100, 0, 103, 104, 105, 0, 0, 33, 0, 0, 49, 50, 0, 0, 45, 46, 0, 8, 108, 59, 57, 0, 0, 32, 21, 20, 0, 0, 84, 83, 81, 82, 80, 85, 86, 87, 88, 89, 90, 78, 79, 73, 74, 75, 76, 77, 36, 38, 58, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 0, 111, 120, 0, 0, 0, 48, 0, 0, 92, 0, 0, 0, 106, 0, 34, 61, 43, 47, 0, 0, 56, 91, 35, 37, 0, 0, 53, 55, 107, 44, 52, 0, 0, 54 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -225, -225, 199, 38, 39, -55, 12, -29, -93, -225, 117, -224, -225, -185, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, -225, 2, -225, -225, -225, -225, -225, -225, 0, -225, 32, -225 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 57, 58, 92, 93, 61, 62, 63, 64, 65, 66, 94, 67, 184, 247, 180, 260, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 116, 85, 86, 87 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_uint16 yytable[] = { 84, 125, 183, 154, 88, 241, 186, 89, 84, 245, 169, 90, 249, 84, 144, 145, 146, 147, 148, 149, 150, 115, 117, 118, 119, 101, 173, 174, 173, 174, 258, 148, 149, 150, 91, 177, 178, 262, 59, 60, 182, 155, 170, 171, 172, 242, 132, 95, 130, 246, 248, 59, 60, 96, 122, 122, 121, 124, 84, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 97, 175, 146, 147, 148, 149, 150, 188, 190, 123, 123, 98, 102, 113, 84, 103, 104, 105, 84, 127, 128, 106, 107, 84, 192, 193, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 108, 109, 110, 216, 189, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 127, 128, 228, 183, 183, 111, 112, 126, 130, 232, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 129, 257, 151, 152, 153, 181, 237, 176, 173, 132, 214, 191, 215, 229, 230, 231, 233, 234, 235, 239, 182, 182, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 240, 259, 132, 243, 236, 254, 244, 255, 256, 179, 250, 251, 252, 100, 253, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 261, 84, 84, 84, 84, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 4, 5, 0, 0, 0, 0, 84, 0, 0, 0, 114, 0, 0, 84, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 131, 132, 0, 44, 45, 46, 47, 48, 49, 0, 0, 0, 0, 0, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 0, 0, 0, 0, 50, 51, 0, 0, 0, 0, 52, 53, 54, 55, 56, 187, 1, 2, 3, 4, 5, 6, 0, 7, 8, 9, 10, 11, 12, 13, 99, 0, 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 132, 238, 0, 44, 45, 46, 47, 48, 49, 0, 0, 0, 0, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 0, 0, 0, 0, 0, 50, 51, 0, 0, 0, 0, 52, 53, 54, 55, 56, 1, 2, 3, 4, 5, 6, 0, 7, 8, 9, 10, 11, 12, 13, 185, 0, 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 132, 0, 0, 44, 45, 46, 47, 48, 49, 0, 0, 0, 0, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 0, 0, 0, 0, 0, 50, 51, 0, 0, 0, 0, 52, 53, 54, 55, 56, 1, 2, 3, 4, 5, 6, 0, 7, 8, 9, 10, 11, 12, 13, 0, 0, 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 0, 0, 0, 44, 45, 46, 47, 48, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 0, 0, 0, 0, 0, 50, 51, 0, 0, 0, 0, 52, 53, 54, 55, 56, 1, 2, 0, 4, 5, 167, 168, 0, 0, 0, 0, 0, 0, 114, 0, 0, 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 0, 0, 0, 44, 45, 46, 47, 48, 49, 0, 0, 194, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 0, 0, 0, 0, 0, 0, 0, 50, 51, 0, 0, 0, 0, 52, 53, 54, 55, 56, 1, 2, 0, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 114, 0, 0, 0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 0, 0, 0, 44, 45, 46, 47, 48, 49, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 50, 51, 0, 0, 0, 0, 52, 53, 54, 55, 56, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 0, 0, 0, 0, 0, 0, 54, 55, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150 }; static const yytype_int16 yycheck[] = { 0, 56, 95, 59, 58, 19, 17, 58, 8, 233, 18, 96, 236, 13, 84, 85, 86, 87, 88, 89, 90, 50, 51, 52, 53, 13, 6, 7, 6, 7, 254, 88, 89, 90, 96, 90, 91, 261, 0, 0, 95, 97, 50, 51, 52, 59, 60, 96, 59, 234, 235, 13, 13, 5, 54, 55, 54, 55, 58, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 5, 58, 86, 87, 88, 89, 90, 113, 114, 54, 55, 5, 58, 96, 91, 58, 58, 58, 95, 58, 58, 58, 58, 100, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 58, 58, 58, 154, 114, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 100, 100, 169, 234, 235, 58, 58, 0, 59, 176, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 5, 19, 59, 59, 5, 12, 194, 96, 6, 60, 58, 97, 58, 58, 58, 62, 97, 5, 96, 62, 234, 235, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 62, 255, 60, 231, 97, 9, 97, 5, 97, 91, 238, 239, 240, 13, 242, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 233, 234, 235, 236, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, -1, 6, 7, -1, -1, -1, -1, 254, -1, -1, -1, 16, -1, -1, 261, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 59, 60, -1, 53, 54, 55, 56, 57, 58, -1, -1, -1, -1, -1, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, -1, -1, -1, -1, 86, 87, -1, -1, -1, -1, 92, 93, 94, 95, 96, 97, 3, 4, 5, 6, 7, 8, -1, 10, 11, 12, 13, 14, 15, 16, 17, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 60, 61, -1, 53, 54, 55, 56, 57, 58, -1, -1, -1, -1, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, -1, -1, -1, -1, -1, 86, 87, -1, -1, -1, -1, 92, 93, 94, 95, 96, 3, 4, 5, 6, 7, 8, -1, 10, 11, 12, 13, 14, 15, 16, 17, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 60, -1, -1, 53, 54, 55, 56, 57, 58, -1, -1, -1, -1, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, -1, -1, -1, -1, -1, 86, 87, -1, -1, -1, -1, 92, 93, 94, 95, 96, 3, 4, 5, 6, 7, 8, -1, 10, 11, 12, 13, 14, 15, 16, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, -1, 53, 54, 55, 56, 57, 58, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, -1, -1, -1, -1, -1, 86, 87, -1, -1, -1, -1, 92, 93, 94, 95, 96, 3, 4, -1, 6, 7, 94, 95, -1, -1, -1, -1, -1, -1, 16, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, -1, 53, 54, 55, 56, 57, 58, -1, -1, 61, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, -1, -1, -1, -1, -1, -1, -1, 86, 87, -1, -1, -1, -1, 92, 93, 94, 95, 96, 3, 4, -1, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, 16, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, -1, -1, -1, 53, 54, 55, 56, 57, 58, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, 86, 87, -1, -1, -1, -1, 92, 93, 94, 95, 96, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 58, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, -1, -1, -1, -1, -1, -1, 94, 95, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 53, 54, 55, 56, 57, 58, 86, 87, 92, 93, 94, 95, 96, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 111, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 58, 58, 96, 96, 102, 103, 110, 96, 5, 5, 5, 17, 101, 105, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 96, 16, 106, 132, 106, 106, 106, 58, 125, 132, 134, 125, 104, 0, 102, 103, 5, 59, 59, 60, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 59, 59, 5, 59, 97, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 94, 95, 18, 50, 51, 52, 6, 7, 58, 96, 104, 104, 109, 114, 12, 104, 107, 112, 17, 17, 97, 106, 105, 106, 97, 106, 106, 61, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 58, 58, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 58, 58, 62, 106, 97, 5, 96, 97, 106, 61, 62, 62, 19, 59, 106, 97, 110, 112, 113, 112, 110, 106, 106, 106, 106, 9, 5, 97, 19, 110, 104, 115, 97, 110 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 99, 100, 100, 101, 101, 101, 101, 102, 102, 103, 103, 103, 103, 103, 103, 103, 103, 104, 104, 105, 105, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 107, 107, 108, 108, 108, 108, 109, 109, 110, 110, 111, 111, 112, 112, 113, 113, 114, 114, 114, 115, 115, 116, 116, 116, 117, 117, 118, 118, 118, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 121, 121, 122, 122, 122, 122, 123, 123, 124, 124, 125, 125, 125, 125, 125, 125, 125, 126, 127, 127, 128, 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, 129, 129, 130, 131, 131, 131, 131, 131, 131, 131, 132, 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, 134, 134, 135, 135, 135, 135, 135, 135, 135, 135, 135 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 0, 1, 2, 2, 1, 1, 3, 2, 2, 2, 1, 1, 2, 2, 2, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 4, 5, 3, 5, 3, 1, 1, 1, 1, 5, 7, 1, 1, 1, 0, 1, 1, 0, 1, 0, 9, 6, 5, 3, 3, 3, 2, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 4, 6, 3, 1, 1, 3, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (tree, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (N) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (0) #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K]) /* Enable debugging if requested. */ #if AXDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined AXLTYPE_IS_TRIVIAL && AXLTYPE_IS_TRIVIAL /* Print *YYLOCP on YYO. Private, do not rely on its existence. */ YY_ATTRIBUTE_UNUSED static unsigned yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp) { unsigned res = 0; int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0; if (0 <= yylocp->first_line) { res += YYFPRINTF (yyo, "%d", yylocp->first_line); if (0 <= yylocp->first_column) res += YYFPRINTF (yyo, ".%d", yylocp->first_column); } if (0 <= yylocp->last_line) { if (yylocp->first_line < yylocp->last_line) { res += YYFPRINTF (yyo, "-%d", yylocp->last_line); if (0 <= end_col) res += YYFPRINTF (yyo, ".%d", end_col); } else if (0 <= end_col && yylocp->first_column < end_col) res += YYFPRINTF (yyo, "-%d", end_col); } return res; } # define YY_LOCATION_PRINT(File, Loc) \ yy_location_print_ (File, &(Loc)) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, tree); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*----------------------------------------. | Print this symbol's value on YYOUTPUT. | `----------------------------------------*/ static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, openvdb::ax::ast::Tree** tree) { FILE *yyo = yyoutput; YYUSE (yyo); YYUSE (yylocationp); YYUSE (tree); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, openvdb::ax::ast::Tree** tree) { YYFPRINTF (yyoutput, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, tree); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, openvdb::ax::ast::Tree** tree) { unsigned long int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , tree); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, yylsp, Rule, tree); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !AXDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !AXDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, openvdb::ax::ast::Tree** tree) { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (tree); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 53: /* L_INT32 */ { } break; case 54: /* L_INT64 */ { } break; case 55: /* L_FLOAT */ { } break; case 56: /* L_DOUBLE */ { } break; case 57: /* L_STRING */ { free(const_cast<char*>(((*yyvaluep).string))); } break; case 58: /* IDENTIFIER */ { free(const_cast<char*>(((*yyvaluep).string))); } break; case 100: /* tree */ { } break; case 101: /* body */ { delete ((*yyvaluep).block); } break; case 102: /* block */ { delete ((*yyvaluep).block); } break; case 103: /* statement */ { delete ((*yyvaluep).statement); } break; case 104: /* expressions */ { delete ((*yyvaluep).expression); } break; case 105: /* comma_operator */ { for (auto& ptr : *((*yyvaluep).explist)) delete ptr; delete ((*yyvaluep).explist); } break; case 106: /* expression */ { delete ((*yyvaluep).expression); } break; case 107: /* declaration */ { delete ((*yyvaluep).declare_local); } break; case 108: /* declaration_list */ { delete ((*yyvaluep).statementlist); } break; case 109: /* declarations */ { delete ((*yyvaluep).statement); } break; case 110: /* block_or_statement */ { delete ((*yyvaluep).block); } break; case 111: /* conditional_statement */ { delete ((*yyvaluep).statement); } break; case 112: /* loop_condition */ { delete ((*yyvaluep).statement); } break; case 113: /* loop_condition_optional */ { delete ((*yyvaluep).statement); } break; case 114: /* loop_init */ { delete ((*yyvaluep).statement); } break; case 115: /* loop_iter */ { delete ((*yyvaluep).expression); } break; case 116: /* loop */ { delete ((*yyvaluep).statement); } break; case 117: /* function_start_expression */ { delete ((*yyvaluep).function); } break; case 118: /* function_call_expression */ { delete ((*yyvaluep).expression); } break; case 119: /* assign_expression */ { delete ((*yyvaluep).expression); } break; case 120: /* binary_expression */ { delete ((*yyvaluep).expression); } break; case 121: /* ternary_expression */ { delete ((*yyvaluep).expression); } break; case 122: /* unary_expression */ { delete ((*yyvaluep).expression); } break; case 123: /* pre_crement */ { delete ((*yyvaluep).expression); } break; case 124: /* post_crement */ { delete ((*yyvaluep).expression); } break; case 125: /* variable_reference */ { delete ((*yyvaluep).expression); } break; case 126: /* array */ { delete ((*yyvaluep).expression); } break; case 127: /* variable */ { delete ((*yyvaluep).variable); } break; case 128: /* attribute */ { delete ((*yyvaluep).attribute); } break; case 129: /* external */ { delete ((*yyvaluep).external); } break; case 130: /* local */ { delete ((*yyvaluep).local); } break; case 131: /* literal */ { delete ((*yyvaluep).value); } break; case 132: /* type */ { } break; case 133: /* matrix_type */ { } break; case 134: /* scalar_type */ { } break; case 135: /* vector_type */ { } break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Location data for the lookahead symbol. */ YYLTYPE yylloc # if defined AXLTYPE_IS_TRIVIAL && AXLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ int yyparse (openvdb::ax::ast::Tree** tree) { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: { *tree = newNode<Tree>(&(yyloc)); (yyval.tree) = *tree; } break; case 3: { *tree = newNode<Tree>(&(yylsp[0]), (yyvsp[0].block)); (yyval.tree) = *tree; } break; case 4: { (yyvsp[-1].block)->addStatement((yyvsp[0].statement)); (yyval.block) = (yyvsp[-1].block); } break; case 5: { (yyvsp[-1].block)->addStatement((yyvsp[0].block)); (yyval.block) = (yyvsp[-1].block); } break; case 6: { (yyval.block) = newNode<Block>(&(yyloc)); (yyval.block)->addStatement((yyvsp[0].statement)); } break; case 7: { (yyval.block) = newNode<Block>(&(yyloc)); (yyval.block)->addStatement((yyvsp[0].block)); } break; case 8: { (yyval.block) = (yyvsp[-1].block); } break; case 9: { (yyval.block) = newNode<Block>(&(yyloc)); } break; case 10: { (yyval.statement) = (yyvsp[-1].expression); } break; case 11: { (yyval.statement) = (yyvsp[-1].statement); } break; case 12: { (yyval.statement) = (yyvsp[0].statement); } break; case 13: { (yyval.statement) = (yyvsp[0].statement); } break; case 14: { (yyval.statement) = newNode<Keyword>(&(yyloc), tokens::RETURN); } break; case 15: { (yyval.statement) = newNode<Keyword>(&(yyloc), tokens::BREAK); } break; case 16: { (yyval.statement) = newNode<Keyword>(&(yyloc), tokens::CONTINUE); } break; case 17: { (yyval.statement) = nullptr; } break; case 18: { (yyval.expression) = (yyvsp[0].expression); } break; case 19: { (yyval.expression) = newNode<CommaOperator>(&(yyloc), *static_cast<ExpList*>((yyvsp[0].explist))); } break; case 20: { (yyval.explist) = new ExpList(); (yyval.explist)->assign({(yyvsp[-2].expression), (yyvsp[0].expression)}); } break; case 21: { (yyvsp[-2].explist)->emplace_back((yyvsp[0].expression)); (yyval.explist) = (yyvsp[-2].explist); } break; case 22: { (yyval.expression) = (yyvsp[0].expression); } break; case 23: { (yyval.expression) = (yyvsp[0].expression); } break; case 24: { (yyval.expression) = (yyvsp[0].expression); } break; case 25: { (yyval.expression) = (yyvsp[0].expression); } break; case 26: { (yyval.expression) = (yyvsp[0].expression); } break; case 27: { (yyval.expression) = (yyvsp[0].value); } break; case 28: { (yyval.expression) = (yyvsp[0].external); } break; case 29: { (yyval.expression) = (yyvsp[0].expression); } break; case 30: { (yyval.expression) = (yyvsp[0].expression); } break; case 31: { (yyval.expression) = (yyvsp[0].expression); } break; case 32: { (yyval.expression) = (yyvsp[-1].expression); } break; case 33: { (yyval.declare_local) = newNode<DeclareLocal>(&(yylsp[-1]), static_cast<tokens::CoreType>((yyvsp[-1].index)), newNode<Local>(&(yylsp[0]), (yyvsp[0].string))); free(const_cast<char*>((yyvsp[0].string))); } break; case 34: { (yyval.declare_local) = newNode<DeclareLocal>(&(yylsp[-3]), static_cast<tokens::CoreType>((yyvsp[-3].index)), newNode<Local>(&(yylsp[-2]), (yyvsp[-2].string)), (yyvsp[0].expression)); free(const_cast<char*>((yyvsp[-2].string))); } break; case 35: { (yyval.statementlist) = newNode<StatementList>(&(yyloc), (yyvsp[-4].declare_local)); const tokens::CoreType type = static_cast<const DeclareLocal*>((yyvsp[-4].declare_local))->type(); (yyval.statementlist)->addStatement(newNode<DeclareLocal>(&(yylsp[-4]), type, newNode<Local>(&(yylsp[-2]), (yyvsp[-2].string)), (yyvsp[0].expression))); free(const_cast<char*>((yyvsp[-2].string))); } break; case 36: { (yyval.statementlist) = newNode<StatementList>(&(yyloc), (yyvsp[-2].declare_local)); const tokens::CoreType type = static_cast<const DeclareLocal*>((yyvsp[-2].declare_local))->type(); (yyval.statementlist)->addStatement(newNode<DeclareLocal>(&(yylsp[-2]), type, newNode<Local>(&(yylsp[0]), (yyvsp[0].string)))); free(const_cast<char*>((yyvsp[0].string))); } break; case 37: { const auto firstNode = (yyvsp[-4].statementlist)->child(0); assert(firstNode); const tokens::CoreType type = static_cast<const DeclareLocal*>(firstNode)->type(); (yyval.statementlist)->addStatement(newNode<DeclareLocal>(&(yylsp[-4]), type, newNode<Local>(&(yylsp[-2]), (yyvsp[-2].string)), (yyvsp[0].expression))); (yyval.statementlist) = (yyvsp[-4].statementlist); } break; case 38: { const auto firstNode = (yyvsp[-2].statementlist)->child(0); assert(firstNode); const tokens::CoreType type = static_cast<const DeclareLocal*>(firstNode)->type(); (yyval.statementlist)->addStatement(newNode<DeclareLocal>(&(yylsp[-2]), type, newNode<Local>(&(yylsp[0]), (yyvsp[0].string)))); free(const_cast<char*>((yyvsp[0].string))); (yyval.statementlist) = (yyvsp[-2].statementlist); } break; case 39: { (yyval.statement) = (yyvsp[0].declare_local); } break; case 40: { (yyval.statement) = (yyvsp[0].statementlist); } break; case 41: { (yyval.block) = (yyvsp[0].block); } break; case 42: { (yyval.block) = newNode<Block>(&(yyloc)); (yyval.block)->addStatement((yyvsp[0].statement)); } break; case 43: { (yyval.statement) = newNode<ConditionalStatement>(&(yyloc), (yyvsp[-2].expression), (yyvsp[0].block)); } break; case 44: { (yyval.statement) = newNode<ConditionalStatement>(&(yyloc), (yyvsp[-4].expression), (yyvsp[-2].block), (yyvsp[0].block)); } break; case 45: { (yyval.statement) = (yyvsp[0].expression); } break; case 46: { (yyval.statement) = (yyvsp[0].declare_local); } break; case 47: { (yyval.statement) = (yyvsp[0].statement); } break; case 48: { (yyval.statement) = nullptr; } break; case 49: { (yyval.statement) = (yyvsp[0].expression); } break; case 50: { (yyval.statement) = (yyvsp[0].statement); } break; case 51: { (yyval.statement) = nullptr; } break; case 52: { (yyval.expression) = (yyvsp[0].expression); } break; case 53: { (yyval.expression) = nullptr; } break; case 54: { (yyval.statement) = newNode<Loop>(&(yyloc), tokens::FOR, ((yyvsp[-4].statement) ? (yyvsp[-4].statement) : newNode<Value<bool>>(&(yyloc), true)), (yyvsp[0].block), (yyvsp[-6].statement), (yyvsp[-2].expression)); } break; case 55: { (yyval.statement) = newNode<Loop>(&(yyloc), tokens::DO, (yyvsp[-1].statement), (yyvsp[-4].block)); } break; case 56: { (yyval.statement) = newNode<Loop>(&(yyloc), tokens::WHILE, (yyvsp[-2].statement), (yyvsp[0].block)); } break; case 57: { (yyval.function) = newNode<FunctionCall>(&(yylsp[-2]), (yyvsp[-2].string)); (yyval.function)->append((yyvsp[0].expression)); free(const_cast<char*>((yyvsp[-2].string))); } break; case 58: { (yyvsp[-2].function)->append((yyvsp[0].expression)); (yyval.function) = (yyvsp[-2].function); } break; case 59: { (yyval.expression) = newNode<FunctionCall>(&(yylsp[-2]), (yyvsp[-2].string)); free(const_cast<char*>((yyvsp[-2].string))); } break; case 60: { (yyval.expression) = (yyvsp[-1].function); } break; case 61: { (yyval.expression) = newNode<Cast>(&(yylsp[-3]), (yyvsp[-1].expression), static_cast<tokens::CoreType>((yyvsp[-3].index))); } break; case 62: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression)); } break; case 63: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::PLUS); } break; case 64: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MINUS); } break; case 65: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MULTIPLY); } break; case 66: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::DIVIDE); } break; case 67: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MODULO); } break; case 68: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::BITAND); } break; case 69: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::BITXOR); } break; case 70: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::BITOR); } break; case 71: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::SHIFTLEFT); } break; case 72: { (yyval.expression) = newNode<AssignExpression>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::SHIFTRIGHT); } break; case 73: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::PLUS); } break; case 74: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MINUS); } break; case 75: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MULTIPLY); } break; case 76: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::DIVIDE); } break; case 77: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MODULO); } break; case 78: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::SHIFTLEFT); } break; case 79: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::SHIFTRIGHT); } break; case 80: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::BITAND); } break; case 81: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::BITOR); } break; case 82: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::BITXOR); } break; case 83: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::AND); } break; case 84: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::OR); } break; case 85: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::EQUALSEQUALS); } break; case 86: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::NOTEQUALS); } break; case 87: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MORETHAN); } break; case 88: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::LESSTHAN); } break; case 89: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::MORETHANOREQUAL); } break; case 90: { (yyval.expression) = newNode<BinaryOperator>(&(yylsp[-2]), (yyvsp[-2].expression), (yyvsp[0].expression), tokens::LESSTHANOREQUAL); } break; case 91: { (yyval.expression) = newNode<TernaryOperator>(&(yylsp[-4]), (yyvsp[-4].expression), (yyvsp[-2].expression), (yyvsp[0].expression)); } break; case 92: { (yyval.expression) = newNode<TernaryOperator>(&(yylsp[-3]), (yyvsp[-3].expression), nullptr, (yyvsp[0].expression)); } break; case 93: { (yyval.expression) = newNode<UnaryOperator>(&(yylsp[-1]), (yyvsp[0].expression), tokens::PLUS); } break; case 94: { (yyval.expression) = newNode<UnaryOperator>(&(yylsp[-1]), (yyvsp[0].expression), tokens::MINUS); } break; case 95: { (yyval.expression) = newNode<UnaryOperator>(&(yylsp[-1]), (yyvsp[0].expression), tokens::BITNOT); } break; case 96: { (yyval.expression) = newNode<UnaryOperator>(&(yylsp[-1]), (yyvsp[0].expression), tokens::NOT); } break; case 97: { (yyval.expression) = newNode<Crement>(&(yylsp[-1]), (yyvsp[0].expression), Crement::Increment, /*post*/false); } break; case 98: { (yyval.expression) = newNode<Crement>(&(yylsp[-1]), (yyvsp[0].expression), Crement::Decrement, /*post*/false); } break; case 99: { (yyval.expression) = newNode<Crement>(&(yylsp[-1]), (yyvsp[-1].expression), Crement::Increment, /*post*/true); } break; case 100: { (yyval.expression) = newNode<Crement>(&(yylsp[-1]), (yyvsp[-1].expression), Crement::Decrement, /*post*/true); } break; case 101: { (yyval.expression) = (yyvsp[0].variable); } break; case 102: { (yyval.expression) = (yyvsp[0].expression); } break; case 103: { (yyval.expression) = newNode<ArrayUnpack>(&(yylsp[-1]), (yyvsp[-1].variable), newNode<Value<int32_t>>(&(yylsp[0]), 0)); } break; case 104: { (yyval.expression) = newNode<ArrayUnpack>(&(yylsp[-1]), (yyvsp[-1].variable), newNode<Value<int32_t>>(&(yylsp[0]), 1)); } break; case 105: { (yyval.expression) = newNode<ArrayUnpack>(&(yylsp[-1]), (yyvsp[-1].variable), newNode<Value<int32_t>>(&(yylsp[0]), 2)); } break; case 106: { (yyval.expression) = newNode<ArrayUnpack>(&(yylsp[-3]), (yyvsp[-3].variable), (yyvsp[-1].expression)); } break; case 107: { (yyval.expression) = newNode<ArrayUnpack>(&(yylsp[-5]), (yyvsp[-5].variable), (yyvsp[-3].expression), (yyvsp[-1].expression)); } break; case 108: { (yyval.expression) = newNode<ArrayPack>(&(yylsp[-2]), *(yyvsp[-1].explist)); } break; case 109: { (yyval.variable) = (yyvsp[0].attribute); } break; case 110: { (yyval.variable) = (yyvsp[0].local); } break; case 111: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), static_cast<tokens::CoreType>((yyvsp[-2].index))); free(const_cast<char*>((yyvsp[0].string))); } break; case 112: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::INT16); free(const_cast<char*>((yyvsp[0].string))); } break; case 113: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::INT32); free(const_cast<char*>((yyvsp[0].string))); } break; case 114: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::FLOAT); free(const_cast<char*>((yyvsp[0].string))); } break; case 115: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::VEC3F); free(const_cast<char*>((yyvsp[0].string))); } break; case 116: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::STRING); free(const_cast<char*>((yyvsp[0].string))); } break; case 117: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::MAT3F); free(const_cast<char*>((yyvsp[0].string))); } break; case 118: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::MAT4F); free(const_cast<char*>((yyvsp[0].string))); } break; case 119: { (yyval.attribute) = newNode<Attribute>(&(yyloc), (yyvsp[0].string), tokens::FLOAT, true); free(const_cast<char*>((yyvsp[0].string))); } break; case 120: { (yyval.external) = newNode<ExternalVariable>(&(yyloc), (yyvsp[0].string), static_cast<tokens::CoreType>((yyvsp[-2].index))); free(const_cast<char*>((yyvsp[0].string))); } break; case 121: { (yyval.external) = newNode<ExternalVariable>(&(yyloc), (yyvsp[0].string), tokens::INT32); free(const_cast<char*>((yyvsp[0].string))); } break; case 122: { (yyval.external) = newNode<ExternalVariable>(&(yyloc), (yyvsp[0].string), tokens::FLOAT); free(const_cast<char*>((yyvsp[0].string))); } break; case 123: { (yyval.external) = newNode<ExternalVariable>(&(yyloc), (yyvsp[0].string), tokens::VEC3F); free(const_cast<char*>((yyvsp[0].string))); } break; case 124: { (yyval.external) = newNode<ExternalVariable>(&(yyloc), (yyvsp[0].string), tokens::STRING); free(const_cast<char*>((yyvsp[0].string))); } break; case 125: { (yyval.external) = newNode<ExternalVariable>(&(yyloc), (yyvsp[0].string), tokens::FLOAT); free(const_cast<char*>((yyvsp[0].string))); } break; case 126: { (yyval.local) = newNode<Local>(&(yyloc), (yyvsp[0].string)); free(const_cast<char*>((yyvsp[0].string))); } break; case 127: { (yyval.value) = newNode<Value<int32_t>>(&(yylsp[0]), (yyvsp[0].index)); } break; case 128: { (yyval.value) = newNode<Value<int64_t>>(&(yylsp[0]), (yyvsp[0].index)); } break; case 129: { (yyval.value) = newNode<Value<float>>(&(yylsp[0]), static_cast<float>((yyvsp[0].flt))); } break; case 130: { (yyval.value) = newNode<Value<double>>(&(yylsp[0]), (yyvsp[0].flt)); } break; case 131: { (yyval.value) = newNode<Value<std::string>>(&(yylsp[0]), (yyvsp[0].string)); free(const_cast<char*>((yyvsp[0].string))); } break; case 132: { (yyval.value) = newNode<Value<bool>>(&(yylsp[0]), true); } break; case 133: { (yyval.value) = newNode<Value<bool>>(&(yylsp[0]), false); } break; case 134: { (yyval.index) = (yyvsp[0].index); } break; case 135: { (yyval.index) = (yyvsp[0].index); } break; case 136: { (yyval.index) = (yyvsp[0].index); } break; case 137: { (yyval.index) = tokens::STRING; } break; case 138: { (yyval.index) = tokens::MAT3F; } break; case 139: { (yyval.index) = tokens::MAT3D; } break; case 140: { (yyval.index) = tokens::MAT4F; } break; case 141: { (yyval.index) = tokens::MAT4D; } break; case 142: { (yyval.index) = tokens::BOOL; } break; case 143: { (yyval.index) = tokens::INT32; } break; case 144: { (yyval.index) = tokens::INT64; } break; case 145: { (yyval.index) = tokens::FLOAT; } break; case 146: { (yyval.index) = tokens::DOUBLE; } break; case 147: { (yyval.index) = tokens::VEC2I; } break; case 148: { (yyval.index) = tokens::VEC2F; } break; case 149: { (yyval.index) = tokens::VEC2D; } break; case 150: { (yyval.index) = tokens::VEC3I; } break; case 151: { (yyval.index) = tokens::VEC3F; } break; case 152: { (yyval.index) = tokens::VEC3D; } break; case 153: { (yyval.index) = tokens::VEC4I; } break; case 154: { (yyval.index) = tokens::VEC4F; } break; case 155: { (yyval.index) = tokens::VEC4D; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (tree, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (tree, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, tree); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, tree); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (tree, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, tree); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, tree); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } OPENVDB_NO_TYPE_CONVERSION_WARNING_END
101,410
C++
29.955739
218
0.490139
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/grammar/generated/axlexer.cc
#define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define yy_create_buffer ax_create_buffer #define yy_delete_buffer ax_delete_buffer #define yy_scan_buffer ax_scan_buffer #define yy_scan_string ax_scan_string #define yy_scan_bytes ax_scan_bytes #define yy_init_buffer ax_init_buffer #define yy_flush_buffer ax_flush_buffer #define yy_load_buffer_state ax_load_buffer_state #define yy_switch_to_buffer ax_switch_to_buffer #define yypush_buffer_state axpush_buffer_state #define yypop_buffer_state axpop_buffer_state #define yyensure_buffer_stack axensure_buffer_stack #define yy_flex_debug ax_flex_debug #define yyin axin #define yyleng axleng #define yylex axlex #define yylineno axlineno #define yyout axout #define yyrestart axrestart #define yytext axtext #define yywrap axwrap #define yyalloc axalloc #define yyrealloc axrealloc #define yyfree axfree #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 4 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif #ifdef yy_create_buffer #define ax_create_buffer_ALREADY_DEFINED #else #define yy_create_buffer ax_create_buffer #endif #ifdef yy_delete_buffer #define ax_delete_buffer_ALREADY_DEFINED #else #define yy_delete_buffer ax_delete_buffer #endif #ifdef yy_scan_buffer #define ax_scan_buffer_ALREADY_DEFINED #else #define yy_scan_buffer ax_scan_buffer #endif #ifdef yy_scan_string #define ax_scan_string_ALREADY_DEFINED #else #define yy_scan_string ax_scan_string #endif #ifdef yy_scan_bytes #define ax_scan_bytes_ALREADY_DEFINED #else #define yy_scan_bytes ax_scan_bytes #endif #ifdef yy_init_buffer #define ax_init_buffer_ALREADY_DEFINED #else #define yy_init_buffer ax_init_buffer #endif #ifdef yy_flush_buffer #define ax_flush_buffer_ALREADY_DEFINED #else #define yy_flush_buffer ax_flush_buffer #endif #ifdef yy_load_buffer_state #define ax_load_buffer_state_ALREADY_DEFINED #else #define yy_load_buffer_state ax_load_buffer_state #endif #ifdef yy_switch_to_buffer #define ax_switch_to_buffer_ALREADY_DEFINED #else #define yy_switch_to_buffer ax_switch_to_buffer #endif #ifdef yypush_buffer_state #define axpush_buffer_state_ALREADY_DEFINED #else #define yypush_buffer_state axpush_buffer_state #endif #ifdef yypop_buffer_state #define axpop_buffer_state_ALREADY_DEFINED #else #define yypop_buffer_state axpop_buffer_state #endif #ifdef yyensure_buffer_stack #define axensure_buffer_stack_ALREADY_DEFINED #else #define yyensure_buffer_stack axensure_buffer_stack #endif #ifdef yylex #define axlex_ALREADY_DEFINED #else #define yylex axlex #endif #ifdef yyrestart #define axrestart_ALREADY_DEFINED #else #define yyrestart axrestart #endif #ifdef yylex_init #define axlex_init_ALREADY_DEFINED #else #define yylex_init axlex_init #endif #ifdef yylex_init_extra #define axlex_init_extra_ALREADY_DEFINED #else #define yylex_init_extra axlex_init_extra #endif #ifdef yylex_destroy #define axlex_destroy_ALREADY_DEFINED #else #define yylex_destroy axlex_destroy #endif #ifdef yyget_debug #define axget_debug_ALREADY_DEFINED #else #define yyget_debug axget_debug #endif #ifdef yyset_debug #define axset_debug_ALREADY_DEFINED #else #define yyset_debug axset_debug #endif #ifdef yyget_extra #define axget_extra_ALREADY_DEFINED #else #define yyget_extra axget_extra #endif #ifdef yyset_extra #define axset_extra_ALREADY_DEFINED #else #define yyset_extra axset_extra #endif #ifdef yyget_in #define axget_in_ALREADY_DEFINED #else #define yyget_in axget_in #endif #ifdef yyset_in #define axset_in_ALREADY_DEFINED #else #define yyset_in axset_in #endif #ifdef yyget_out #define axget_out_ALREADY_DEFINED #else #define yyget_out axget_out #endif #ifdef yyset_out #define axset_out_ALREADY_DEFINED #else #define yyset_out axset_out #endif #ifdef yyget_leng #define axget_leng_ALREADY_DEFINED #else #define yyget_leng axget_leng #endif #ifdef yyget_text #define axget_text_ALREADY_DEFINED #else #define yyget_text axget_text #endif #ifdef yyget_lineno #define axget_lineno_ALREADY_DEFINED #else #define yyget_lineno axget_lineno #endif #ifdef yyset_lineno #define axset_lineno_ALREADY_DEFINED #else #define yyset_lineno axset_lineno #endif #ifdef yywrap #define axwrap_ALREADY_DEFINED #else #define yywrap axwrap #endif #ifdef yyalloc #define axalloc_ALREADY_DEFINED #else #define yyalloc axalloc #endif #ifdef yyrealloc #define axrealloc_ALREADY_DEFINED #else #define yyrealloc axrealloc #endif #ifdef yyfree #define axfree_ALREADY_DEFINED #else #define yyfree axfree #endif #ifdef yytext #define axtext_ALREADY_DEFINED #else #define yytext axtext #endif #ifdef yyleng #define axleng_ALREADY_DEFINED #else #define yyleng axleng #endif #ifdef yyin #define axin_ALREADY_DEFINED #else #define yyin axin #endif #ifdef yyout #define axout_ALREADY_DEFINED #else #define yyout axout #endif #ifdef yy_flex_debug #define ax_flex_debug_ALREADY_DEFINED #else #define yy_flex_debug ax_flex_debug #endif #ifdef yylineno #define axlineno_ALREADY_DEFINED #else #define yylineno axlineno #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #ifndef SIZE_MAX #define SIZE_MAX (~(size_t)0) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ /* begin standard C++ headers. */ /* TODO: this is always defined, so inline it */ #define yyconst const #if defined(__GNUC__) && __GNUC__ >= 3 #define yynoreturn __attribute__((__noreturn__)) #else #define yynoreturn #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an * integer in range [0..255] for use as an array index. */ #define YY_SC_TO_UI(c) ((YY_CHAR) (c)) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart( yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) #define YY_LINENO_REWIND_TO(ptr) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ int yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = NULL; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart ( FILE *input_file ); void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size ); void yy_delete_buffer ( YY_BUFFER_STATE b ); void yy_flush_buffer ( YY_BUFFER_STATE b ); void yypush_buffer_state ( YY_BUFFER_STATE new_buffer ); void yypop_buffer_state ( void ); static void yyensure_buffer_stack ( void ); static void yy_load_buffer_state ( void ); static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size ); YY_BUFFER_STATE yy_scan_string ( const char *yy_str ); YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len ); void *yyalloc ( yy_size_t ); void *yyrealloc ( void *, yy_size_t ); void yyfree ( void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define axwrap() (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef flex_uint8_t YY_CHAR; FILE *yyin = NULL, *yyout = NULL; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #ifdef yytext_ptr #undef yytext_ptr #endif #define yytext_ptr yytext static yy_state_type yy_get_previous_state ( void ); static yy_state_type yy_try_NUL_trans ( yy_state_type current_state ); static int yy_get_next_buffer ( void ); static void yynoreturn yy_fatal_error ( const char* msg ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (int) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 123 #define YY_END_OF_BUFFER 124 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static const flex_int16_t yy_accept[326] = { 0, 0, 0, 124, 122, 108, 110, 36, 122, 3, 9, 12, 40, 41, 7, 5, 37, 6, 122, 8, 113, 113, 113, 39, 1, 19, 4, 18, 38, 2, 121, 44, 45, 14, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 42, 13, 43, 15, 108, 17, 0, 111, 0, 26, 34, 27, 24, 32, 22, 33, 23, 118, 51, 50, 49, 46, 47, 48, 109, 25, 119, 113, 0, 114, 112, 94, 95, 10, 21, 16, 20, 11, 121, 28, 121, 121, 121, 121, 121, 121, 121, 121, 67, 121, 121, 121, 58, 53, 121, 121, 121, 121, 121, 121, 59, 54, 61, 121, 121, 121, 121, 121, 60, 55, 121, 121, 121, 121, 121, 121, 121, 121, 121, 57, 52, 121, 121, 121, 121, 29, 35, 115, 109, 119, 116, 0, 120, 30, 31, 121, 121, 121, 121, 121, 121, 121, 101, 121, 121, 121, 121, 121, 121, 106, 66, 121, 121, 121, 121, 72, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 117, 71, 121, 106, 101, 121, 121, 121, 121, 121, 62, 102, 121, 121, 121, 121, 121, 121, 121, 121, 107, 121, 121, 121, 121, 100, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 104, 63, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 69, 121, 121, 121, 121, 64, 75, 121, 121, 121, 102, 73, 74, 88, 87, 90, 89, 121, 121, 121, 121, 99, 121, 121, 121, 121, 121, 121, 121, 121, 121, 105, 121, 80, 79, 78, 83, 82, 81, 86, 85, 84, 121, 121, 68, 121, 121, 76, 121, 56, 92, 121, 121, 65, 103, 77, 121, 121, 121, 121, 91, 121, 121, 121, 93, 121, 121, 121, 121, 121, 121, 70, 121, 121, 121, 121, 121, 121, 96, 121, 121, 121, 97, 98, 0 } ; static const YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 5, 1, 6, 7, 8, 1, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 17, 22, 17, 23, 17, 24, 25, 26, 27, 28, 29, 30, 31, 31, 31, 31, 32, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 33, 34, 35, 36, 37, 1, 38, 39, 40, 41, 42, 43, 44, 45, 46, 31, 47, 48, 49, 50, 51, 52, 31, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static const YY_CHAR yy_meta[66] = { 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 4, 3, 1, 1, 1, 1, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1 } ; static const flex_int16_t yy_base[331] = { 0, 0, 0, 417, 418, 414, 418, 388, 61, 418, 387, 59, 418, 418, 386, 56, 418, 55, 79, 54, 126, 382, 381, 418, 418, 45, 383, 46, 418, 418, 0, 418, 418, 382, 24, 40, 38, 44, 104, 370, 81, 356, 368, 352, 362, 120, 62, 353, 121, 357, 418, 49, 418, 418, 399, 418, 74, 418, 0, 418, 418, 418, 418, 418, 418, 418, 418, 164, 418, 418, 418, 418, 418, 418, 0, 418, 171, 0, 183, 418, 418, 418, 418, 373, 418, 418, 418, 372, 0, 418, 347, 355, 341, 341, 356, 355, 342, 348, 334, 335, 332, 332, 418, 418, 338, 54, 332, 338, 333, 334, 418, 418, 0, 58, 331, 325, 68, 324, 418, 418, 327, 72, 82, 331, 327, 329, 318, 321, 75, 418, 418, 332, 318, 324, 323, 418, 418, 418, 0, 127, 418, 198, 166, 418, 418, 320, 329, 324, 323, 311, 309, 82, 324, 322, 318, 310, 316, 303, 318, 204, 0, 313, 314, 310, 306, 205, 307, 190, 293, 294, 292, 294, 296, 303, 289, 108, 288, 290, 287, 298, 297, 74, 292, 291, 210, 281, 294, 286, 418, 0, 286, 0, 0, 278, 276, 284, 273, 280, 0, 0, 274, 284, 270, 302, 304, 301, 271, 265, 0, 269, 296, 298, 295, 0, 130, 136, 269, 276, 271, 259, 256, 268, 258, 262, 257, 266, 265, 256, 0, 0, 262, 251, 251, 256, 251, 191, 192, 198, 247, 241, 254, 0, 245, 246, 251, 242, 0, 0, 250, 244, 247, 258, 0, 0, 0, 0, 0, 0, 228, 231, 245, 234, 0, 242, 239, 241, 236, 224, 233, 239, 234, 220, 0, 217, 0, 0, 0, 0, 0, 0, 0, 0, 0, 211, 225, 0, 206, 206, 0, 209, 418, 239, 216, 202, 0, 0, 0, 201, 212, 205, 211, 199, 204, 209, 200, 0, 207, 206, 206, 195, 188, 163, 0, 171, 143, 145, 121, 123, 123, 0, 108, 98, 86, 0, 0, 418, 265, 267, 271, 90, 87 } ; static const flex_int16_t yy_def[331] = { 0, 325, 1, 325, 325, 325, 325, 325, 326, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 20, 20, 325, 325, 325, 325, 325, 325, 325, 327, 325, 325, 325, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 325, 325, 325, 325, 325, 325, 326, 325, 326, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 328, 325, 325, 20, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 327, 325, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 325, 325, 327, 327, 327, 327, 327, 327, 325, 325, 327, 327, 327, 327, 327, 327, 325, 325, 327, 327, 327, 327, 327, 327, 327, 327, 327, 325, 325, 327, 327, 327, 327, 325, 325, 325, 328, 329, 325, 325, 330, 325, 325, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 325, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 325, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 327, 0, 325, 325, 325, 325, 325 } ; static const flex_int16_t yy_nxt[484] = { 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 20, 20, 21, 22, 20, 20, 23, 24, 25, 26, 27, 28, 29, 30, 30, 31, 4, 32, 33, 30, 30, 34, 35, 36, 37, 38, 30, 39, 40, 30, 41, 42, 30, 30, 43, 44, 45, 46, 47, 48, 49, 30, 30, 30, 50, 51, 52, 53, 57, 60, 63, 65, 74, 83, 84, 86, 87, 90, 135, 91, 93, 57, 97, 75, 66, 64, 92, 94, 61, 110, 95, 98, 142, 96, 99, 139, 100, 58, 67, 67, 67, 67, 67, 67, 67, 101, 124, 158, 164, 125, 58, 159, 102, 111, 136, 165, 168, 126, 172, 231, 68, 169, 174, 181, 127, 69, 112, 232, 118, 129, 324, 182, 183, 113, 70, 173, 103, 175, 194, 195, 71, 72, 73, 76, 104, 77, 77, 77, 77, 77, 77, 77, 119, 130, 105, 323, 224, 106, 322, 107, 78, 78, 108, 321, 320, 131, 225, 120, 121, 132, 78, 78, 140, 254, 133, 255, 79, 122, 319, 256, 123, 257, 80, 67, 67, 67, 67, 67, 67, 67, 139, 139, 139, 139, 139, 139, 139, 141, 318, 141, 78, 317, 142, 142, 142, 142, 142, 142, 142, 137, 78, 188, 214, 215, 295, 316, 140, 142, 142, 142, 142, 142, 142, 142, 203, 210, 204, 211, 205, 212, 191, 235, 236, 237, 274, 277, 275, 278, 315, 276, 279, 280, 309, 281, 310, 216, 282, 311, 314, 272, 228, 313, 199, 312, 272, 308, 272, 228, 307, 306, 295, 305, 304, 192, 303, 302, 301, 238, 56, 300, 56, 56, 88, 88, 138, 299, 138, 138, 298, 297, 228, 228, 296, 295, 295, 295, 294, 293, 292, 291, 290, 199, 289, 199, 199, 288, 287, 286, 285, 284, 283, 272, 273, 272, 271, 270, 269, 268, 267, 266, 265, 264, 263, 262, 261, 260, 259, 258, 253, 252, 251, 250, 249, 248, 191, 191, 191, 247, 246, 245, 244, 243, 242, 192, 192, 241, 240, 191, 239, 234, 233, 230, 229, 228, 227, 226, 223, 222, 221, 220, 219, 218, 217, 213, 209, 208, 207, 206, 202, 201, 200, 199, 198, 197, 196, 193, 192, 192, 191, 190, 189, 187, 186, 185, 184, 180, 179, 178, 177, 176, 171, 170, 167, 166, 163, 162, 161, 160, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 54, 134, 128, 117, 116, 115, 114, 109, 89, 85, 82, 81, 62, 59, 55, 54, 325, 3, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325 } ; static const flex_int16_t yy_chk[484] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 11, 15, 17, 19, 25, 25, 27, 27, 34, 51, 34, 35, 56, 36, 19, 17, 15, 34, 35, 11, 40, 35, 36, 330, 35, 37, 329, 37, 8, 18, 18, 18, 18, 18, 18, 18, 37, 46, 105, 113, 46, 56, 105, 38, 40, 51, 113, 116, 46, 121, 181, 18, 116, 122, 128, 46, 18, 40, 181, 45, 48, 322, 128, 128, 40, 18, 121, 38, 122, 151, 151, 18, 18, 18, 20, 38, 20, 20, 20, 20, 20, 20, 20, 45, 48, 38, 321, 175, 38, 320, 38, 20, 139, 38, 318, 317, 48, 175, 45, 45, 48, 20, 139, 139, 214, 48, 214, 20, 45, 316, 215, 45, 215, 20, 67, 67, 67, 67, 67, 67, 67, 76, 76, 76, 76, 76, 76, 76, 78, 315, 78, 142, 314, 78, 78, 78, 78, 78, 78, 78, 67, 142, 142, 167, 167, 313, 311, 76, 141, 141, 141, 141, 141, 141, 141, 159, 165, 159, 165, 159, 165, 165, 184, 184, 184, 235, 236, 235, 236, 310, 235, 236, 237, 301, 237, 301, 167, 237, 301, 309, 308, 307, 306, 304, 303, 302, 300, 299, 298, 297, 293, 292, 291, 289, 287, 286, 284, 283, 184, 326, 273, 326, 326, 327, 327, 328, 271, 328, 328, 270, 269, 268, 267, 266, 265, 264, 263, 261, 260, 259, 258, 251, 250, 249, 248, 245, 244, 243, 242, 240, 239, 238, 234, 233, 232, 231, 230, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 212, 211, 210, 209, 207, 206, 205, 204, 203, 202, 201, 200, 197, 196, 195, 194, 193, 190, 187, 186, 185, 183, 182, 180, 179, 178, 177, 176, 174, 173, 172, 171, 170, 169, 168, 166, 164, 163, 162, 161, 158, 157, 156, 155, 154, 153, 152, 150, 149, 148, 147, 146, 145, 134, 133, 132, 131, 127, 126, 125, 124, 123, 120, 117, 115, 114, 109, 108, 107, 106, 104, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 87, 83, 54, 49, 47, 44, 43, 42, 41, 39, 33, 26, 22, 21, 14, 10, 7, 5, 3, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325, 325 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; /* Copyright Contributors to the OpenVDB Project SPDX-License-Identifier: MPL-2.0 @file grammar/axlexer.l @authors Nick Avramoussis, Richard Jones @brief OpenVDB AX Lexer */ #include "openvdb_ax/ast/Parse.h" #include "openvdb_ax/compiler/Logger.h" #include "axparser.h" /*generated by bison*/ #include <openvdb/Platform.h> #include <cstdlib> #include <errno.h> /// @note Bypasses conversion warnings in YY_CURRENT_BUFFER macro. /// This is a bit over zealous as we only need to suppress /// -Wnull-conversion OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN extern openvdb::ax::Logger* axlog; /// @note Location tracking macro for axlloc token locations. /// YY_USER_ACTION is called before any and each lexer action /// is performed. Instead of manually tracking newlines, we /// can simply scan for them in the current text held by axtext #define YY_USER_ACTION \ assert(axlog); \ axlloc.first_line = axlloc.last_line; \ axlloc.first_column = axlloc.last_column; \ for (int i = 0; axtext[i] != '\0'; i++) { \ if (axtext[i] == '\n') { \ axlloc.last_line++; \ axlloc.last_column = 1; \ } \ else { \ axlloc.last_column++; \ } \ } /* Option 'noyywrap' indicates that when EOF is hit, yyin does not * automatically reset to another file. */ /* Options 'nounput' and 'noinput' are useful for interactive session * support. We don't support or require this. */ #define YY_NO_INPUT 1 /* Option 'prefix' creates a C++ lexer with the given prefix, so that * we can link with other flex-generated lexers in the same application * without name conflicts. */ /* Some handy macros which define constant tokens */ /* All whitespace bar new lines: * \t tabs, \v vertical tabs, \r carriage return, \f form feed (page break) * https://www.regular-expressions.info/refcharacters.html */ #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals ( void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy ( void ); int yyget_debug ( void ); void yyset_debug ( int debug_flag ); YY_EXTRA_TYPE yyget_extra ( void ); void yyset_extra ( YY_EXTRA_TYPE user_defined ); FILE *yyget_in ( void ); void yyset_in ( FILE * _in_str ); FILE *yyget_out ( void ); void yyset_out ( FILE * _out_str ); int yyget_leng ( void ); char *yyget_text ( void ); int yyget_lineno ( void ); void yyset_lineno ( int _line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap ( void ); #else extern int yywrap ( void ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy ( char *, const char *, int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen ( const char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput ( void ); #else static int input ( void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ int n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE ); } yy_load_buffer_state( ); } { while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 326 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 418 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP { return SEMICOLON; } YY_BREAK case 2: YY_RULE_SETUP { return AT; } YY_BREAK case 3: YY_RULE_SETUP { return DOLLAR; } YY_BREAK case 4: YY_RULE_SETUP { return EQUALS; } YY_BREAK case 5: YY_RULE_SETUP { return PLUS; } YY_BREAK case 6: YY_RULE_SETUP { return MINUS; } YY_BREAK case 7: YY_RULE_SETUP { return MULTIPLY; } YY_BREAK case 8: YY_RULE_SETUP { return DIVIDE; } YY_BREAK case 9: YY_RULE_SETUP { return MODULO; } YY_BREAK case 10: YY_RULE_SETUP { return SHIFTLEFT; } YY_BREAK case 11: YY_RULE_SETUP { return SHIFTRIGHT; } YY_BREAK case 12: YY_RULE_SETUP { return BITAND; } YY_BREAK case 13: YY_RULE_SETUP { return BITOR; } YY_BREAK case 14: YY_RULE_SETUP { return BITXOR; } YY_BREAK case 15: YY_RULE_SETUP { return BITNOT; } YY_BREAK case 16: YY_RULE_SETUP { return EQUALSEQUALS; } YY_BREAK case 17: YY_RULE_SETUP { return NOTEQUALS; } YY_BREAK case 18: YY_RULE_SETUP { return MORETHAN; } YY_BREAK case 19: YY_RULE_SETUP { return LESSTHAN; } YY_BREAK case 20: YY_RULE_SETUP { return MORETHANOREQUAL; } YY_BREAK case 21: YY_RULE_SETUP { return LESSTHANOREQUAL; } YY_BREAK case 22: YY_RULE_SETUP { return PLUSEQUALS; } YY_BREAK case 23: YY_RULE_SETUP { return MINUSEQUALS; } YY_BREAK case 24: YY_RULE_SETUP { return MULTIPLYEQUALS; } YY_BREAK case 25: YY_RULE_SETUP { return DIVIDEEQUALS; } YY_BREAK case 26: YY_RULE_SETUP { return MODULOEQUALS; } YY_BREAK case 27: YY_RULE_SETUP { return BITANDEQUALS; } YY_BREAK case 28: YY_RULE_SETUP { return BITXOREQUALS; } YY_BREAK case 29: YY_RULE_SETUP { return BITOREQUALS; } YY_BREAK case 30: YY_RULE_SETUP { return SHIFTLEFTEQUALS; } YY_BREAK case 31: YY_RULE_SETUP { return SHIFTRIGHTEQUALS; } YY_BREAK case 32: YY_RULE_SETUP { return PLUSPLUS; } YY_BREAK case 33: YY_RULE_SETUP { return MINUSMINUS; } YY_BREAK case 34: YY_RULE_SETUP { return AND; } YY_BREAK case 35: YY_RULE_SETUP { return OR; } YY_BREAK case 36: YY_RULE_SETUP { return NOT; } YY_BREAK case 37: YY_RULE_SETUP { return COMMA; } YY_BREAK case 38: YY_RULE_SETUP { return QUESTION; } YY_BREAK case 39: YY_RULE_SETUP { return COLON; } YY_BREAK case 40: YY_RULE_SETUP { return LPARENS; } YY_BREAK case 41: YY_RULE_SETUP { return RPARENS; } YY_BREAK case 42: YY_RULE_SETUP { return LCURLY; } YY_BREAK case 43: YY_RULE_SETUP { return RCURLY; } YY_BREAK case 44: YY_RULE_SETUP { return LSQUARE; } YY_BREAK case 45: YY_RULE_SETUP { return RSQUARE; } YY_BREAK case 46: YY_RULE_SETUP { return DOT_X; } YY_BREAK case 47: YY_RULE_SETUP { return DOT_Y; } YY_BREAK case 48: YY_RULE_SETUP { return DOT_Z; } YY_BREAK case 49: YY_RULE_SETUP { return DOT_X; } YY_BREAK case 50: YY_RULE_SETUP { return DOT_Y; } YY_BREAK case 51: YY_RULE_SETUP { return DOT_Z; } YY_BREAK case 52: YY_RULE_SETUP { return V_AT; } YY_BREAK case 53: YY_RULE_SETUP { return F_AT; } YY_BREAK case 54: YY_RULE_SETUP { return I_AT; } YY_BREAK case 55: YY_RULE_SETUP { return S_AT; } YY_BREAK case 56: YY_RULE_SETUP { return I16_AT; } YY_BREAK case 57: YY_RULE_SETUP { return V_DOLLAR; } YY_BREAK case 58: YY_RULE_SETUP { return F_DOLLAR; } YY_BREAK case 59: YY_RULE_SETUP { return I_DOLLAR; } YY_BREAK case 60: YY_RULE_SETUP { return S_DOLLAR; } YY_BREAK case 61: YY_RULE_SETUP { return IF; } YY_BREAK case 62: YY_RULE_SETUP { return ELSE; } YY_BREAK case 63: YY_RULE_SETUP { return TRUE; } YY_BREAK case 64: YY_RULE_SETUP { return FALSE; } YY_BREAK case 65: YY_RULE_SETUP { return RETURN; } YY_BREAK case 66: YY_RULE_SETUP { return FOR; } YY_BREAK case 67: YY_RULE_SETUP { return DO; } YY_BREAK case 68: YY_RULE_SETUP { return WHILE; } YY_BREAK case 69: YY_RULE_SETUP { return BREAK;} YY_BREAK case 70: YY_RULE_SETUP { return CONTINUE;} YY_BREAK case 71: YY_RULE_SETUP { return BOOL; } YY_BREAK case 72: YY_RULE_SETUP { return INT32; } YY_BREAK case 73: YY_RULE_SETUP { return INT32; } YY_BREAK case 74: YY_RULE_SETUP { return INT64; } YY_BREAK case 75: YY_RULE_SETUP { return FLOAT; } YY_BREAK case 76: YY_RULE_SETUP { return DOUBLE; } YY_BREAK case 77: YY_RULE_SETUP { return STRING; } YY_BREAK case 78: YY_RULE_SETUP { return VEC2I; } YY_BREAK case 79: YY_RULE_SETUP { return VEC2F; } YY_BREAK case 80: YY_RULE_SETUP { return VEC2D; } YY_BREAK case 81: YY_RULE_SETUP { return VEC3I; } YY_BREAK case 82: YY_RULE_SETUP { return VEC3F; } YY_BREAK case 83: YY_RULE_SETUP { return VEC3D; } YY_BREAK case 84: YY_RULE_SETUP { return VEC4I; } YY_BREAK case 85: YY_RULE_SETUP { return VEC4F; } YY_BREAK case 86: YY_RULE_SETUP { return VEC4D; } YY_BREAK case 87: YY_RULE_SETUP { return MAT3F; } YY_BREAK case 88: YY_RULE_SETUP { return MAT3D; } YY_BREAK case 89: YY_RULE_SETUP { return MAT4F; } YY_BREAK case 90: YY_RULE_SETUP { return MAT4D; } YY_BREAK /*Tokens to support VEX Syntax*/ case 91: YY_RULE_SETUP { return VEC3F; } /*VEX SUPPORT TOKENS*/ YY_BREAK case 92: YY_RULE_SETUP { return MAT4F; } YY_BREAK case 93: YY_RULE_SETUP { return MAT3F; } YY_BREAK case 94: YY_RULE_SETUP { return M3F_AT; } YY_BREAK case 95: YY_RULE_SETUP { return M4F_AT; } YY_BREAK /*Deprecated Tokens*/ case 96: YY_RULE_SETUP { axlog->warning("vectorint keyword is deprecated. use vec3i.", {axlloc.first_line, axlloc.first_column}); return VEC3I; } YY_BREAK case 97: YY_RULE_SETUP { axlog->warning("vectorfloat keyword is deprecated. use vec3f.", {axlloc.first_line, axlloc.first_column}); return VEC3F; } YY_BREAK case 98: YY_RULE_SETUP { axlog->warning("vectordouble keyword is deprecated. use vec3d.", {axlloc.first_line, axlloc.first_column}); return VEC3D; } YY_BREAK case 99: YY_RULE_SETUP { axlog->warning("short local variables have been removed. use int, int32 or int64.", {axlloc.first_line, axlloc.first_column}); return INT32; } YY_BREAK case 100: YY_RULE_SETUP { axlog->warning("long keyword is deprecated. use int64.", {axlloc.first_line, axlloc.first_column}); return INT64; } YY_BREAK /* Reserved keywords */ case 101: case 102: case 103: case 104: case 105: case 106: case 107: YY_RULE_SETUP { /* @todo: move this into parser */ std::ostringstream os; os <<"\""<< axtext << "\" is a reserved keyword."; axlog->error(os.str(), {axlloc.first_line, axlloc.first_column}); } YY_BREAK case 108: YY_RULE_SETUP { } /* ignore whitespace */ YY_BREAK case 109: YY_RULE_SETUP { } /* ignore //-style one-line comments */ YY_BREAK case 110: /* rule 110 can match eol */ YY_RULE_SETUP { } /* ignore newlines */ YY_BREAK case 111: YY_RULE_SETUP { axlval.string = strndup(axtext+1, axleng-2); return L_STRING; } YY_BREAK case 112: YY_RULE_SETUP { axlog->warning("s suffix is deprecated.", {axlloc.first_line, axlloc.first_column}); errno = 0; axlval.index = uint64_t(std::strtoull(axtext, /*end*/nullptr, /*base*/10)); if (errno == ERANGE) { errno = 0; axlog->error("integer constant is too large to be represented:", {axlloc.first_line, axlloc.first_column}); } return L_INT32; } YY_BREAK case 113: YY_RULE_SETUP { errno = 0; axlval.index = uint64_t(std::strtoull(axtext, /*end*/nullptr, /*base*/10)); if (errno == ERANGE) { errno = 0; axlog->error("integer constant is too large to be represented:", {axlloc.first_line, axlloc.first_column}); } return L_INT32; } YY_BREAK case 114: YY_RULE_SETUP { errno = 0; axlval.index = uint64_t(std::strtoull(axtext, /*end*/nullptr, /*base*/10)); if (errno == ERANGE) { errno = 0; axlog->error("integer constant is too large to be represented:", {axlloc.first_line, axlloc.first_column}); } return L_INT64; } YY_BREAK case 115: case 116: case 117: YY_RULE_SETUP { errno = 0; axlval.flt = static_cast<double>(std::strtof(axtext, /*end*/nullptr)); if (errno == ERANGE) { errno = 0; if (std::isinf(axlval.flt)) { axlog->warning("floating point constant is too large for type float, " "will be converted to inf.", {axlloc.first_line, axlloc.first_column}); } else if (axlval.flt == 0.0) { axlog->warning("floating point constant truncated to zero.", {axlloc.first_line, axlloc.first_column}); } else { axlog->warning("floating point constant is too small for type float " "and may underflow.", {axlloc.first_line, axlloc.first_column}); } } return L_FLOAT; } YY_BREAK case 118: case 119: case 120: YY_RULE_SETUP { errno = 0; axlval.flt = std::strtod(axtext, /*end*/nullptr); if (errno == ERANGE) { errno = 0; if (std::isinf(axlval.flt)) { axlog->warning("floating point constant is too large for type double, " "will be converted to inf.", {axlloc.first_line, axlloc.first_column}); } else if (axlval.flt == 0.0) { axlog->warning("floating point constant truncated to zero.", {axlloc.first_line, axlloc.first_column}); } else { axlog->warning("floating point constant is too small for type double " "and may underflow.", {axlloc.first_line, axlloc.first_column}); } } return L_DOUBLE; } YY_BREAK case 121: YY_RULE_SETUP { axlval.string = strdup(axtext); return IDENTIFIER; } YY_BREAK case 122: YY_RULE_SETUP { /* error on everything else */ /* @todo: move this into parser */ assert(axlog); axlog->error("stray or invalid character.", {axlloc.first_line, axlloc.first_column}); } YY_BREAK case 123: YY_RULE_SETUP ECHO; YY_BREAK case YY_STATE_EOF(INITIAL): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = (yytext_ptr); int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1); for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc( (void *) b->yy_ch_buf, (yy_size_t) (b->yy_buf_size + 2) ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = NULL; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart( yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); /* "- 2" to take care of EOB's */ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { yy_state_type yy_current_state; char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 326 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { int yy_is_jam; char *yy_cp = (yy_c_buf_p); YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 326 ) yy_c = yy_meta[yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; yy_is_jam = (yy_current_state == 325); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (int) ((yy_c_buf_p) - (yytext_ptr)); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart( yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return 0; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer( yyin, YY_BUF_SIZE ); } yy_init_buffer( YY_CURRENT_BUFFER, input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer( b, file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree( (void *) b->yy_ch_buf ); yyfree( (void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer( b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { yy_size_t num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return NULL; b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = NULL; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer( b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (const char * yystr ) { return yy_scan_bytes( yystr, (int) strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = (yy_size_t) (_yybytes_len + 2); buf = (char *) yyalloc( n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer( buf, n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yynoreturn yy_fatal_error (const char* msg ) { fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ int yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param _line_number line number * */ void yyset_lineno (int _line_number ) { yylineno = _line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * _in_str ) { yyin = _in_str ; } void yyset_out (FILE * _out_str ) { yyout = _out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int _bdebug ) { yy_flex_debug = _bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ (yy_buffer_stack) = NULL; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = NULL; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = NULL; yyout = NULL; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer( YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, const char * s2, int n ) { int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (const char * s ) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return malloc(size); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return realloc(ptr, size); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" OPENVDB_NO_TYPE_CONVERSION_WARNING_END
79,695
C++
27.688265
119
0.535943
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/grammar/generated/axparser.h
/* A Bison parser, made by GNU Bison 3.0.5. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY_AX_OPENVDB_AX_GRAMMAR_AXPARSER_H_INCLUDED # define YY_AX_OPENVDB_AX_GRAMMAR_AXPARSER_H_INCLUDED /* Debug traces. */ #ifndef AXDEBUG # if defined YYDEBUG #if YYDEBUG # define AXDEBUG 1 # else # define AXDEBUG 0 # endif # else /* ! defined YYDEBUG */ # define AXDEBUG 0 # endif /* ! defined YYDEBUG */ #endif /* ! defined AXDEBUG */ #if AXDEBUG extern int axdebug; #endif /* Token type. */ #ifndef AXTOKENTYPE # define AXTOKENTYPE enum axtokentype { TRUE = 258, FALSE = 259, SEMICOLON = 260, AT = 261, DOLLAR = 262, IF = 263, ELSE = 264, FOR = 265, DO = 266, WHILE = 267, RETURN = 268, BREAK = 269, CONTINUE = 270, LCURLY = 271, RCURLY = 272, LSQUARE = 273, RSQUARE = 274, STRING = 275, DOUBLE = 276, FLOAT = 277, INT32 = 278, INT64 = 279, BOOL = 280, VEC2I = 281, VEC2F = 282, VEC2D = 283, VEC3I = 284, VEC3F = 285, VEC3D = 286, VEC4I = 287, VEC4F = 288, VEC4D = 289, F_AT = 290, I_AT = 291, V_AT = 292, S_AT = 293, I16_AT = 294, MAT3F = 295, MAT3D = 296, MAT4F = 297, MAT4D = 298, M3F_AT = 299, M4F_AT = 300, F_DOLLAR = 301, I_DOLLAR = 302, V_DOLLAR = 303, S_DOLLAR = 304, DOT_X = 305, DOT_Y = 306, DOT_Z = 307, L_INT32 = 308, L_INT64 = 309, L_FLOAT = 310, L_DOUBLE = 311, L_STRING = 312, IDENTIFIER = 313, COMMA = 314, QUESTION = 315, COLON = 316, EQUALS = 317, PLUSEQUALS = 318, MINUSEQUALS = 319, MULTIPLYEQUALS = 320, DIVIDEEQUALS = 321, MODULOEQUALS = 322, BITANDEQUALS = 323, BITXOREQUALS = 324, BITOREQUALS = 325, SHIFTLEFTEQUALS = 326, SHIFTRIGHTEQUALS = 327, OR = 328, AND = 329, BITOR = 330, BITXOR = 331, BITAND = 332, EQUALSEQUALS = 333, NOTEQUALS = 334, MORETHAN = 335, LESSTHAN = 336, MORETHANOREQUAL = 337, LESSTHANOREQUAL = 338, SHIFTLEFT = 339, SHIFTRIGHT = 340, PLUS = 341, MINUS = 342, MULTIPLY = 343, DIVIDE = 344, MODULO = 345, UMINUS = 346, NOT = 347, BITNOT = 348, PLUSPLUS = 349, MINUSMINUS = 350, LPARENS = 351, RPARENS = 352, LOWER_THAN_ELSE = 353 }; #endif /* Value type. */ #if ! defined AXSTYPE && ! defined AXSTYPE_IS_DECLARED union AXSTYPE { /// @brief Temporary storage for comma separated expressions using ExpList = std::vector<openvdb::ax::ast::Expression*>; const char* string; uint64_t index; double flt; openvdb::ax::ast::Tree* tree; openvdb::ax::ast::ValueBase* value; openvdb::ax::ast::Statement* statement; openvdb::ax::ast::StatementList* statementlist; openvdb::ax::ast::Block* block; openvdb::ax::ast::Expression* expression; openvdb::ax::ast::FunctionCall* function; openvdb::ax::ast::ArrayPack* arraypack; openvdb::ax::ast::CommaOperator* comma; openvdb::ax::ast::Variable* variable; openvdb::ax::ast::ExternalVariable* external; openvdb::ax::ast::Attribute* attribute; openvdb::ax::ast::DeclareLocal* declare_local; openvdb::ax::ast::Local* local; ExpList* explist; }; typedef union AXSTYPE AXSTYPE; # define AXSTYPE_IS_TRIVIAL 1 # define AXSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined AXLTYPE && ! defined AXLTYPE_IS_DECLARED typedef struct AXLTYPE AXLTYPE; struct AXLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define AXLTYPE_IS_DECLARED 1 # define AXLTYPE_IS_TRIVIAL 1 #endif extern AXSTYPE axlval; extern AXLTYPE axlloc; int axparse (openvdb::ax::ast::Tree** tree); #endif /* !YY_AX_OPENVDB_AX_GRAMMAR_AXPARSER_H_INCLUDED */
5,263
C
23.713615
80
0.646209
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBUtil.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file OpenVDBUtil.cc /// /// @author FX R&D OpenVDB team #include "OpenVDBUtil.h" #include <openvdb/math/Math.h> #include <maya/MGlobal.h> #include <boost/algorithm/string.hpp> #include <iomanip> // std::setw, std::setfill, std::left #include <sstream> // std::stringstream #include <string> // std::string, std::getline #include <stdexcept> namespace openvdb_maya { //////////////////////////////////////// const OpenVDBData* getInputVDB(const MObject& vdb, MDataBlock& data) { MStatus status; MDataHandle inputVdbHandle = data.inputValue(vdb, &status); if (status != MS::kSuccess) { MGlobal::displayError("Invalid VDB input"); return nullptr; } MFnPluginData inputPluginData(inputVdbHandle.data()); const MPxData * inputPxData = inputPluginData.data(); if (!inputPxData) { MGlobal::displayError("Invalid VDB input"); return nullptr; } return dynamic_cast<const OpenVDBData*>(inputPxData); } void getGrids(std::vector<openvdb::GridBase::ConstPtr>& grids, const OpenVDBData& vdb, const std::string& names) { grids.clear(); if (names.empty() || names == "*") { for (size_t n = 0, N = vdb.numberOfGrids(); n < N; ++n) { grids.push_back(vdb.gridPtr(n)); } } else { for (size_t n = 0, N = vdb.numberOfGrids(); n < N; ++n) { if (vdb.grid(n).getName() == names) grids.push_back(vdb.gridPtr(n)); } } } std::string getGridNames(const OpenVDBData& vdb) { std::vector<std::string> names; for (size_t n = 0, N = vdb.numberOfGrids(); n < N; ++n) { names.push_back(vdb.grid(n).getName()); } return boost::algorithm::join(names, " "); } bool containsGrid(const std::vector<std::string>& selectionList, const std::string& gridName, size_t gridIndex) { for (size_t n = 0, N = selectionList.size(); n < N; ++n) { const std::string& word = selectionList[n]; try { return static_cast<size_t>(std::stoul(word)) == gridIndex; } catch (const std::exception&) { bool match = true; for (size_t i = 0, I = std::min(word.length(), gridName.length()); i < I; ++i) { if (word[i] == '*') { return true; } else if (word[i] != gridName[i]) { match = false; break; } } if (match && (word.length() == gridName.length())) return true; } } return selectionList.empty(); } bool getSelectedGrids(GridCPtrVec& grids, const std::string& selection, const OpenVDBData& inputVdb, OpenVDBData& outputVdb) { grids.clear(); std::vector<std::string> selectionList; boost::split(selectionList, selection, boost::is_any_of(" ")); for (size_t n = 0, N = inputVdb.numberOfGrids(); n < N; ++n) { GridCRef grid = inputVdb.grid(n); if (containsGrid(selectionList, grid.getName(), n)) { grids.push_back(inputVdb.gridPtr(n)); } else { outputVdb.insert(grid); } } return !grids.empty(); } bool getSelectedGrids(GridCPtrVec& grids, const std::string& selection, const OpenVDBData& inputVdb) { grids.clear(); std::vector<std::string> selectionList; boost::split(selectionList, selection, boost::is_any_of(" ")); for (size_t n = 0, N = inputVdb.numberOfGrids(); n < N; ++n) { GridCRef grid = inputVdb.grid(n); if (containsGrid(selectionList, grid.getName(), n)) { grids.push_back(inputVdb.gridPtr(n)); } } return !grids.empty(); } //////////////////////////////////////// void printGridInfo(std::ostream& os, const OpenVDBData& vdb) { os << "\nOutput " << vdb.numberOfGrids() << " VDB(s)\n"; openvdb::GridPtrVec::const_iterator it; size_t memUsage = 0, idx = 0; for (size_t n = 0, N = vdb.numberOfGrids(); n < N; ++n) { const openvdb::GridBase& grid = vdb.grid(n); memUsage += grid.memUsage(); openvdb::Coord dim = grid.evalActiveVoxelDim(); os << "[" << idx++ << "]"; if (!grid.getName().empty()) os << " '" << grid.getName() << "'"; os << " voxel size: " << grid.voxelSize()[0] << ", type: " << grid.valueType() << ", dim: " << dim[0] << "x" << dim[1] << "x" << dim[2] <<"\n"; } openvdb::util::printBytes(os, memUsage, "\nApproximate Memory Usage:"); } void updateNodeInfo(std::stringstream& stream, MDataBlock& data, MObject& strAttr) { MString str = stream.str().c_str(); MDataHandle strHandle = data.outputValue(strAttr); strHandle.set(str); data.setClean(strAttr); } void insertFrameNumber(std::string& str, const MTime& time, int numberingScheme) { size_t pos = str.find_first_of("#"); if (pos != std::string::npos) { size_t length = str.find_last_of("#") + 1 - pos; // Current frame value const double frame = time.as(MTime::uiUnit()); // Frames per second const MTime dummy(1.0, MTime::kSeconds); const double fps = dummy.as(MTime::uiUnit()); // Ticks per frame const double tpf = 6000.0 / fps; const int tpfDigits = int(std::log10(int(tpf)) + 1); const int wholeFrame = int(frame); std::stringstream ss; ss << std::setw(int(length)) << std::setfill('0'); if (numberingScheme == 1) { // Fractional frame values ss << wholeFrame; std::stringstream stream; stream << frame; std::string tmpStr = stream.str();; tmpStr = tmpStr.substr(tmpStr.find('.')); if (!tmpStr.empty()) ss << tmpStr; } else if (numberingScheme == 2) { // Global ticks int ticks = int(openvdb::math::Round(frame * tpf)); ss << ticks; } else { // Frame.SubTick ss << wholeFrame; const int frameTick = static_cast<int>( openvdb::math::Round(frame - double(wholeFrame)) * tpf); if (frameTick > 0) { ss << "." << std::setw(tpfDigits) << std::setfill('0') << frameTick; } } str.replace(pos, length, ss.str()); } } //////////////////////////////////////// BufferObject::BufferObject(): mVertexBuffer(0), mNormalBuffer(0), mIndexBuffer(0), mColorBuffer(0), mPrimType(GL_POINTS), mPrimNum(0) { } BufferObject::~BufferObject() { clear(); } void BufferObject::render() const { if (mPrimNum == 0 || !glIsBuffer(mIndexBuffer) || !glIsBuffer(mVertexBuffer)) { OPENVDB_LOG_DEBUG_RUNTIME("request to render empty or uninitialized buffer"); return; } const bool usesColorBuffer = glIsBuffer(mColorBuffer); const bool usesNormalBuffer = glIsBuffer(mNormalBuffer); glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, 0); if (usesColorBuffer) { glBindBuffer(GL_ARRAY_BUFFER, mColorBuffer); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(3, GL_FLOAT, 0, 0); } if (usesNormalBuffer) { glEnableClientState(GL_NORMAL_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, mNormalBuffer); glNormalPointer(GL_FLOAT, 0, 0); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer); glDrawElements(mPrimType, mPrimNum, GL_UNSIGNED_INT, 0); // disable client-side capabilities if (usesColorBuffer) glDisableClientState(GL_COLOR_ARRAY); if (usesNormalBuffer) glDisableClientState(GL_NORMAL_ARRAY); // release vbo's glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void BufferObject::genIndexBuffer(const std::vector<GLuint>& v, GLenum primType) { // clear old buffer if (glIsBuffer(mIndexBuffer) == GL_TRUE) glDeleteBuffers(1, &mIndexBuffer); // gen new buffer glGenBuffers(1, &mIndexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer); if (glIsBuffer(mIndexBuffer) == GL_FALSE) throw "Error: Unable to create index buffer"; // upload data glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * v.size(), &v[0], GL_STATIC_DRAW); // upload data if (GL_NO_ERROR != glGetError()) throw "Error: Unable to upload index buffer data"; // release buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); mPrimNum = static_cast<GLsizei>(v.size()); mPrimType = primType; } void BufferObject::genVertexBuffer(const std::vector<GLfloat>& v) { if (glIsBuffer(mVertexBuffer) == GL_TRUE) glDeleteBuffers(1, &mVertexBuffer); glGenBuffers(1, &mVertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); if (glIsBuffer(mVertexBuffer) == GL_FALSE) throw "Error: Unable to create vertex buffer"; glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * v.size(), &v[0], GL_STATIC_DRAW); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to upload vertex buffer data"; glBindBuffer(GL_ARRAY_BUFFER, 0); } void BufferObject::genNormalBuffer(const std::vector<GLfloat>& v) { if (glIsBuffer(mNormalBuffer) == GL_TRUE) glDeleteBuffers(1, &mNormalBuffer); glGenBuffers(1, &mNormalBuffer); glBindBuffer(GL_ARRAY_BUFFER, mNormalBuffer); if (glIsBuffer(mNormalBuffer) == GL_FALSE) throw "Error: Unable to create normal buffer"; glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * v.size(), &v[0], GL_STATIC_DRAW); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to upload normal buffer data"; glBindBuffer(GL_ARRAY_BUFFER, 0); } void BufferObject::genColorBuffer(const std::vector<GLfloat>& v) { if (glIsBuffer(mColorBuffer) == GL_TRUE) glDeleteBuffers(1, &mColorBuffer); glGenBuffers(1, &mColorBuffer); glBindBuffer(GL_ARRAY_BUFFER, mColorBuffer); if (glIsBuffer(mColorBuffer) == GL_FALSE) throw "Error: Unable to create color buffer"; glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * v.size(), &v[0], GL_STATIC_DRAW); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to upload color buffer data"; glBindBuffer(GL_ARRAY_BUFFER, 0); } void BufferObject::clear() { if (glIsBuffer(mIndexBuffer) == GL_TRUE) glDeleteBuffers(1, &mIndexBuffer); if (glIsBuffer(mVertexBuffer) == GL_TRUE) glDeleteBuffers(1, &mVertexBuffer); if (glIsBuffer(mColorBuffer) == GL_TRUE) glDeleteBuffers(1, &mColorBuffer); if (glIsBuffer(mNormalBuffer) == GL_TRUE) glDeleteBuffers(1, &mNormalBuffer); mPrimType = GL_POINTS; mPrimNum = 0; } //////////////////////////////////////// ShaderProgram::ShaderProgram(): mProgram(0), mVertShader(0), mFragShader(0) { } ShaderProgram::~ShaderProgram() { clear(); } void ShaderProgram::setVertShader(const std::string& s) { mVertShader = glCreateShader(GL_VERTEX_SHADER); if (glIsShader(mVertShader) == GL_FALSE) throw "Error: Unable to create shader program."; GLint length = static_cast<GLint>(s.length()); const char *str = s.c_str(); glShaderSource(mVertShader, 1, &str, &length); glCompileShader(mVertShader); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to compile vertex shader."; } void ShaderProgram::setFragShader(const std::string& s) { mFragShader = glCreateShader(GL_FRAGMENT_SHADER); if (glIsShader(mFragShader) == GL_FALSE) throw "Error: Unable to create shader program."; GLint length = static_cast<GLint>(s.length()); const char *str = s.c_str(); glShaderSource(mFragShader, 1, &str, &length); glCompileShader(mFragShader); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to compile fragment shader."; } void ShaderProgram::build() { mProgram = glCreateProgram(); if (glIsProgram(mProgram) == GL_FALSE) throw "Error: Unable to create shader program."; if (glIsShader(mVertShader) == GL_TRUE) glAttachShader(mProgram, mVertShader); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to attach vertex shader."; if (glIsShader(mFragShader) == GL_TRUE) glAttachShader(mProgram, mFragShader); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to attach fragment shader."; glLinkProgram(mProgram); GLint linked; glGetProgramiv(mProgram, GL_LINK_STATUS, &linked); if (!linked) throw "Error: Unable to link shader program."; } void ShaderProgram::build(const std::vector<GLchar*>& attributes) { mProgram = glCreateProgram(); if (glIsProgram(mProgram) == GL_FALSE) throw "Error: Unable to create shader program."; for (GLuint n = 0, N = static_cast<GLuint>(attributes.size()); n < N; ++n) { glBindAttribLocation(mProgram, n, attributes[n]); } if (glIsShader(mVertShader) == GL_TRUE) glAttachShader(mProgram, mVertShader); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to attach vertex shader."; if (glIsShader(mFragShader) == GL_TRUE) glAttachShader(mProgram, mFragShader); if (GL_NO_ERROR != glGetError()) throw "Error: Unable to attach fragment shader."; glLinkProgram(mProgram); GLint linked; glGetProgramiv(mProgram, GL_LINK_STATUS, &linked); if (!linked) throw "Error: Unable to link shader program."; } void ShaderProgram::startShading() const { if (glIsProgram(mProgram) == GL_FALSE) throw "Error: called startShading() on uncompiled shader program."; glUseProgram(mProgram); } void ShaderProgram::stopShading() const { glUseProgram(0); } void ShaderProgram::clear() { GLsizei numShaders; GLuint shaders[2]; glGetAttachedShaders(mProgram, 2, &numShaders, shaders); // detach and remove shaders for (GLsizei n = 0; n < numShaders; ++n) { glDetachShader(mProgram, shaders[n]); if (glIsShader(shaders[n]) == GL_TRUE) glDeleteShader(shaders[n]); } // remove program if (glIsProgram(mProgram)) glDeleteProgram(mProgram); } //////////////////////////////////////// WireBoxBuilder::WireBoxBuilder( const openvdb::math::Transform& xform, std::vector<GLuint>& indices, std::vector<GLfloat>& points, std::vector<GLfloat>& colors) : mXForm(&xform) , mIndices(&indices) , mPoints(&points) , mColors(&colors) { } void WireBoxBuilder::add(GLuint boxIndex, const openvdb::CoordBBox& bbox, const openvdb::Vec3s& color) { GLuint ptnCount = boxIndex * 8; // Generate corner points GLuint ptnOffset = ptnCount * 3; GLuint colorOffset = ptnOffset; // Nodes are rendered as cell-centered const openvdb::Vec3d min(bbox.min().x()-0.5, bbox.min().y()-0.5, bbox.min().z()-0.5); const openvdb::Vec3d max(bbox.max().x()+0.5, bbox.max().y()+0.5, bbox.max().z()+0.5); // corner 1 openvdb::Vec3d ptn = mXForm->indexToWorld(min); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[2]); // corner 2 ptn.x() = min.x(); ptn.y() = min.y(); ptn.z() = max.z(); ptn = mXForm->indexToWorld(ptn); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[2]); // corner 3 ptn.x() = max.x(); ptn.y() = min.y(); ptn.z() = max.z(); ptn = mXForm->indexToWorld(ptn); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[2]); // corner 4 ptn.x() = max.x(); ptn.y() = min.y(); ptn.z() = min.z(); ptn = mXForm->indexToWorld(ptn); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[2]); // corner 5 ptn.x() = min.x(); ptn.y() = max.y(); ptn.z() = min.z(); ptn = mXForm->indexToWorld(ptn); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[2]); // corner 6 ptn.x() = min.x(); ptn.y() = max.y(); ptn.z() = max.z(); ptn = mXForm->indexToWorld(ptn); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[2]); // corner 7 ptn = mXForm->indexToWorld(max); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[2]); // corner 8 ptn.x() = max.x(); ptn.y() = max.y(); ptn.z() = min.z(); ptn = mXForm->indexToWorld(ptn); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[0]); (*mPoints)[ptnOffset++] = static_cast<GLfloat>(ptn[1]); (*mPoints)[ptnOffset] = static_cast<GLfloat>(ptn[2]); for (int n = 0; n < 8; ++n) { (*mColors)[colorOffset++] = color[0]; (*mColors)[colorOffset++] = color[1]; (*mColors)[colorOffset++] = color[2]; } // Generate edges GLuint edgeOffset = boxIndex * 24; // edge 1 (*mIndices)[edgeOffset++] = ptnCount; (*mIndices)[edgeOffset++] = ptnCount + 1; // edge 2 (*mIndices)[edgeOffset++] = ptnCount + 1; (*mIndices)[edgeOffset++] = ptnCount + 2; // edge 3 (*mIndices)[edgeOffset++] = ptnCount + 2; (*mIndices)[edgeOffset++] = ptnCount + 3; // edge 4 (*mIndices)[edgeOffset++] = ptnCount + 3; (*mIndices)[edgeOffset++] = ptnCount; // edge 5 (*mIndices)[edgeOffset++] = ptnCount + 4; (*mIndices)[edgeOffset++] = ptnCount + 5; // edge 6 (*mIndices)[edgeOffset++] = ptnCount + 5; (*mIndices)[edgeOffset++] = ptnCount + 6; // edge 7 (*mIndices)[edgeOffset++] = ptnCount + 6; (*mIndices)[edgeOffset++] = ptnCount + 7; // edge 8 (*mIndices)[edgeOffset++] = ptnCount + 7; (*mIndices)[edgeOffset++] = ptnCount + 4; // edge 9 (*mIndices)[edgeOffset++] = ptnCount; (*mIndices)[edgeOffset++] = ptnCount + 4; // edge 10 (*mIndices)[edgeOffset++] = ptnCount + 1; (*mIndices)[edgeOffset++] = ptnCount + 5; // edge 11 (*mIndices)[edgeOffset++] = ptnCount + 2; (*mIndices)[edgeOffset++] = ptnCount + 6; // edge 12 (*mIndices)[edgeOffset++] = ptnCount + 3; (*mIndices)[edgeOffset] = ptnCount + 7; } } // namespace util
18,587
C++
27.908243
102
0.609566
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBReadNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <openvdb/io/Stream.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnPluginData.h> #include <maya/MFnStringData.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnUnitAttribute.h> #include <maya/MFnEnumAttribute.h> #include <fstream> #include <sstream> // std::stringstream namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBReadNode : public MPxNode { OpenVDBReadNode() {} virtual ~OpenVDBReadNode() {} virtual MStatus compute(const MPlug& plug, MDataBlock& data); static void* creator(); static MStatus initialize(); static MTypeId id; static MObject aVdbFilePath; static MObject aFrameNumbering; static MObject aInputTime; static MObject aVdbOutput; static MObject aNodeInfo; }; MTypeId OpenVDBReadNode::id(0x00108A51); MObject OpenVDBReadNode::aVdbFilePath; MObject OpenVDBReadNode::aFrameNumbering; MObject OpenVDBReadNode::aInputTime; MObject OpenVDBReadNode::aVdbOutput; MObject OpenVDBReadNode::aNodeInfo; namespace { mvdb::NodeRegistry registerNode("OpenVDBRead", OpenVDBReadNode::id, OpenVDBReadNode::creator, OpenVDBReadNode::initialize); } //////////////////////////////////////// void* OpenVDBReadNode::creator() { return new OpenVDBReadNode(); } MStatus OpenVDBReadNode::initialize() { MStatus stat; MFnTypedAttribute tAttr; MFnEnumAttribute eAttr; MFnUnitAttribute unitAttr; MFnStringData fnStringData; MObject defaultStringData = fnStringData.create(""); MObject emptyStr = fnStringData.create(""); // Setup the input attributes aVdbFilePath = tAttr.create("VdbFilePath", "file", MFnData::kString, defaultStringData, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aVdbFilePath); if (stat != MS::kSuccess) return stat; aFrameNumbering = eAttr.create("FrameNumbering", "numbering", 0, &stat); if (stat != MS::kSuccess) return stat; eAttr.addField("Frame.SubTick", 0); eAttr.addField("Fractional frame values", 1); eAttr.addField("Global ticks", 2); eAttr.setConnectable(false); stat = addAttribute(aFrameNumbering); if (stat != MS::kSuccess) return stat; aInputTime = unitAttr.create("inputTime", "int", MTime(0.0, MTime::kFilm)); unitAttr.setKeyable(true); unitAttr.setReadable(true); unitAttr.setWritable(true); unitAttr.setStorable(true); stat = addAttribute(aInputTime); if (stat != MS::kSuccess) return stat; // Setup the output attributes aVdbOutput = tAttr.create("VdbOutput", "vdb", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setWritable(false); tAttr.setStorable(false); stat = addAttribute(aVdbOutput); if (stat != MS::kSuccess) return stat; aNodeInfo = tAttr.create("NodeInfo", "info", MFnData::kString, emptyStr, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); stat = addAttribute(aNodeInfo); if (stat != MS::kSuccess) return stat; // Set the attribute dependencies stat = attributeAffects(aVdbFilePath, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFrameNumbering, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aInputTime, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbFilePath, aNodeInfo); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFrameNumbering, aNodeInfo); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aInputTime, aNodeInfo); if (stat != MS::kSuccess) return stat; return MS::kSuccess; } //////////////////////////////////////// MStatus OpenVDBReadNode::compute(const MPlug& plug, MDataBlock& data) { if (plug == aVdbOutput || plug == aNodeInfo) { MStatus status; const int numberingScheme = data.inputValue(aFrameNumbering , &status).asInt(); MDataHandle filePathHandle = data.inputValue (aVdbFilePath, &status); if (status != MS::kSuccess) return status; std::string filename = filePathHandle.asString().asChar(); if (filename.empty()) { return MS::kUnknownParameter; } MTime time = data.inputValue(aInputTime).asTime(); mvdb::insertFrameNumber(filename, time, numberingScheme); std::stringstream infoStr; infoStr << "File: " << filename << "\n"; std::ifstream ifile(filename.c_str(), std::ios_base::binary); openvdb::GridPtrVecPtr grids = openvdb::io::Stream(ifile).getGrids(); if (grids && !grids->empty()) { MFnPluginData outputDataCreators; outputDataCreators.create(OpenVDBData::id, &status); if (status != MS::kSuccess) return status; OpenVDBData* vdb = static_cast<OpenVDBData*>(outputDataCreators.data(&status)); if (status != MS::kSuccess) return status; vdb->insert(*grids); MDataHandle outHandle = data.outputValue(aVdbOutput); outHandle.set(vdb); infoStr << "Frame: " << time.as(MTime::uiUnit()) << " -> loaded\n"; mvdb::printGridInfo(infoStr, *vdb); } else { infoStr << "Frame: " << time.as(MTime::uiUnit()) << " -> no matching file.\n"; } mvdb::updateNodeInfo(infoStr, data, aNodeInfo); return data.setClean(plug); } return MS::kUnknownParameter; }
5,803
C++
27.732673
99
0.657936
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBUtil.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #ifndef OPENVDB_MAYA_UTIL_HAS_BEEN_INCLUDED #define OPENVDB_MAYA_UTIL_HAS_BEEN_INCLUDED #include "OpenVDBData.h" #include <openvdb/openvdb.h> #include <openvdb/Types.h> #include <openvdb/tree/LeafManager.h> #include <openvdb/tools/VolumeToMesh.h> #include <openvdb/util/Formats.h> // printBytes #include <tbb/tick_count.h> #include <maya/M3dView.h> #include <maya/MString.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MFnPluginData.h> #include <maya/MTime.h> #if defined(__APPLE__) || defined(MACOSX) #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #include <algorithm> // for std::min(), std::max() #include <cmath> // for std::abs(), std::floor() #include <iostream> #include <limits> #include <sstream> #include <string> #include <type_traits> #include <vector> //////////////////////////////////////// namespace openvdb_maya { using Grid = openvdb::GridBase; using GridPtr = openvdb::GridBase::Ptr; using GridCPtr = openvdb::GridBase::ConstPtr; using GridRef = openvdb::GridBase&; using GridCRef = const openvdb::GridBase&; using GridPtrVec = openvdb::GridPtrVec; using GridPtrVecIter = GridPtrVec::iterator; using GridPtrVecCIter = GridPtrVec::const_iterator; using GridCPtrVec = openvdb::GridCPtrVec; using GridCPtrVecIter = GridCPtrVec::iterator; using GridCPtrVecCIter = GridCPtrVec::const_iterator; //////////////////////////////////////// /// @brief Return a pointer to the input VDB data object or nullptr if this fails. const OpenVDBData* getInputVDB(const MObject& vdb, MDataBlock& data); void getGrids(std::vector<openvdb::GridBase::ConstPtr>& grids, const OpenVDBData& vdb, const std::string& names); std::string getGridNames(const OpenVDBData& vdb); bool containsGrid(const std::vector<std::string>& selectionList, const std::string& gridName, size_t gridIndex); /// @brief Constructs a list of selected grids @c grids from /// the @c inputVdb and passes through unselected grids /// to the @c outputVdb. /// /// @return @c false if no matching grids were found. bool getSelectedGrids(GridCPtrVec& grids, const std::string& selection, const OpenVDBData& inputVdb, OpenVDBData& outputVdb); /// @brief Constructs a list of selected grids @c grids from /// the @c inputVdb. /// /// @return @c false if no matching grids were found. bool getSelectedGrids(GridCPtrVec& grids, const std::string& selection, const OpenVDBData& inputVdb); /// @brief Replaces a sequence of pound signs (#) with the current /// frame number. /// /// @details The number of pound signs defines the zero padding width. /// For example '###' for frame 5 would produce "name.005.type" /// /// @note Supports three numbering schemes: /// 0 = Frame.SubTick /// 1 = Fractional frame values /// 2 = Global ticks void insertFrameNumber(std::string& str, const MTime& time, int numberingScheme = 0); //////////////////////////////////////// // Statistics and grid info struct Timer { Timer() : mStamp(tbb::tick_count::now()) { } void reset() { mStamp = tbb::tick_count::now(); } double seconds() const { return (tbb::tick_count::now() - mStamp).seconds(); } std::string elapsedTime() const { double sec = seconds(); return sec < 1.0 ? (std::to_string(sec * 1000.0) + " ms") : (std::to_string(sec) + " s"); } private: tbb::tick_count mStamp; }; void printGridInfo(std::ostream& os, const OpenVDBData& vdb); void updateNodeInfo(std::stringstream& stream, MDataBlock& data, MObject& strAttr); //////////////////////////////////////// // OpenGL helper objects class BufferObject { public: BufferObject(); BufferObject(const BufferObject&) = default; ~BufferObject(); void render() const; /// @note accepted @c primType: GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, /// GL_LINES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_TRIANGLES, /// GL_QUAD_STRIP, GL_QUADS and GL_POLYGON void genIndexBuffer(const std::vector<GLuint>&, GLenum primType); void genVertexBuffer(const std::vector<GLfloat>&); void genNormalBuffer(const std::vector<GLfloat>&); void genColorBuffer(const std::vector<GLfloat>&); void clear(); private: GLuint mVertexBuffer, mNormalBuffer, mIndexBuffer, mColorBuffer; GLenum mPrimType; GLsizei mPrimNum; }; class ShaderProgram { public: ShaderProgram(); ~ShaderProgram(); void setVertShader(const std::string&); void setFragShader(const std::string&); void build(); void build(const std::vector<GLchar*>& attributes); void startShading() const; void stopShading() const; void clear(); private: GLuint mProgram, mVertShader, mFragShader; }; //////////////////////////////////////// namespace util { template<class TreeType> class MinMaxVoxel { public: using LeafArray = openvdb::tree::LeafManager<TreeType>; using ValueType = typename TreeType::ValueType; // LeafArray = openvdb::tree::LeafManager<TreeType> leafs(myTree) MinMaxVoxel(LeafArray&); void runParallel(); void runSerial(); const ValueType& minVoxel() const { return mMin; } const ValueType& maxVoxel() const { return mMax; } inline MinMaxVoxel(const MinMaxVoxel<TreeType>&, tbb::split); inline void operator()(const tbb::blocked_range<size_t>&); inline void join(const MinMaxVoxel<TreeType>&); private: LeafArray& mLeafArray; ValueType mMin, mMax; }; template <class TreeType> MinMaxVoxel<TreeType>::MinMaxVoxel(LeafArray& leafs) : mLeafArray(leafs) , mMin(std::numeric_limits<ValueType>::max()) , mMax(-mMin) { } template <class TreeType> inline MinMaxVoxel<TreeType>::MinMaxVoxel(const MinMaxVoxel<TreeType>& rhs, tbb::split) : mLeafArray(rhs.mLeafArray) , mMin(std::numeric_limits<ValueType>::max()) , mMax(-mMin) { } template <class TreeType> void MinMaxVoxel<TreeType>::runParallel() { tbb::parallel_reduce(mLeafArray.getRange(), *this); } template <class TreeType> void MinMaxVoxel<TreeType>::runSerial() { (*this)(mLeafArray.getRange()); } template <class TreeType> inline void MinMaxVoxel<TreeType>::operator()(const tbb::blocked_range<size_t>& range) { typename TreeType::LeafNodeType::ValueOnCIter iter; for (size_t n = range.begin(); n < range.end(); ++n) { iter = mLeafArray.leaf(n).cbeginValueOn(); for (; iter; ++iter) { const ValueType value = iter.getValue(); mMin = std::min(mMin, value); mMax = std::max(mMax, value); } } } template <class TreeType> inline void MinMaxVoxel<TreeType>::join(const MinMaxVoxel<TreeType>& rhs) { mMin = std::min(mMin, rhs.mMin); mMax = std::max(mMax, rhs.mMax); } } // namespace util //////////////////////////////////////// ///@todo Move this into a graphics library. // Should be shared with the stand alone viewer. class WireBoxBuilder { public: WireBoxBuilder(const openvdb::math::Transform& xform, std::vector<GLuint>& indices, std::vector<GLfloat>& points, std::vector<GLfloat>& colors); void add(GLuint boxIndex, const openvdb::CoordBBox& bbox, const openvdb::Vec3s& color); private: const openvdb::math::Transform *mXForm; std::vector<GLuint> *mIndices; std::vector<GLfloat> *mPoints; std::vector<GLfloat> *mColors; }; // WireBoxBuilder class BoundingBoxGeo { public: BoundingBoxGeo(BufferObject& buffer) : mBuffer(&buffer) , mMin(-1.0) , mMax(1.0) { } void operator()(openvdb::GridBase::ConstPtr grid) { const size_t N = 8 * 3; std::vector<GLuint> indices(N); std::vector<GLfloat> points(N); std::vector<GLfloat> colors(N); WireBoxBuilder boxBuilder(grid->constTransform(), indices, points, colors); boxBuilder.add(0, grid->evalActiveVoxelBoundingBox(), openvdb::Vec3s(0.045f, 0.045f, 0.045f)); // store the sorted min/max points. mMin[0] = std::numeric_limits<float>::max(); mMin[1] = mMin[0]; mMin[2] = mMin[0]; mMax[0] = -mMin[0]; mMax[1] = -mMin[0]; mMax[2] = -mMin[0]; for (int i = 0; i < 8; ++i) { int p = i * 3; mMin[0] = std::min(mMin[0], points[p]); mMin[1] = std::min(mMin[1], points[p+1]); mMin[2] = std::min(mMin[2], points[p+2]); mMax[0] = std::max(mMax[0], points[p]); mMax[1] = std::max(mMax[1], points[p+1]); mMax[2] = std::max(mMax[2], points[p+2]); } // gen buffers and upload data to GPU (ignoring color array) mBuffer->genVertexBuffer(points); mBuffer->genIndexBuffer(indices, GL_LINES); } const openvdb::Vec3s& min() const { return mMin; } const openvdb::Vec3s& max() const { return mMax; } private: BufferObject *mBuffer; openvdb::Vec3s mMin, mMax; }; // BoundingBoxGeo class InternalNodesGeo { public: InternalNodesGeo(BufferObject& buffer) : mBuffer(&buffer) {} template<typename GridType> void operator()(typename GridType::ConstPtr grid) { size_t nodeCount = grid->tree().nonLeafCount(); const size_t N = nodeCount * 8 * 3; std::vector<GLuint> indices(N); std::vector<GLfloat> points(N); std::vector<GLfloat> colors(N); WireBoxBuilder boxBuilder(grid->constTransform(), indices, points, colors); openvdb::CoordBBox bbox(openvdb::Coord(0), openvdb::Coord(10)); size_t boxIndex = 0; typename GridType::TreeType::NodeCIter iter = grid->tree().cbeginNode(); iter.setMaxDepth(GridType::TreeType::NodeCIter::LEAF_DEPTH - 1); const openvdb::Vec3s nodeColor[2] = { openvdb::Vec3s(0.0432f, 0.33f, 0.0411023f), // first internal node level openvdb::Vec3s(0.871f, 0.394f, 0.01916f) // intermediate internal node levels }; for ( ; iter; ++iter) { iter.getBoundingBox(bbox); boxBuilder.add(static_cast<GLuint>(boxIndex++), bbox, nodeColor[(iter.getLevel() == 1)]); } // end node iteration // gen buffers and upload data to GPU mBuffer->genVertexBuffer(points); mBuffer->genColorBuffer(colors); mBuffer->genIndexBuffer(indices, GL_LINES); } private: BufferObject *mBuffer; }; // InternalNodesGeo class LeafNodesGeo { public: LeafNodesGeo(BufferObject& buffer) : mBuffer(&buffer) {} template<typename GridType> void operator()(typename GridType::ConstPtr grid) { using TreeType = typename GridType::TreeType; openvdb::tree::LeafManager<const TreeType> leafs(grid->tree()); const size_t N = leafs.leafCount() * 8 * 3; std::vector<GLuint> indices(N); std::vector<GLfloat> points(N); std::vector<GLfloat> colors(N); WireBoxBuilder boxBuilder(grid->constTransform(), indices, points, colors); const openvdb::Vec3s color(0.00608299f, 0.279541f, 0.625f); // leaf node color tbb::parallel_for(leafs.getRange(), LeafOp<TreeType>(leafs, boxBuilder, color)); // gen buffers and upload data to GPU mBuffer->genVertexBuffer(points); mBuffer->genColorBuffer(colors); mBuffer->genIndexBuffer(indices, GL_LINES); } protected: template<typename TreeType> struct LeafOp { using LeafManagerType = openvdb::tree::LeafManager<const TreeType>; LeafOp(const LeafManagerType& leafs, WireBoxBuilder& boxBuilder, const openvdb::Vec3s& color) : mLeafs(&leafs), mBoxBuilder(&boxBuilder), mColor(color) {} void operator()(const tbb::blocked_range<size_t>& range) const { openvdb::CoordBBox bbox; openvdb::Coord& min = bbox.min(); openvdb::Coord& max = bbox.max(); const int offset = int(TreeType::LeafNodeType::DIM) - 1; for (size_t n = range.begin(); n < range.end(); ++n) { min = mLeafs->leaf(n).origin(); max[0] = min[0] + offset; max[1] = min[1] + offset; max[2] = min[2] + offset; mBoxBuilder->add(static_cast<GLuint>(n), bbox, mColor); } } private: const LeafManagerType *mLeafs; WireBoxBuilder *mBoxBuilder; const openvdb::Vec3s mColor; }; // LeafOp private: BufferObject *mBuffer; }; // LeafNodesGeo class ActiveTileGeo { public: ActiveTileGeo(BufferObject& buffer) : mBuffer(&buffer) {} template<typename GridType> void operator()(typename GridType::ConstPtr grid) { using TreeType = typename GridType::TreeType; const openvdb::Index maxDepth = TreeType::ValueAllIter::LEAF_DEPTH - 1; size_t tileCount = 0; { typename TreeType::ValueOnCIter iter(grid->tree()); iter.setMaxDepth(maxDepth); for ( ; iter; ++iter) { ++tileCount; } } const size_t N = tileCount * 8 * 3; std::vector<GLuint> indices(N); std::vector<GLfloat> points(N); std::vector<GLfloat> colors(N); WireBoxBuilder boxBuilder(grid->constTransform(), indices, points, colors); const openvdb::Vec3s color(0.9f, 0.3f, 0.3f); openvdb::CoordBBox bbox; size_t boxIndex = 0; typename TreeType::ValueOnCIter iter(grid->tree()); iter.setMaxDepth(maxDepth); for ( ; iter; ++iter) { iter.getBoundingBox(bbox); boxBuilder.add(static_cast<GLuint>(boxIndex++), bbox, color); } // end tile iteration // gen buffers and upload data to GPU mBuffer->genVertexBuffer(points); mBuffer->genColorBuffer(colors); mBuffer->genIndexBuffer(indices, GL_LINES); } private: BufferObject *mBuffer; }; // ActiveTileGeo class SurfaceGeo { public: SurfaceGeo(BufferObject& buffer, float iso) : mBuffer(&buffer), mIso(iso) {} template<typename GridType> void operator()(typename GridType::ConstPtr grid) { openvdb::tools::VolumeToMesh mesher(mIso); mesher(*grid); // Copy points and generate point normals. std::vector<GLfloat> points(mesher.pointListSize() * 3); std::vector<GLfloat> normals(mesher.pointListSize() * 3); openvdb::tree::ValueAccessor<const typename GridType::TreeType> acc(grid->tree()); openvdb::math::GenericMap map(grid->transform()); openvdb::Coord ijk; for (size_t n = 0, i = 0, N = mesher.pointListSize(); n < N; ++n) { const openvdb::Vec3s& p = mesher.pointList()[n]; points[i++] = p[0]; points[i++] = p[1]; points[i++] = p[2]; } // Copy primitives openvdb::tools::PolygonPoolList& polygonPoolList = mesher.polygonPoolList(); size_t numQuads = 0; for (size_t n = 0, N = mesher.polygonPoolListSize(); n < N; ++n) { numQuads += polygonPoolList[n].numQuads(); } std::vector<GLuint> indices; indices.reserve(numQuads * 4); openvdb::Vec3d normal, e1, e2; for (size_t n = 0, N = mesher.polygonPoolListSize(); n < N; ++n) { const openvdb::tools::PolygonPool& polygons = polygonPoolList[n]; for (size_t i = 0, I = polygons.numQuads(); i < I; ++i) { const openvdb::Vec4I& quad = polygons.quad(i); indices.push_back(quad[0]); indices.push_back(quad[1]); indices.push_back(quad[2]); indices.push_back(quad[3]); e1 = mesher.pointList()[quad[1]]; e1 -= mesher.pointList()[quad[0]]; e2 = mesher.pointList()[quad[2]]; e2 -= mesher.pointList()[quad[1]]; normal = e1.cross(e2); const double length = normal.length(); if (length > 1.0e-7) normal *= (1.0 / length); for (int v = 0; v < 4; ++v) { normals[quad[v]*3] = static_cast<GLfloat>(-normal[0]); normals[quad[v]*3+1] = static_cast<GLfloat>(-normal[1]); normals[quad[v]*3+2] = static_cast<GLfloat>(-normal[2]); } } } // Construct and transfer GPU buffers. mBuffer->genVertexBuffer(points); mBuffer->genNormalBuffer(normals); mBuffer->genIndexBuffer(indices, GL_QUADS); } private: BufferObject *mBuffer; float mIso; }; // SurfaceGeo template<typename TreeType> class PointGenerator { public: using LeafManagerType = openvdb::tree::LeafManager<TreeType>; PointGenerator( std::vector<GLfloat>& points, std::vector<GLuint>& indices, LeafManagerType& leafs, std::vector<unsigned>& indexMap, const openvdb::math::Transform& transform, size_t voxelsPerLeaf = TreeType::LeafNodeType::NUM_VOXELS) : mPoints(&points) , mIndices(&indices) , mLeafs(&leafs) , mIndexMap(&indexMap) , mTransform(&transform) , mVoxelsPerLeaf(voxelsPerLeaf) { } void runParallel() { tbb::parallel_for(mLeafs->getRange(), *this); } inline void operator()(const tbb::blocked_range<size_t>& range) const { using ValueOnCIter = typename TreeType::LeafNodeType::ValueOnCIter; openvdb::Vec3d pos; unsigned index = 0; size_t activeVoxels = 0; for (size_t n = range.begin(); n < range.end(); ++n) { index = (*mIndexMap)[n]; ValueOnCIter it = mLeafs->leaf(n).cbeginValueOn(); activeVoxels = mLeafs->leaf(n).onVoxelCount(); if (activeVoxels <= mVoxelsPerLeaf) { for ( ; it; ++it) { pos = mTransform->indexToWorld(it.getCoord()); insertPoint(pos, index); ++index; } } else if (1 == mVoxelsPerLeaf) { pos = mTransform->indexToWorld(it.getCoord()); insertPoint(pos, index); } else { std::vector<openvdb::Coord> coords; coords.reserve(activeVoxels); for ( ; it; ++it) { coords.push_back(it.getCoord()); } pos = mTransform->indexToWorld(coords[0]); insertPoint(pos, index); ++index; pos = mTransform->indexToWorld(coords[activeVoxels-1]); insertPoint(pos, index); ++index; int r = int(std::floor(mVoxelsPerLeaf / activeVoxels)); for (int i = 1, I = static_cast<int>(mVoxelsPerLeaf) - 2; i < I; ++i) { pos = mTransform->indexToWorld(coords[i * r]); insertPoint(pos, index); ++index; } } } } private: void insertPoint(const openvdb::Vec3d& pos, unsigned index) const { (*mIndices)[index] = index; const unsigned element = index * 3; (*mPoints)[element ] = static_cast<GLfloat>(pos[0]); (*mPoints)[element + 1] = static_cast<GLfloat>(pos[1]); (*mPoints)[element + 2] = static_cast<GLfloat>(pos[2]); } std::vector<GLfloat> *mPoints; std::vector<GLuint> *mIndices; LeafManagerType *mLeafs; std::vector<unsigned> *mIndexMap; const openvdb::math::Transform *mTransform; const size_t mVoxelsPerLeaf; }; // PointGenerator template<typename GridType> class PointAttributeGenerator { public: using ValueType = typename GridType::ValueType; PointAttributeGenerator( std::vector<GLfloat>& points, std::vector<GLfloat>& colors, const GridType& grid, ValueType minValue, ValueType maxValue, openvdb::Vec3s (&colorMap)[4], bool isLevelSet = false) : mPoints(&points) , mColors(&colors) , mNormals(nullptr) , mGrid(&grid) , mAccessor(grid.tree()) , mMinValue(minValue) , mMaxValue(maxValue) , mColorMap(colorMap) , mIsLevelSet(isLevelSet) , mZeroValue(openvdb::zeroVal<ValueType>()) { init(); } PointAttributeGenerator( std::vector<GLfloat>& points, std::vector<GLfloat>& colors, std::vector<GLfloat>& normals, const GridType& grid, ValueType minValue, ValueType maxValue, openvdb::Vec3s (&colorMap)[4], bool isLevelSet = false) : mPoints(&points) , mColors(&colors) , mNormals(&normals) , mGrid(&grid) , mAccessor(grid.tree()) , mMinValue(minValue) , mMaxValue(maxValue) , mColorMap(colorMap) , mIsLevelSet(isLevelSet) , mZeroValue(openvdb::zeroVal<ValueType>()) { init(); } void runParallel() { tbb::parallel_for( tbb::blocked_range<size_t>(0, (mPoints->size() / 3)), *this); } inline void operator()(const tbb::blocked_range<size_t>& range) const { openvdb::Coord ijk; openvdb::Vec3d pos, tmpNormal, normal(0.0, -1.0, 0.0); openvdb::Vec3s color(0.9f, 0.3f, 0.3f); float w = 0.0; size_t e1, e2, e3, voxelNum = 0; for (size_t n = range.begin(); n < range.end(); ++n) { e1 = 3 * n; e2 = e1 + 1; e3 = e2 + 1; pos[0] = (*mPoints)[e1]; pos[1] = (*mPoints)[e2]; pos[2] = (*mPoints)[e3]; pos = mGrid->worldToIndex(pos); ijk[0] = int(pos[0]); ijk[1] = int(pos[1]); ijk[2] = int(pos[2]); const ValueType& value = mAccessor.getValue(ijk); if (value < mZeroValue) { // is negative if (mIsLevelSet) { color = mColorMap[1]; } else { w = (float(value) - mOffset[1]) * mScale[1]; color = openvdb::Vec3s{w * mColorMap[0] + (1.0 - w) * mColorMap[1]}; } } else { if (mIsLevelSet) { color = mColorMap[2]; } else { w = (float(value) - mOffset[0]) * mScale[0]; color = openvdb::Vec3s{w * mColorMap[2] + (1.0 - w) * mColorMap[3]}; } } (*mColors)[e1] = color[0]; (*mColors)[e2] = color[1]; (*mColors)[e3] = color[2]; if (mNormals) { if ((voxelNum % 2) == 0) { tmpNormal = openvdb::math::ISGradient< openvdb::math::CD_2ND>::result(mAccessor, ijk); double length = tmpNormal.length(); if (length > 1.0e-7) { tmpNormal *= 1.0 / length; normal = tmpNormal; } } ++voxelNum; (*mNormals)[e1] = static_cast<GLfloat>(normal[0]); (*mNormals)[e2] = static_cast<GLfloat>(normal[1]); (*mNormals)[e3] = static_cast<GLfloat>(normal[2]); } } } private: void init() { mOffset[0] = float(std::min(mZeroValue, mMinValue)); mScale[0] = 1.f / float(std::abs(std::max(mZeroValue, mMaxValue) - mOffset[0])); mOffset[1] = float(std::min(mZeroValue, mMinValue)); mScale[1] = 1.f / float(std::abs(std::max(mZeroValue, mMaxValue) - mOffset[1])); } std::vector<GLfloat> *mPoints; std::vector<GLfloat> *mColors; std::vector<GLfloat> *mNormals; const GridType *mGrid; openvdb::tree::ValueAccessor<const typename GridType::TreeType> mAccessor; ValueType mMinValue, mMaxValue; openvdb::Vec3s (&mColorMap)[4]; const bool mIsLevelSet; ValueType mZeroValue; float mOffset[2], mScale[2]; }; // PointAttributeGenerator class ActiveVoxelGeo { public: ActiveVoxelGeo(BufferObject& pointBuffer) : mPointBuffer(&pointBuffer) , mColorMinPosValue(0.3f, 0.9f, 0.3f) // green , mColorMaxPosValue(0.9f, 0.3f, 0.3f) // red , mColorMinNegValue(0.9f, 0.9f, 0.3f) // yellow , mColorMaxNegValue(0.3f, 0.3f, 0.9f) // blue { } void setColorMinPosValue(const openvdb::Vec3s& c) { mColorMinPosValue = c; } void setColorMaxPosValue(const openvdb::Vec3s& c) { mColorMaxPosValue = c; } void setColorMinNegValue(const openvdb::Vec3s& c) { mColorMinNegValue = c; } void setColorMaxNegValue(const openvdb::Vec3s& c) { mColorMaxNegValue = c; } template<typename GridType> void operator()(typename GridType::ConstPtr grid) { const size_t maxVoxelPoints = 26000000; openvdb::Vec3s colorMap[4]; colorMap[0] = mColorMinPosValue; colorMap[1] = mColorMaxPosValue; colorMap[2] = mColorMinNegValue; colorMap[3] = mColorMaxNegValue; ////////// using ValueType = typename GridType::ValueType; using TreeType = typename GridType::TreeType; const TreeType& tree = grid->tree(); const bool isLevelSetGrid = grid->getGridClass() == openvdb::GRID_LEVEL_SET; ValueType minValue, maxValue; openvdb::tree::LeafManager<const TreeType> leafs(tree); { util::MinMaxVoxel<const TreeType> minmax(leafs); minmax.runParallel(); minValue = minmax.minVoxel(); maxValue = minmax.maxVoxel(); } size_t voxelsPerLeaf = TreeType::LeafNodeType::NUM_VOXELS; if (tree.activeLeafVoxelCount() > maxVoxelPoints) { voxelsPerLeaf = std::max((maxVoxelPoints / tree.leafCount()), size_t(1)); } std::vector<unsigned> indexMap(leafs.leafCount()); unsigned voxelCount = 0; for (size_t l = 0, L = leafs.leafCount(); l < L; ++l) { indexMap[l] = voxelCount; voxelCount += std::min(static_cast<size_t>(leafs.leaf(l).onVoxelCount()), voxelsPerLeaf); } std::vector<GLfloat> points(voxelCount * 3), colors(voxelCount * 3), normals(voxelCount * 3); std::vector<GLuint> indices(voxelCount); PointGenerator<const TreeType> pointGen( points, indices, leafs, indexMap, grid->transform(), voxelsPerLeaf); pointGen.runParallel(); PointAttributeGenerator<GridType> attributeGen( points, colors, normals, *grid, minValue, maxValue, colorMap, isLevelSetGrid); attributeGen.runParallel(); mPointBuffer->genVertexBuffer(points); mPointBuffer->genColorBuffer(colors); mPointBuffer->genNormalBuffer(normals); mPointBuffer->genIndexBuffer(indices, GL_POINTS); } private: BufferObject *mPointBuffer; openvdb::Vec3s mColorMinPosValue, mColorMaxPosValue, mColorMinNegValue, mColorMaxNegValue; }; // ActiveVoxelGeo //////////////////////////////////////// /// Helper class used internally by processTypedGrid() template<typename GridType, typename OpType, bool IsConst/*=false*/> struct GridProcessor { static inline void call(OpType& op, openvdb::GridBase::Ptr grid) { op.template operator()<GridType>(openvdb::gridPtrCast<GridType>(grid)); } }; /// Helper class used internally by processTypedGrid() template<typename GridType, typename OpType> struct GridProcessor<GridType, OpType, /*IsConst=*/true> { static inline void call(OpType& op, openvdb::GridBase::ConstPtr grid) { op.template operator()<GridType>(openvdb::gridConstPtrCast<GridType>(grid)); } }; /// Helper function used internally by processTypedGrid() template<typename GridType, typename OpType, typename GridPtrType> inline void doProcessTypedGrid(GridPtrType grid, OpType& op) { GridProcessor<GridType, OpType, std::is_const<typename GridPtrType::element_type>::value>::call(op, grid); } //////////////////////////////////////// /// @brief Utility function that, given a generic grid pointer, /// calls a functor on the fully-resolved grid /// /// Usage: /// @code /// struct PruneOp { /// template<typename GridT> /// void operator()(typename GridT::Ptr grid) const { grid->tree()->prune(); } /// }; /// /// processTypedGrid(myGridPtr, PruneOp()); /// @endcode /// /// @return @c false if the grid type is unknown or unhandled. template<typename GridPtrType, typename OpType> bool processTypedGrid(GridPtrType grid, OpType& op) { using namespace openvdb; if (grid->template isType<BoolGrid>()) doProcessTypedGrid<BoolGrid>(grid, op); else if (grid->template isType<FloatGrid>()) doProcessTypedGrid<FloatGrid>(grid, op); else if (grid->template isType<DoubleGrid>()) doProcessTypedGrid<DoubleGrid>(grid, op); else if (grid->template isType<Int32Grid>()) doProcessTypedGrid<Int32Grid>(grid, op); else if (grid->template isType<Int64Grid>()) doProcessTypedGrid<Int64Grid>(grid, op); else if (grid->template isType<Vec3IGrid>()) doProcessTypedGrid<Vec3IGrid>(grid, op); else if (grid->template isType<Vec3SGrid>()) doProcessTypedGrid<Vec3SGrid>(grid, op); else if (grid->template isType<Vec3DGrid>()) doProcessTypedGrid<Vec3DGrid>(grid, op); else return false; return true; } /// @brief Utility function that, given a generic grid pointer, calls /// a functor on the fully-resolved grid, provided that the grid's /// voxel values are scalars /// /// Usage: /// @code /// struct PruneOp { /// template<typename GridT> /// void operator()(typename GridT::Ptr grid) const { grid->tree()->prune(); } /// }; /// /// processTypedScalarGrid(myGridPtr, PruneOp()); /// @endcode /// /// @return @c false if the grid type is unknown or non-scalar. template<typename GridPtrType, typename OpType> bool processTypedScalarGrid(GridPtrType grid, OpType& op) { using namespace openvdb; if (grid->template isType<FloatGrid>()) doProcessTypedGrid<FloatGrid>(grid, op); else if (grid->template isType<DoubleGrid>()) doProcessTypedGrid<DoubleGrid>(grid, op); else if (grid->template isType<Int32Grid>()) doProcessTypedGrid<Int32Grid>(grid, op); else if (grid->template isType<Int64Grid>()) doProcessTypedGrid<Int64Grid>(grid, op); else return false; return true; } /// @brief Utility function that, given a generic grid pointer, calls /// a functor on the fully-resolved grid, provided that the grid's /// voxel values are vectors template<typename GridPtrType, typename OpType> bool processTypedVectorGrid(GridPtrType grid, OpType& op) { using namespace openvdb; if (grid->template isType<Vec3IGrid>()) doProcessTypedGrid<Vec3IGrid>(grid, op); else if (grid->template isType<Vec3SGrid>()) doProcessTypedGrid<Vec3SGrid>(grid, op); else if (grid->template isType<Vec3DGrid>()) doProcessTypedGrid<Vec3DGrid>(grid, op); else return false; return true; } } // namespace util //////////////////////////////////////// #endif // OPENVDB_MAYA_UTIL_HAS_BEEN_INCLUDED
31,310
C
28.848427
101
0.600862
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBWriteNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <openvdb/io/Stream.h> #include <openvdb/math/Math.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnPluginData.h> #include <maya/MFnStringData.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnUnitAttribute.h> #include <maya/MFnEnumAttribute.h> #include <sstream> // std::stringstream namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBWriteNode : public MPxNode { OpenVDBWriteNode() {} virtual ~OpenVDBWriteNode() {} virtual MStatus compute(const MPlug& plug, MDataBlock& data); static void* creator(); static MStatus initialize(); static MTypeId id; static MObject aVdbFilePath; static MObject aFrameNumbering; static MObject aInputTime; static MObject aVdbInput; static MObject aVdbOutput; static MObject aNodeInfo; }; MTypeId OpenVDBWriteNode::id(0x00108A52); MObject OpenVDBWriteNode::aVdbFilePath; MObject OpenVDBWriteNode::aFrameNumbering; MObject OpenVDBWriteNode::aInputTime; MObject OpenVDBWriteNode::aVdbInput; MObject OpenVDBWriteNode::aVdbOutput; MObject OpenVDBWriteNode::aNodeInfo; namespace { mvdb::NodeRegistry registerNode("OpenVDBWrite", OpenVDBWriteNode::id, OpenVDBWriteNode::creator, OpenVDBWriteNode::initialize); } // unnamed namespace //////////////////////////////////////// void* OpenVDBWriteNode::creator() { return new OpenVDBWriteNode(); } MStatus OpenVDBWriteNode::initialize() { MStatus stat; MFnTypedAttribute tAttr; MFnEnumAttribute eAttr; MFnUnitAttribute unitAttr; MFnStringData fnStringData; MObject defaultStringData = fnStringData.create("volume.vdb"); MObject emptyStr = fnStringData.create(""); // Setup the input attributes aVdbFilePath = tAttr.create("VdbFilePath", "file", MFnData::kString, defaultStringData, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aVdbFilePath); if (stat != MS::kSuccess) return stat; aFrameNumbering = eAttr.create("FrameNumbering", "numbering", 0, &stat); if (stat != MS::kSuccess) return stat; eAttr.addField("Frame.SubTick", 0); eAttr.addField("Fractional frame values", 1); eAttr.addField("Global ticks", 2); eAttr.setConnectable(false); stat = addAttribute(aFrameNumbering); if (stat != MS::kSuccess) return stat; aInputTime = unitAttr.create("inputTime", "int", MTime(0.0, MTime::kFilm)); unitAttr.setKeyable(true); unitAttr.setReadable(true); unitAttr.setWritable(true); unitAttr.setStorable(true); stat = addAttribute(aInputTime); if (stat != MS::kSuccess) return stat; aVdbInput = tAttr.create("VdbInput", "vdbinput", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(true); stat = addAttribute(aVdbInput); if (stat != MS::kSuccess) return stat; // Setup the output attributes aVdbOutput = tAttr.create("VdbOutput", "vdboutput", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setWritable(false); tAttr.setStorable(false); stat = addAttribute(aVdbOutput); if (stat != MS::kSuccess) return stat; aNodeInfo = tAttr.create("NodeInfo", "info", MFnData::kString, emptyStr, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); stat = addAttribute(aNodeInfo); if (stat != MS::kSuccess) return stat; // Set the attribute dependencies stat = attributeAffects(aVdbFilePath, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFrameNumbering, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aInputTime, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbFilePath, aNodeInfo); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFrameNumbering, aNodeInfo); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aInputTime, aNodeInfo); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aNodeInfo); if (stat != MS::kSuccess) return stat; return MS::kSuccess; } //////////////////////////////////////// MStatus OpenVDBWriteNode::compute(const MPlug& plug, MDataBlock& data) { if (plug == aVdbOutput || plug == aNodeInfo) { MStatus status; const int numberingScheme = data.inputValue(aFrameNumbering , &status).asInt(); MDataHandle filePathHandle = data.inputValue(aVdbFilePath, &status); if (status != MS::kSuccess) return status; std::string filename = filePathHandle.asString().asChar(); if (filename.empty()) { return MS::kUnknownParameter; } MTime time = data.inputValue(aInputTime).asTime(); mvdb::insertFrameNumber(filename, time, numberingScheme); std::stringstream infoStr; infoStr << "File: " << filename << "\n"; MDataHandle inputVdbHandle = data.inputValue(aVdbInput, &status); if (status != MS::kSuccess) return status; MFnPluginData fnData(inputVdbHandle.data()); MPxData * pxData = fnData.data(); if (pxData) { OpenVDBData* vdb = dynamic_cast<OpenVDBData*>(pxData); if (vdb) { // Add file-level metadata. openvdb::MetaMap outMeta; outMeta.insertMeta("creator", openvdb::StringMetadata("Maya/OpenVDB_Write_Node")); const MTime dummy(1.0, MTime::kSeconds); const double fps = dummy.as(MTime::uiUnit()); const double tpf = 6000.0 / fps; const double frame = time.as(MTime::uiUnit()); outMeta.insertMeta("frame", openvdb::DoubleMetadata(frame)); outMeta.insertMeta("tick", openvdb::Int32Metadata(int(openvdb::math::Round(frame * tpf)))); outMeta.insertMeta("frames_per_second", openvdb::Int32Metadata(int(fps))); outMeta.insertMeta("ticks_per_frame", openvdb::Int32Metadata(int(tpf))); outMeta.insertMeta("ticks_per_second", openvdb::Int32Metadata(6000)); // Create a VDB file object. openvdb::io::File file(filename); vdb->write(file, outMeta); //file.write(vdb->grids(), outMeta); file.close(); // Output MFnPluginData outputDataCreators; outputDataCreators.create(OpenVDBData::id, &status); if (status != MS::kSuccess) return status; OpenVDBData* outputVdb = static_cast<OpenVDBData*>(outputDataCreators.data(&status)); if (status != MS::kSuccess) return status; outputVdb = vdb; MDataHandle outHandle = data.outputValue(aVdbOutput); outHandle.set(outputVdb); infoStr << "Frame: " << frame << "\n"; mvdb::printGridInfo(infoStr, *vdb); } mvdb::updateNodeInfo(infoStr, data, aNodeInfo); return data.setClean(plug); } } return MS::kUnknownParameter; }
7,602
C++
29.290837
107
0.640095
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBVisualizeNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file OpenVDBVisualizeNode.cc /// /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <openvdb/io/Stream.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnStringData.h> #include <maya/MFnPluginData.h> #include <maya/MFnNumericAttribute.h> #include <maya/MPxLocatorNode.h> #include <maya/MString.h> #include <maya/MPlug.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MColor.h> #include <maya/M3dView.h> namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBVisualizeNode : public MPxLocatorNode { OpenVDBVisualizeNode(); virtual ~OpenVDBVisualizeNode(); virtual MStatus compute(const MPlug& plug, MDataBlock& data); virtual void draw(M3dView & view, const MDagPath & path, M3dView::DisplayStyle style, M3dView::DisplayStatus status); virtual bool isBounded() const; virtual MBoundingBox boundingBox() const; static void * creator(); static MStatus initialize(); static MObject aVdbInput; static MObject aVdbAllGridNames; static MObject aVdbSelectedGridNames; static MObject aVisualizeBBox; static MObject aVisualizeInternalNodes; static MObject aVisualizeLeafNodes; static MObject aVisualizeActiveTiles; static MObject aVisualizeActiveVoxels; static MObject aVisualizeSurface; static MObject aIsovalue; static MObject aCachedBBox; static MObject aCachedInternalNodes; static MObject aCachedLeafNodes; static MObject aCachedActiveTiles; static MObject aCachedActiveVoxels; static MObject aCachedSurface; static MTypeId id; private: std::vector<mvdb::BufferObject> mBBoxBuffers; std::vector<mvdb::BufferObject> mNodeBuffers; std::vector<mvdb::BufferObject> mLeafBuffers; std::vector<mvdb::BufferObject> mTileBuffers; std::vector<mvdb::BufferObject> mSurfaceBuffers; std::vector<mvdb::BufferObject> mPointBuffers; mvdb::ShaderProgram mSurfaceShader, mPointShader; MBoundingBox mBBox; }; //////////////////////////////////////// MObject OpenVDBVisualizeNode::aVdbInput; MObject OpenVDBVisualizeNode::aVdbAllGridNames; MObject OpenVDBVisualizeNode::aVdbSelectedGridNames; MObject OpenVDBVisualizeNode::aVisualizeBBox; MObject OpenVDBVisualizeNode::aVisualizeInternalNodes; MObject OpenVDBVisualizeNode::aVisualizeLeafNodes; MObject OpenVDBVisualizeNode::aVisualizeActiveTiles; MObject OpenVDBVisualizeNode::aVisualizeActiveVoxels; MObject OpenVDBVisualizeNode::aVisualizeSurface; MObject OpenVDBVisualizeNode::aIsovalue; MObject OpenVDBVisualizeNode::aCachedBBox; MObject OpenVDBVisualizeNode::aCachedInternalNodes; MObject OpenVDBVisualizeNode::aCachedLeafNodes; MObject OpenVDBVisualizeNode::aCachedActiveTiles; MObject OpenVDBVisualizeNode::aCachedActiveVoxels; MObject OpenVDBVisualizeNode::aCachedSurface; MTypeId OpenVDBVisualizeNode::id(0x00108A53); namespace { mvdb::NodeRegistry registerNode("OpenVDBVisualize", OpenVDBVisualizeNode::id, OpenVDBVisualizeNode::creator, OpenVDBVisualizeNode::initialize, MPxNode::kLocatorNode); } //////////////////////////////////////// OpenVDBVisualizeNode::OpenVDBVisualizeNode() { mSurfaceShader.setVertShader( "#version 120\n" "varying vec3 normal;\n" "void main() {\n" "normal = normalize(gl_NormalMatrix * gl_Normal);\n" "gl_Position = ftransform();\n" "gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;\n" "}\n"); mSurfaceShader.setFragShader( "#version 120\n" "varying vec3 normal;\n" "const vec4 skyColor = vec4(0.9, 0.9, 1.0, 1.0);\n" "const vec4 groundColor = vec4(0.3, 0.3, 0.2, 1.0);\n" "void main() {\n" "vec3 normalized_normal = normalize(normal);\n" "float w = 0.5 * (1.0 + dot(normalized_normal, vec3(0.0, 1.0, 0.0)));\n" "vec4 diffuseColor = w * skyColor + (1.0 - w) * groundColor;\n" "gl_FragColor = diffuseColor;\n" "}\n"); mSurfaceShader.build(); mPointShader.setVertShader( "#version 120\n" "varying vec3 normal;\n" "void main() {\n" "gl_FrontColor = gl_Color;\n" "normal = normalize(gl_NormalMatrix * gl_Normal);\n" "gl_Position = ftransform();\n" "gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;\n" "}\n"); mPointShader.setFragShader( "#version 120\n" "varying vec3 normal;\n" "void main() {\n" "vec3 normalized_normal = normalize(normal);\n" "float w = 0.5 * (1.0 + dot(normalized_normal, vec3(0.0, 1.0, 0.0)));\n" "vec4 diffuseColor = w * gl_Color + (1.0 - w) * (gl_Color * 0.3);\n" "gl_FragColor = diffuseColor;\n" "}\n"); mPointShader.build(); } OpenVDBVisualizeNode::~OpenVDBVisualizeNode() { } void* OpenVDBVisualizeNode::creator() { return new OpenVDBVisualizeNode(); } MStatus OpenVDBVisualizeNode::initialize() { MStatus stat; MFnNumericAttribute nAttr; MFnTypedAttribute tAttr; // Setup input / output attributes aVdbInput = tAttr.create("VDBInput", "input", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setReadable(false); stat = addAttribute(aVdbInput); if (stat != MS::kSuccess) return stat; // Setup UI attributes aVisualizeBBox = nAttr.create("ActiveValueBoundingBox", "bbox", MFnNumericData::kBoolean); nAttr.setDefault(true); nAttr.setConnectable(false); stat = addAttribute(aVisualizeBBox); if (stat != MS::kSuccess) return stat; aVisualizeInternalNodes = nAttr.create("InternalNodes", "inodes", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aVisualizeInternalNodes); if (stat != MS::kSuccess) return stat; aVisualizeLeafNodes = nAttr.create("LeafNodes", "lnodes", MFnNumericData::kBoolean); nAttr.setDefault(true); nAttr.setConnectable(false); stat = addAttribute(aVisualizeLeafNodes); if (stat != MS::kSuccess) return stat; aVisualizeActiveTiles = nAttr.create("ActiveTiles", "tiles", MFnNumericData::kBoolean); nAttr.setDefault(true); nAttr.setConnectable(false); stat = addAttribute(aVisualizeActiveTiles); if (stat != MS::kSuccess) return stat; aVisualizeActiveVoxels = nAttr.create("ActiveVoxels", "voxels", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aVisualizeActiveVoxels); if (stat != MS::kSuccess) return stat; aVisualizeSurface = nAttr.create("Surface", "surface", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aVisualizeSurface); if (stat != MS::kSuccess) return stat; aIsovalue = nAttr.create("Isovalue", "iso", MFnNumericData::kFloat); nAttr.setDefault(0.0); nAttr.setSoftMin(-1.0); nAttr.setSoftMax( 1.0); nAttr.setConnectable(false); stat = addAttribute(aIsovalue); if (stat != MS::kSuccess) return stat; // Setup internal attributes aCachedBBox = nAttr.create("cachedbbox", "cbb", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setWritable(false); nAttr.setReadable(false); nAttr.setHidden(true); stat = addAttribute(aCachedBBox); if (stat != MS::kSuccess) return stat; aCachedInternalNodes = nAttr.create("cachedinternalnodes", "cin", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setWritable(false); nAttr.setReadable(false); nAttr.setHidden(true); stat = addAttribute(aCachedInternalNodes); if (stat != MS::kSuccess) return stat; aCachedLeafNodes = nAttr.create("cachedleafnodes", "cln", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setWritable(false); nAttr.setReadable(false); nAttr.setHidden(true); stat = addAttribute(aCachedLeafNodes); if (stat != MS::kSuccess) return stat; aCachedActiveTiles = nAttr.create("cachedactivetiles", "cat", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setWritable(false); nAttr.setReadable(false); nAttr.setHidden(true); stat = addAttribute(aCachedActiveTiles); if (stat != MS::kSuccess) return stat; aCachedActiveVoxels = nAttr.create("cachedactivevoxels", "cav", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setWritable(false); nAttr.setReadable(false); nAttr.setHidden(true); stat = addAttribute(aCachedActiveVoxels); if (stat != MS::kSuccess) return stat; aCachedSurface = nAttr.create("cachedsurface", "cs", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setWritable(false); nAttr.setReadable(false); nAttr.setHidden(true); stat = addAttribute(aCachedSurface); if (stat != MS::kSuccess) return stat; MFnStringData fnStringData; MObject defaultStringData = fnStringData.create(""); aVdbAllGridNames = tAttr.create("VdbAllGridNames", "allgrids", MFnData::kString, defaultStringData, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); tAttr.setReadable(false); tAttr.setHidden(true); stat = addAttribute(aVdbAllGridNames); if (stat != MS::kSuccess) return stat; aVdbSelectedGridNames = tAttr.create("VdbSelectedGridNames", "selectedgrids", MFnData::kString, defaultStringData, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); tAttr.setReadable(false); tAttr.setHidden(true); stat = addAttribute(aVdbSelectedGridNames); if (stat != MS::kSuccess) return stat; // Setup dependencies stat = attributeAffects(aVdbInput, aVdbAllGridNames); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aCachedBBox); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aCachedInternalNodes); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aCachedLeafNodes); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aCachedActiveTiles); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aCachedActiveVoxels); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInput, aCachedSurface); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aCachedBBox); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aCachedInternalNodes); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aCachedLeafNodes); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aCachedActiveTiles); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aCachedActiveVoxels); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aCachedSurface); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aIsovalue, aCachedSurface); if (stat != MS::kSuccess) return stat; return MS::kSuccess; } //////////////////////////////////////// MStatus OpenVDBVisualizeNode::compute(const MPlug& plug, MDataBlock& data) { MStatus status; const OpenVDBData* inputVdb = mvdb::getInputVDB(aVdbInput, data); if (!inputVdb) return MS::kFailure; if (plug == aVdbAllGridNames) { MString names = mvdb::getGridNames(*inputVdb).c_str(); MDataHandle outHandle = data.outputValue(aVdbAllGridNames); outHandle.set(names); return data.setClean(plug); } // Get selected grids MDataHandle selectionHandle = data.inputValue(aVdbSelectedGridNames, &status); if (status != MS::kSuccess) return status; std::string names = selectionHandle.asString().asChar(); std::vector<openvdb::GridBase::ConstPtr> grids; mvdb::getGrids(grids, *inputVdb, names); if (grids.empty()) { mBBoxBuffers.clear(); mNodeBuffers.clear(); mLeafBuffers.clear(); mTileBuffers.clear(); mSurfaceBuffers.clear(); mPointBuffers.clear(); return MS::kUnknownParameter; } if (plug == aCachedInternalNodes) { mNodeBuffers.clear(); mNodeBuffers.resize(grids.size()); for (size_t n = 0, N = grids.size(); n < N; ++n) { mvdb::InternalNodesGeo drawNodes(mNodeBuffers[n]); mvdb::processTypedGrid(grids[n], drawNodes); } MDataHandle outHandle = data.outputValue(aCachedInternalNodes); outHandle.set(true); } else if (plug == aCachedLeafNodes) { mLeafBuffers.clear(); mLeafBuffers.resize(grids.size()); for (size_t n = 0, N = grids.size(); n < N; ++n) { mvdb::LeafNodesGeo drawLeafs(mLeafBuffers[n]); mvdb::processTypedGrid(grids[n], drawLeafs); } MDataHandle outHandle = data.outputValue(aCachedLeafNodes); outHandle.set(true); } else if (plug == aCachedBBox) { MPoint pMin, pMax; mBBoxBuffers.clear(); mBBoxBuffers.resize(grids.size()); for (size_t n = 0, N = grids.size(); n < N; ++n) { mvdb::BoundingBoxGeo drawBBox(mBBoxBuffers[n]); drawBBox(grids[n]); for (int i = 0; i < 3; ++i) { pMin[i] = drawBBox.min()[i]; pMax[i] = drawBBox.max()[i]; } } mBBox = MBoundingBox(pMin, pMax); MDataHandle outHandle = data.outputValue(aCachedBBox); outHandle.set(true); } else if (plug == aCachedActiveTiles) { mTileBuffers.clear(); mTileBuffers.resize(grids.size()); for (size_t n = 0, N = grids.size(); n < N; ++n) { mvdb::ActiveTileGeo drawTiles(mTileBuffers[n]); mvdb::processTypedGrid(grids[n], drawTiles); } MDataHandle outHandle = data.outputValue(aCachedActiveTiles); outHandle.set(true); } else if(plug == aCachedActiveVoxels) { mPointBuffers.clear(); mPointBuffers.resize(grids.size()); for (size_t n = 0, N = grids.size(); n < N; ++n) { mvdb::ActiveVoxelGeo drawVoxels(mPointBuffers[n]); mvdb::processTypedScalarGrid(grids[n], drawVoxels); } MDataHandle outHandle = data.outputValue(aCachedActiveVoxels); outHandle.set(true); } else if (plug == aCachedSurface) { float iso = data.inputValue(aIsovalue, &status).asFloat(); if (status != MS::kSuccess) return status; mSurfaceBuffers.clear(); mSurfaceBuffers.resize(grids.size()); for (size_t n = 0, N = grids.size(); n < N; ++n) { mvdb::SurfaceGeo drawSurface(mSurfaceBuffers[n], iso); mvdb::processTypedScalarGrid(grids[n], drawSurface); } MDataHandle outHandle = data.outputValue(aCachedSurface); outHandle.set(true); } else { return MS::kUnknownParameter; } return data.setClean(plug); } void OpenVDBVisualizeNode::draw(M3dView & view, const MDagPath& /*path*/, M3dView::DisplayStyle /*style*/, M3dView::DisplayStatus status) { MObject thisNode = thisMObject(); const bool isSelected = (status == M3dView::kActive) || (status == M3dView::kLead); const bool internalNodes = MPlug(thisNode, aVisualizeInternalNodes).asBool(); const bool leafNodes = MPlug(thisNode, aVisualizeLeafNodes).asBool(); const bool bbox = MPlug(thisNode, aVisualizeBBox).asBool(); const bool tiles = MPlug(thisNode, aVisualizeActiveTiles).asBool(); const bool voxels = MPlug(thisNode, aVisualizeActiveVoxels).asBool(); const bool surface = MPlug(thisNode, aVisualizeSurface).asBool(); view.beginGL(); if (surface && MPlug(thisNode, aCachedSurface).asBool()) { if (!view.selectMode()) mSurfaceShader.startShading(); for (size_t n = 0, N = mSurfaceBuffers.size(); n < N; ++n) { mSurfaceBuffers[n].render(); } mSurfaceShader.stopShading(); } if (tiles && MPlug(thisNode, aCachedActiveTiles).asBool()) { for (size_t n = 0, N = mTileBuffers.size(); n < N; ++n) { mTileBuffers[n].render(); } } if (leafNodes && MPlug(thisNode, aCachedLeafNodes).asBool()) { for (size_t n = 0, N = mLeafBuffers.size(); n < N; ++n) { mLeafBuffers[n].render(); } } if (voxels && MPlug(thisNode, aCachedActiveVoxels).asBool()) { if (!view.selectMode()) mPointShader.startShading(); for (size_t n = 0, N = mPointBuffers.size(); n < N; ++n) { mPointBuffers[n].render(); } mPointShader.stopShading(); } if (!view.selectMode()) { if (internalNodes && MPlug(thisNode, aCachedInternalNodes).asBool()) { for (size_t n = 0, N = mNodeBuffers.size(); n < N; ++n) { mNodeBuffers[n].render(); } } if ((isSelected || bbox) && MPlug(thisNode, aCachedBBox).asBool()) { if (isSelected) glColor3f(0.9f, 0.9f, 0.3f); else glColor3f(0.045f, 0.045f, 0.045f); for (size_t n = 0, N = mBBoxBuffers.size(); n < N; ++n) { mBBoxBuffers[n].render(); } } } view.endGL(); } bool OpenVDBVisualizeNode::isBounded() const { return true; } MBoundingBox OpenVDBVisualizeNode::boundingBox() const { bool cachedBBox = false; MObject thisNode = thisMObject(); MPlug(thisNode, aCachedBBox).getValue(cachedBBox); if (cachedBBox) return mBBox; return MBoundingBox(MPoint(-1.0, -1.0, -1.0), MPoint(1.0, 1.0, 1.0)); }
18,126
C++
29.828231
111
0.653261
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBData.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file OpenVDBData.h /// @author FX R&D OpenVDB team #ifndef OPENVDB_MAYA_DATA_HAS_BEEN_INCLUDED #define OPENVDB_MAYA_DATA_HAS_BEEN_INCLUDED #include <openvdb/Platform.h> #include <openvdb/openvdb.h> #include <maya/MPxData.h> #include <maya/MTypeId.h> #include <maya/MString.h> #include <maya/MObjectArray.h> #include <iosfwd> //////////////////////////////////////// class OpenVDBData : public MPxData { public: OpenVDBData(); virtual ~OpenVDBData(); size_t numberOfGrids() const; /// @brief return a constant reference to the specified grid. const openvdb::GridBase& grid(size_t index) const; /// @brief return a constant pointer to the specified grid. openvdb::GridBase::ConstPtr gridPtr(size_t index) const; /// @brief clears this container and duplicates the @c rhs grid container. void duplicate(const OpenVDBData& rhs); /// @brief Append the given grid to this container. void insert(const openvdb::GridBase::ConstPtr&); /// @brief Append a shallow copy of the given grid to this container. void insert(const openvdb::GridBase&); /// @brief Append shallow copies of the given grids to this container. void insert(const openvdb::GridPtrVec&); /// @brief Append shallow copies of the given grids to this container. void insert(const openvdb::GridCPtrVec&); void write(const openvdb::io::File& file, const openvdb::MetaMap& = openvdb::MetaMap()) const; /// @{ // required maya interface methods static void* creator(); virtual MStatus readASCII(const MArgList&, unsigned&); virtual MStatus writeASCII(ostream&); virtual MStatus readBinary(istream&, unsigned length); virtual MStatus writeBinary(ostream&); virtual void copy(const MPxData&); MTypeId typeId() const; MString name() const; static const MString typeName; static const MTypeId id; /// @} private: openvdb::GridCPtrVec mGrids; }; //////////////////////////////////////// #endif // OPENVDB_MAYA_DATA_HAS_BEEN_INCLUDED
2,136
C
24.746988
78
0.672285
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBTransformNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file OpenVDBTransformNode.cc /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnStringData.h> #include <maya/MFnPluginData.h> #include <maya/MGlobal.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFloatVector.h> #include <boost/math/constants/constants.hpp> // boost::math::constants::pi namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBTransformNode : public MPxNode { OpenVDBTransformNode() {} virtual ~OpenVDBTransformNode() {} virtual MStatus compute(const MPlug& plug, MDataBlock& data); static void* creator(); static MStatus initialize(); static MTypeId id; static MObject aVdbInput; static MObject aVdbOutput; static MObject aVdbSelectedGridNames; static MObject aTranslate; static MObject aRotate; static MObject aScale; static MObject aPivot; static MObject aUniformScale; static MObject aInvert; }; MTypeId OpenVDBTransformNode::id(0x00108A57); MObject OpenVDBTransformNode::aVdbOutput; MObject OpenVDBTransformNode::aVdbInput; MObject OpenVDBTransformNode::aVdbSelectedGridNames; MObject OpenVDBTransformNode::aTranslate; MObject OpenVDBTransformNode::aRotate; MObject OpenVDBTransformNode::aScale; MObject OpenVDBTransformNode::aPivot; MObject OpenVDBTransformNode::aUniformScale; MObject OpenVDBTransformNode::aInvert; namespace { mvdb::NodeRegistry registerNode("OpenVDBTransform", OpenVDBTransformNode::id, OpenVDBTransformNode::creator, OpenVDBTransformNode::initialize); } //////////////////////////////////////// void* OpenVDBTransformNode::creator() { return new OpenVDBTransformNode(); } MStatus OpenVDBTransformNode::initialize() { MStatus stat; // attributes MFnTypedAttribute tAttr; MFnStringData strData; aVdbSelectedGridNames = tAttr.create("SelectedGridNames", "grids", MFnData::kString, strData.create("*"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aVdbSelectedGridNames); if (stat != MS::kSuccess) return stat; MFnNumericAttribute nAttr; aTranslate = nAttr.createPoint("Translate", "t", &stat); if (stat != MS::kSuccess) return stat; nAttr.setDefault(0.0, 0.0, 0.0); stat = addAttribute(aTranslate); if (stat != MS::kSuccess) return stat; aRotate = nAttr.createPoint("Rotate", "r", &stat); if (stat != MS::kSuccess) return stat; nAttr.setDefault(0.0, 0.0, 0.0); stat = addAttribute(aRotate); if (stat != MS::kSuccess) return stat; aScale = nAttr.createPoint("Scale", "s", &stat); if (stat != MS::kSuccess) return stat; nAttr.setDefault(1.0, 1.0, 1.0); stat = addAttribute(aScale); if (stat != MS::kSuccess) return stat; aPivot = nAttr.createPoint("Pivot", "p", &stat); if (stat != MS::kSuccess) return stat; nAttr.setDefault(0.0, 0.0, 0.0); stat = addAttribute(aPivot); if (stat != MS::kSuccess) return stat; aUniformScale = nAttr.create("UniformScale", "us", MFnNumericData::kFloat); nAttr.setDefault(1.0); nAttr.setMin(1e-7); nAttr.setSoftMax(10.0); stat = addAttribute(aUniformScale); if (stat != MS::kSuccess) return stat; aInvert = nAttr.create("invert", "InvertTransformation", MFnNumericData::kBoolean); nAttr.setDefault(false); stat = addAttribute(aInvert); if (stat != MS::kSuccess) return stat; // input / output aVdbInput = tAttr.create("VdbInput", "vdbinput", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(true); stat = addAttribute(aVdbInput); if (stat != MS::kSuccess) return stat; aVdbOutput = tAttr.create("VdbOutput", "vdboutput", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setWritable(false); tAttr.setStorable(false); stat = addAttribute(aVdbOutput); if (stat != MS::kSuccess) return stat; // attribute dependencies stat = attributeAffects(aVdbInput, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aTranslate, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aRotate, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aScale, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aPivot, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aUniformScale, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aInvert, aVdbOutput); if (stat != MS::kSuccess) return stat; return MS::kSuccess; } //////////////////////////////////////// MStatus OpenVDBTransformNode::compute(const MPlug& plug, MDataBlock& data) { if (plug == aVdbOutput) { const OpenVDBData* inputVdb = mvdb::getInputVDB(aVdbInput, data); MStatus status; MFnPluginData pluginData; pluginData.create(OpenVDBData::id, &status); if (status != MS::kSuccess) { MGlobal::displayError("Failed to create a new OpenVDBData object."); return MS::kFailure; } OpenVDBData* outputVdb = static_cast<OpenVDBData*>(pluginData.data(&status)); if (inputVdb && outputVdb) { const MFloatVector t = data.inputValue(aTranslate, &status).asFloatVector(); const MFloatVector r = data.inputValue(aRotate, &status).asFloatVector(); const MFloatVector p = data.inputValue(aPivot, &status).asFloatVector(); const MFloatVector s = data.inputValue(aScale, &status).asFloatVector() * data.inputValue(aUniformScale, &status).asFloat(); // Construct new transform openvdb::Mat4R mat(openvdb::Mat4R::identity()); mat.preTranslate(openvdb::Vec3R(p[0], p[1], p[2])); const double deg2rad = boost::math::constants::pi<double>() / 180.0; mat.preRotate(openvdb::math::X_AXIS, deg2rad*r[0]); mat.preRotate(openvdb::math::Y_AXIS, deg2rad*r[1]); mat.preRotate(openvdb::math::Z_AXIS, deg2rad*r[2]); mat.preScale(openvdb::Vec3R(s[0], s[1], s[2])); mat.preTranslate(openvdb::Vec3R(-p[0], -p[1], -p[2])); mat.preTranslate(openvdb::Vec3R(t[0], t[1], t[2])); typedef openvdb::math::AffineMap AffineMap; typedef openvdb::math::Transform Transform; if (data.inputValue(aInvert, &status).asBool()) { mat = mat.inverse(); } AffineMap map(mat); const std::string selectionStr = data.inputValue(aVdbSelectedGridNames, &status).asString().asChar(); mvdb::GridCPtrVec grids; if (!mvdb::getSelectedGrids(grids, selectionStr, *inputVdb, *outputVdb)) { MGlobal::displayWarning("No grids are selected."); } for (mvdb::GridCPtrVecIter it = grids.begin(); it != grids.end(); ++it) { openvdb::GridBase::ConstPtr grid = (*it)->copyGrid(); // shallow copy, shares tree // Merge the transform's current affine representation with the new affine map. AffineMap::Ptr compound( new AffineMap(*grid->transform().baseMap()->getAffineMap(), map)); // Simplify the affine map and replace the transform. openvdb::ConstPtrCast<openvdb::GridBase>(grid)->setTransform( Transform::Ptr(new Transform(openvdb::math::simplify(compound)))); outputVdb->insert(grid); } MDataHandle output = data.outputValue(aVdbOutput); output.set(outputVdb); return data.setClean(plug); } } return MS::kUnknownParameter; }
8,204
C++
29.501859
117
0.643954
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBData.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file OpenVDBData.cc /// @author FX R&D OpenVDB team #include "OpenVDBData.h" #include <openvdb/io/Stream.h> #include <maya/MGlobal.h> #include <maya/MIOStream.h> #include <maya/MPoint.h> #include <maya/MArgList.h> #include <limits> #include <iostream> //////////////////////////////////////// const MTypeId OpenVDBData::id(0x00108A50); const MString OpenVDBData::typeName("OpenVDBData"); //////////////////////////////////////// void* OpenVDBData::creator() { return new OpenVDBData(); } OpenVDBData::OpenVDBData(): MPxData() { } OpenVDBData::~OpenVDBData() { } void OpenVDBData::copy(const MPxData& other) { if (other.typeId() == OpenVDBData::id) { const OpenVDBData& rhs = static_cast<const OpenVDBData&>(other); if (&mGrids != &rhs.mGrids) { // shallow-copy the grids from the rhs container. mGrids.clear(); insert(rhs.mGrids); } } } MTypeId OpenVDBData::typeId() const { return OpenVDBData::id; } MString OpenVDBData::name() const { return OpenVDBData::typeName; } MStatus OpenVDBData::readASCII(const MArgList&, unsigned&) { return MS::kFailure; } MStatus OpenVDBData::writeASCII(ostream&) { return MS::kFailure; } MStatus OpenVDBData::readBinary(istream& in, unsigned) { auto grids = openvdb::io::Stream(in).getGrids(); mGrids.clear(); insert(*grids); return in.fail() ? MS::kFailure : MS::kSuccess; } MStatus OpenVDBData::writeBinary(ostream& out) { openvdb::io::Stream(out).write(mGrids); return out.fail() ? MS::kFailure : MS::kSuccess; } //////////////////////////////////////// size_t OpenVDBData::numberOfGrids() const { return mGrids.size(); } const openvdb::GridBase& OpenVDBData::grid(size_t index) const { return *(mGrids[index]); } openvdb::GridBase::ConstPtr OpenVDBData::gridPtr(size_t index) const { return mGrids[index]; } void OpenVDBData::duplicate(const OpenVDBData& rhs) { mGrids.clear(); for (const auto& gridPtr: rhs.mGrids) { mGrids.push_back(gridPtr->copyGrid()); } } void OpenVDBData::insert(const openvdb::GridBase::ConstPtr& grid) { mGrids.push_back(grid); } void OpenVDBData::insert(const openvdb::GridBase& grid) { mGrids.push_back(grid.copyGrid()); } void OpenVDBData::insert(const openvdb::GridPtrVec& rhs) { mGrids.reserve(mGrids.size() + rhs.size()); for (const auto& gridPtr: rhs) { mGrids.push_back(gridPtr->copyGrid()); } } void OpenVDBData::insert(const openvdb::GridCPtrVec& rhs) { mGrids.reserve(mGrids.size() + rhs.size()); for (const auto& gridPtr: rhs) { mGrids.push_back(gridPtr->copyGrid()); } } void OpenVDBData::write(const openvdb::io::File& file, const openvdb::MetaMap& metadata) const { file.write(mGrids, metadata); } ////////////////////////////////////////
2,957
C++
15.252747
72
0.628678
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBCopyNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnStringData.h> #include <maya/MFnPluginData.h> #include <maya/MGlobal.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFloatVector.h> #include <boost/math/constants/constants.hpp> // boost::math::constants::pi namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBCopyNode : public MPxNode { OpenVDBCopyNode() {} virtual ~OpenVDBCopyNode() {} virtual MStatus compute(const MPlug& plug, MDataBlock& data); static void* creator(); static MStatus initialize(); static MTypeId id; static MObject aVdbInputA; static MObject aVdbInputB; static MObject aVdbOutput; static MObject aVdbSelectedGridNamesA; static MObject aVdbSelectedGridNamesB; }; MTypeId OpenVDBCopyNode::id(0x00108A58); MObject OpenVDBCopyNode::aVdbOutput; MObject OpenVDBCopyNode::aVdbInputA; MObject OpenVDBCopyNode::aVdbInputB; MObject OpenVDBCopyNode::aVdbSelectedGridNamesA; MObject OpenVDBCopyNode::aVdbSelectedGridNamesB; namespace { mvdb::NodeRegistry registerNode("OpenVDBCopy", OpenVDBCopyNode::id, OpenVDBCopyNode::creator, OpenVDBCopyNode::initialize); } //////////////////////////////////////// void* OpenVDBCopyNode::creator() { return new OpenVDBCopyNode(); } MStatus OpenVDBCopyNode::initialize() { MStatus stat; // attributes MFnTypedAttribute tAttr; MFnStringData strData; aVdbSelectedGridNamesA = tAttr.create("GridsFromA", "anames", MFnData::kString, strData.create("*"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aVdbSelectedGridNamesA); if (stat != MS::kSuccess) return stat; aVdbSelectedGridNamesB = tAttr.create("GridsFromB", "bnames", MFnData::kString, strData.create("*"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aVdbSelectedGridNamesB); if (stat != MS::kSuccess) return stat; // input / output aVdbInputA = tAttr.create("VdbInputA", "a", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(true); stat = addAttribute(aVdbInputA); if (stat != MS::kSuccess) return stat; aVdbInputB = tAttr.create("VdbInputB", "b", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(true); stat = addAttribute(aVdbInputB); if (stat != MS::kSuccess) return stat; aVdbOutput = tAttr.create("VdbOutput", "vdboutput", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setWritable(false); tAttr.setStorable(false); stat = addAttribute(aVdbOutput); if (stat != MS::kSuccess) return stat; // attribute dependencies stat = attributeAffects(aVdbInputA, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbInputB, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNamesA, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNamesB, aVdbOutput); if (stat != MS::kSuccess) return stat; return MS::kSuccess; } //////////////////////////////////////// MStatus OpenVDBCopyNode::compute(const MPlug& plug, MDataBlock& data) { if (plug == aVdbOutput) { const OpenVDBData* inputVdbA = mvdb::getInputVDB(aVdbInputA, data); const OpenVDBData* inputVdbB = mvdb::getInputVDB(aVdbInputB, data); MStatus status; MFnPluginData pluginData; pluginData.create(OpenVDBData::id, &status); if (status != MS::kSuccess) { MGlobal::displayError("Failed to create a new OpenVDBData object."); return MS::kFailure; } OpenVDBData* outputVdb = static_cast<OpenVDBData*>(pluginData.data(&status)); MDataHandle output = data.outputValue(aVdbOutput); if (inputVdbA && outputVdb) { const std::string selectionStr = data.inputValue(aVdbSelectedGridNamesA, &status).asString().asChar(); mvdb::GridCPtrVec grids; mvdb::getSelectedGrids(grids, selectionStr, *inputVdbA); for (mvdb::GridCPtrVecIter it = grids.begin(); it != grids.end(); ++it) { outputVdb->insert((*it)->copyGrid()); // shallow copy } } if (inputVdbB && outputVdb) { const std::string selectionStr = data.inputValue(aVdbSelectedGridNamesB, &status).asString().asChar(); mvdb::GridCPtrVec grids; mvdb::getSelectedGrids(grids, selectionStr, *inputVdbB); for (mvdb::GridCPtrVecIter it = grids.begin(); it != grids.end(); ++it) { outputVdb->insert((*it)->copyGrid()); // shallow copy } } output.set(outputVdb); return data.setClean(plug); } return MS::kUnknownParameter; }
5,266
C++
26.010256
112
0.653627
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBFromMayaFluidNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb/tools/Dense.h> #include <openvdb/math/Transform.h> #include <maya/MFnUnitAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MSelectionList.h> #include <maya/MFnFluid.h> #include <maya/MFnStringData.h> #include <maya/MFnPluginData.h> #include <maya/MGlobal.h> #include <maya/MMatrix.h> #include <maya/MPoint.h> #include <maya/MBoundingBox.h> #include <maya/MFnNumericAttribute.h> namespace mvdb = openvdb_maya; struct OpenVDBFromMayaFluidNode : public MPxNode { public: OpenVDBFromMayaFluidNode() {} virtual ~OpenVDBFromMayaFluidNode() {} virtual MStatus compute(const MPlug& plug, MDataBlock& data); static void* creator(); static MStatus initialize(); static MTypeId id; static MObject aFluidNodeName; static MObject aVdbOutput; static MObject aDensity; static MObject aDensityName; static MObject aTemperature; static MObject aTemperatureName; static MObject aPressure; static MObject aPressureName; static MObject aFuel; static MObject aFuelName; static MObject aFalloff; static MObject aFalloffName; static MObject aVelocity; static MObject aVelocityName; static MObject aColors; static MObject aColorsName; static MObject aCoordinates; static MObject aCoordinatesName; static MObject aTime; }; MTypeId OpenVDBFromMayaFluidNode::id(0x00108A55); MObject OpenVDBFromMayaFluidNode::aFluidNodeName; MObject OpenVDBFromMayaFluidNode::aVdbOutput; MObject OpenVDBFromMayaFluidNode::aDensity; MObject OpenVDBFromMayaFluidNode::aDensityName; MObject OpenVDBFromMayaFluidNode::aTemperature; MObject OpenVDBFromMayaFluidNode::aTemperatureName; MObject OpenVDBFromMayaFluidNode::aPressure; MObject OpenVDBFromMayaFluidNode::aPressureName; MObject OpenVDBFromMayaFluidNode::aFuel; MObject OpenVDBFromMayaFluidNode::aFuelName; MObject OpenVDBFromMayaFluidNode::aFalloff; MObject OpenVDBFromMayaFluidNode::aFalloffName; MObject OpenVDBFromMayaFluidNode::aVelocity; MObject OpenVDBFromMayaFluidNode::aVelocityName; MObject OpenVDBFromMayaFluidNode::aColors; MObject OpenVDBFromMayaFluidNode::aColorsName; MObject OpenVDBFromMayaFluidNode::aCoordinates; MObject OpenVDBFromMayaFluidNode::aCoordinatesName; MObject OpenVDBFromMayaFluidNode::aTime; namespace { mvdb::NodeRegistry registerNode("OpenVDBFromMayaFluid", OpenVDBFromMayaFluidNode::id, OpenVDBFromMayaFluidNode::creator, OpenVDBFromMayaFluidNode::initialize); } //////////////////////////////////////// void* OpenVDBFromMayaFluidNode::creator() { return new OpenVDBFromMayaFluidNode(); } MStatus OpenVDBFromMayaFluidNode::initialize() { MStatus stat; MFnTypedAttribute tAttr; MFnNumericAttribute nAttr; MFnStringData strData; aFluidNodeName = tAttr.create("FluidNodeName", "fluid", MFnData::kString, strData.create("fluidShape"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aFluidNodeName); if (stat != MS::kSuccess) return stat; aDensity = nAttr.create("Density", "d", MFnNumericData::kBoolean); nAttr.setDefault(true); nAttr.setConnectable(false); stat = addAttribute(aDensity); if (stat != MS::kSuccess) return stat; aDensityName = tAttr.create("DensityName", "dname", MFnData::kString, strData.create("density"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aDensityName); if (stat != MS::kSuccess) return stat; aTemperature = nAttr.create("Temperature", "t", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aTemperature); if (stat != MS::kSuccess) return stat; aTemperatureName = tAttr.create("TemperatureName", "tname", MFnData::kString, strData.create("temperature"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aTemperatureName); if (stat != MS::kSuccess) return stat; aPressure = nAttr.create("Pressure", "p", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aPressure); if (stat != MS::kSuccess) return stat; aPressureName = tAttr.create("PressureName", "pname", MFnData::kString, strData.create("pressure"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aPressureName); if (stat != MS::kSuccess) return stat; aFuel = nAttr.create("Fuel", "f", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aFuel); if (stat != MS::kSuccess) return stat; aFuelName = tAttr.create("FuelName", "fname", MFnData::kString, strData.create("fuel"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aFuelName); if (stat != MS::kSuccess) return stat; aFalloff = nAttr.create("Falloff", "falloff", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aFalloff); if (stat != MS::kSuccess) return stat; aFalloffName = tAttr.create("FalloffName", "falloffname", MFnData::kString, strData.create("falloff"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aFalloffName); if (stat != MS::kSuccess) return stat; aVelocity = nAttr.create("Velocity", "v", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aVelocity); if (stat != MS::kSuccess) return stat; aVelocityName = tAttr.create("VelocityName", "vname", MFnData::kString, strData.create("velocity"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aVelocityName); if (stat != MS::kSuccess) return stat; aColors = nAttr.create("Color", "cd", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aColors); if (stat != MS::kSuccess) return stat; aColorsName = tAttr.create("ColorsName", "cdname", MFnData::kString, strData.create("color"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aColorsName); if (stat != MS::kSuccess) return stat; aCoordinates = nAttr.create("Coordinates", "uvw", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aCoordinates); if (stat != MS::kSuccess) return stat; aCoordinatesName = tAttr.create("CoordinatesName", "uvwname", MFnData::kString, strData.create("coordinates"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aCoordinatesName); if (stat != MS::kSuccess) return stat; MFnUnitAttribute uniAttr; aTime = uniAttr.create("CurrentTime", "time", MFnUnitAttribute::kTime, 0.0, &stat); if (stat != MS::kSuccess) return stat; stat = addAttribute(aTime); if (stat != MS::kSuccess) return stat; // Setup the output vdb aVdbOutput = tAttr.create("VdbOutput", "vdb", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setWritable(false); tAttr.setStorable(false); stat = addAttribute(aVdbOutput); if (stat != MS::kSuccess) return stat; // Set the attribute dependencies stat = attributeAffects(message, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFluidNodeName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aDensity, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aDensityName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aTemperature, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aTemperatureName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aPressure, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aPressureName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFuel, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFuelName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFalloff, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFalloffName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVelocity, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVelocityName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aColors, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aColorsName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aCoordinates, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aCoordinatesName, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aTime, aVdbOutput); if (stat != MS::kSuccess) return stat; return MS::kSuccess; } //////////////////////////////////////// namespace internal { inline openvdb::math::Transform::Ptr getTransform(const MFnFluid& fluid) { // Construct local transform openvdb::Vec3I res; fluid.getResolution(res[0], res[1], res[2]); openvdb::Vec3d dim; fluid.getDimensions(dim[0], dim[1], dim[2]); if (res[0] > 0) dim[0] /= double(res[0]); if (res[1] > 0) dim[1] /= double(res[1]); if (res[2] > 0) dim[2] /= double(res[2]); MBoundingBox bbox = fluid.boundingBox(); MPoint pos = bbox.min(); openvdb::Mat4R mat1(dim[0], 0.0, 0.0, 0.0, 0.0, dim[1], 0.0, 0.0, 0.0, 0.0, dim[2], 0.0, pos.x, pos.y, pos.z, 1.0); // Get node transform MMatrix mm; MStatus status; MObject parent = fluid.parent(0, &status); if (status == MS::kSuccess) { MFnDagNode parentNode(parent); mm = parentNode.transformationMatrix(); } openvdb::Mat4R mat2(mm(0,0), mm(0,1), mm(0,2), mm(0,3), mm(1,0), mm(1,1), mm(1,2), mm(1,3), mm(2,0), mm(2,1), mm(2,2), mm(2,3), mm(3,0), mm(3,1), mm(3,2), mm(3,3)); return openvdb::math::Transform::createLinearTransform(mat1 * mat2); } template<typename value_t> void copyGrid(OpenVDBData& vdb, const std::string& name, const openvdb::math::Transform& xform, const value_t* data, const openvdb::CoordBBox& bbox, value_t bg, value_t tol) { if (data != NULL) { openvdb::FloatGrid::Ptr grid = openvdb::FloatGrid::create(bg); openvdb::tools::Dense<const value_t, openvdb::tools::LayoutXYZ> dense(bbox, data); openvdb::tools::copyFromDense(dense, grid->tree(), tol); grid->setName(name); grid->setTransform(xform.copy()); vdb.insert(grid); } } }; // namespace internal //////////////////////////////////////// MStatus OpenVDBFromMayaFluidNode::compute(const MPlug& plug, MDataBlock& data) { MStatus status; if (plug == aVdbOutput) { data.inputValue(aTime, &status); MString nodeName = data.inputValue(aFluidNodeName, &status).asString(); MObject fluidNode; MSelectionList selectionList; selectionList.add(nodeName); if (selectionList.length() != 0) { selectionList.getDependNode(0, fluidNode); } if (fluidNode.isNull()) { MGlobal::displayError("There is no fluid node with the given name."); return MS::kFailure; } if (!fluidNode.hasFn(MFn::kFluid)) { MGlobal::displayError("The named node is not a fluid."); return MS::kFailure; } MFnFluid fluid(fluidNode); if (fluid.object() == MObject::kNullObj) return MS::kFailure; openvdb::math::Transform::Ptr xform = internal::getTransform(fluid); unsigned int xRes, yRes, zRes; fluid.getResolution(xRes, yRes, zRes); // inclusive bbox openvdb::CoordBBox bbox(openvdb::Coord(0), openvdb::Coord(xRes-1, yRes-1, zRes-1)); // get output vdb MFnPluginData outputDataCreators; outputDataCreators.create(OpenVDBData::id, &status); if (status != MS::kSuccess) return status; OpenVDBData* vdb = static_cast<OpenVDBData*>(outputDataCreators.data(&status)); if (status != MS::kSuccess) return status; // convert fluid data if (data.inputValue(aDensity, &status).asBool()) { const std::string name = data.inputValue(aDensityName, &status).asString().asChar(); internal::copyGrid(*vdb, name, *xform, fluid.density(), bbox, 0.0f, 1e-7f); } if (data.inputValue(aTemperature, &status).asBool()) { const std::string name = data.inputValue(aTemperatureName, &status).asString().asChar(); internal::copyGrid(*vdb, name, *xform, fluid.temperature(), bbox, 0.0f, 1e-7f); } if (data.inputValue(aPressure, &status).asBool()) { const std::string name = data.inputValue(aPressureName, &status).asString().asChar(); internal::copyGrid(*vdb, name, *xform, fluid.pressure(), bbox, 0.0f, 1e-7f); } if (data.inputValue(aFuel, &status).asBool()) { const std::string name = data.inputValue(aFuelName, &status).asString().asChar(); internal::copyGrid(*vdb, name, *xform, fluid.fuel(), bbox, 0.0f, 1e-7f); } if (data.inputValue(aFalloff, &status).asBool()) { const std::string name = data.inputValue(aFalloffName, &status).asString().asChar(); internal::copyGrid(*vdb, name, *xform, fluid.falloff(), bbox, 0.0f, 1e-7f); } if (data.inputValue(aVelocity, &status).asBool()) { const std::string name = data.inputValue(aVelocityName, &status).asString().asChar(); float *xgrid, *ygrid, *zgrid; fluid.getVelocity(xgrid, ygrid, zgrid); internal::copyGrid(*vdb, name + "_x", *xform, xgrid, bbox, 0.0f, 1e-7f); internal::copyGrid(*vdb, name + "_y", *xform, ygrid, bbox, 0.0f, 1e-7f); internal::copyGrid(*vdb, name + "_z", *xform, zgrid, bbox, 0.0f, 1e-7f); } if (data.inputValue(aColors, &status).asBool()) { const std::string name = data.inputValue(aColorsName, &status).asString().asChar(); float *xgrid, *ygrid, *zgrid; fluid.getColors(xgrid, ygrid, zgrid); internal::copyGrid(*vdb, name + "_r", *xform, xgrid, bbox, 0.0f, 1e-7f); internal::copyGrid(*vdb, name + "_g", *xform, ygrid, bbox, 0.0f, 1e-7f); internal::copyGrid(*vdb, name + "_b", *xform, zgrid, bbox, 0.0f, 1e-7f); } if (data.inputValue(aCoordinates, &status).asBool()) { const std::string name = data.inputValue(aCoordinatesName, &status).asString().asChar(); float *xgrid, *ygrid, *zgrid; fluid.getCoordinates(xgrid, ygrid, zgrid); internal::copyGrid(*vdb, name + "_u", *xform, xgrid, bbox, 0.0f, 1e-7f); internal::copyGrid(*vdb, name + "_v", *xform, ygrid, bbox, 0.0f, 1e-7f); internal::copyGrid(*vdb, name + "_w", *xform, zgrid, bbox, 0.0f, 1e-7f); } // export grids MDataHandle outHandle = data.outputValue(aVdbOutput); outHandle.set(vdb); return data.setClean(plug); } return MS::kUnknownParameter; }
16,170
C++
31.934827
100
0.650216
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBFilterNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <openvdb/tools/Filter.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnStringData.h> #include <maya/MFnPluginData.h> #include <maya/MGlobal.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnNumericAttribute.h> namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBFilterNode : public MPxNode { OpenVDBFilterNode() {} virtual ~OpenVDBFilterNode() {} virtual MStatus compute(const MPlug& plug, MDataBlock& data); static void* creator(); static MStatus initialize(); static MTypeId id; static MObject aVdbInput; static MObject aVdbOutput; static MObject aVdbSelectedGridNames; static MObject aFilter; static MObject aRadius; static MObject aOffset; static MObject aIterations; }; MTypeId OpenVDBFilterNode::id(0x00108A56); MObject OpenVDBFilterNode::aVdbOutput; MObject OpenVDBFilterNode::aVdbInput; MObject OpenVDBFilterNode::aVdbSelectedGridNames; MObject OpenVDBFilterNode::aFilter; MObject OpenVDBFilterNode::aRadius; MObject OpenVDBFilterNode::aOffset; MObject OpenVDBFilterNode::aIterations; namespace { mvdb::NodeRegistry registerNode("OpenVDBFilter", OpenVDBFilterNode::id, OpenVDBFilterNode::creator, OpenVDBFilterNode::initialize); } //////////////////////////////////////// void* OpenVDBFilterNode::creator() { return new OpenVDBFilterNode(); } MStatus OpenVDBFilterNode::initialize() { MStatus stat; // attributes MFnTypedAttribute tAttr; MFnStringData strData; aVdbSelectedGridNames = tAttr.create("SelectedGridNames", "grids", MFnData::kString, strData.create("*"), &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aVdbSelectedGridNames); if (stat != MS::kSuccess) return stat; MFnEnumAttribute eAttr; aFilter = eAttr.create("Filter", "filter", 0, &stat); if (stat != MS::kSuccess) return stat; eAttr.addField("Mean", 0); eAttr.addField("Gauss", 1); eAttr.addField("Median", 2); eAttr.addField("Offset", 3); eAttr.setConnectable(false); stat = addAttribute(aFilter); if (stat != MS::kSuccess) return stat; MFnNumericAttribute nAttr; aRadius = nAttr.create("FilterVoxelRadius", "r", MFnNumericData::kInt); nAttr.setDefault(1); nAttr.setMin(1); nAttr.setSoftMin(1); nAttr.setSoftMax(5); stat = addAttribute(aRadius); if (stat != MS::kSuccess) return stat; aIterations = nAttr.create("Iterations", "it", MFnNumericData::kInt); nAttr.setDefault(1); nAttr.setMin(1); nAttr.setSoftMin(1); nAttr.setSoftMax(10); stat = addAttribute(aIterations); if (stat != MS::kSuccess) return stat; aOffset = nAttr.create("Offset", "o", MFnNumericData::kFloat); nAttr.setDefault(0.0); nAttr.setSoftMin(-1.0); nAttr.setSoftMax(1.0); stat = addAttribute(aOffset); if (stat != MS::kSuccess) return stat; // input / output aVdbInput = tAttr.create("VdbInput", "vdbinput", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(true); stat = addAttribute(aVdbInput); if (stat != MS::kSuccess) return stat; aVdbOutput = tAttr.create("VdbOutput", "vdboutput", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setWritable(false); tAttr.setStorable(false); stat = addAttribute(aVdbOutput); if (stat != MS::kSuccess) return stat; // attribute dependencies stat = attributeAffects(aVdbInput, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aFilter, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aVdbSelectedGridNames, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aRadius, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aOffset, aVdbOutput); if (stat != MS::kSuccess) return stat; stat = attributeAffects(aIterations, aVdbOutput); if (stat != MS::kSuccess) return stat; return MS::kSuccess; } //////////////////////////////////////// namespace internal { template <typename GridT> void filterGrid(openvdb::GridBase& grid, int operation, int radius, int iterations, float offset = 0.0) { GridT& gridRef = static_cast<GridT&>(grid); openvdb::tools::Filter<GridT> filter(gridRef); switch (operation) { case 0: filter.mean(radius, iterations); break; case 1: filter.gaussian(radius, iterations); break; case 2: filter.median(radius, iterations); break; case 3: filter.offset(typename GridT::ValueType(offset)); break; } } }; // namespace internal //////////////////////////////////////// MStatus OpenVDBFilterNode::compute(const MPlug& plug, MDataBlock& data) { if (plug == aVdbOutput) { const OpenVDBData* inputVdb = mvdb::getInputVDB(aVdbInput, data); MStatus status; MFnPluginData pluginData; pluginData.create(OpenVDBData::id, &status); if (status != MS::kSuccess) { MGlobal::displayError("Failed to create a new OpenVDBData object."); return MS::kFailure; } OpenVDBData* outputVdb = static_cast<OpenVDBData*>(pluginData.data(&status)); if (inputVdb && outputVdb) { const int operation = data.inputValue(aFilter, &status).asInt(); const int radius = data.inputValue(aRadius, &status).asInt(); const int iterations = data.inputValue(aIterations, &status).asInt(); const float offset = data.inputValue(aOffset, &status).asFloat(); const std::string selectionStr = data.inputValue(aVdbSelectedGridNames, &status).asString().asChar(); mvdb::GridCPtrVec grids; if (!mvdb::getSelectedGrids(grids, selectionStr, *inputVdb, *outputVdb)) { MGlobal::displayWarning("No grids are selected."); } for (mvdb::GridCPtrVecIter it = grids.begin(); it != grids.end(); ++it) { const openvdb::GridBase& gridRef = **it; if (gridRef.type() == openvdb::FloatGrid::gridType()) { openvdb::GridBase::Ptr grid = gridRef.deepCopyGrid(); // modifiable copy internal::filterGrid<openvdb::FloatGrid>(*grid, operation, radius, iterations, offset); outputVdb->insert(grid); } else if (gridRef.type() == openvdb::DoubleGrid::gridType()) { openvdb::GridBase::Ptr grid = gridRef.deepCopyGrid(); // modifiable copy internal::filterGrid<openvdb::DoubleGrid>(*grid, operation, radius, iterations, offset); outputVdb->insert(grid); } else { const std::string msg = "Skipped '" + gridRef.getName() + "', unsupported type."; MGlobal::displayWarning(msg.c_str()); outputVdb->insert(gridRef); } } MDataHandle output = data.outputValue(aVdbOutput); output.set(outputVdb); return data.setClean(plug); } } return MS::kUnknownParameter; }
7,564
C++
27.018518
117
0.634056
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBPlugin.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #ifndef OPENVDB_MAYA_PLUGIN_HAS_BEEN_INCLUDED #define OPENVDB_MAYA_PLUGIN_HAS_BEEN_INCLUDED #include <maya/MString.h> #include <maya/MTypeId.h> #include <maya/MPxData.h> #define MNoVersionString #include <maya/MFnPlugin.h> //////////////////////////////////////// namespace openvdb_maya { struct NodeRegistry { NodeRegistry(const MString& typeName, const MTypeId& typeId, MCreatorFunction creatorFunction, MInitializeFunction initFunction, MPxNode::Type type = MPxNode::kDependNode, const MString* classification = NULL); static void registerNodes(MFnPlugin& plugin, MStatus& status); static void deregisterNodes(MFnPlugin& plugin, MStatus& status); }; } // namespace openvdb_maya //////////////////////////////////////// #endif // OPENVDB_MAYA_NODE_REGISTRY_HAS_BEEN_INCLUDED
953
C
22.268292
68
0.674711
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBPlugin.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #include <openvdb_maya/OpenVDBData.h> #include "OpenVDBPlugin.h" #include <openvdb/Platform.h> #include <openvdb/openvdb.h> #include <openvdb/Types.h> // compiler pragmas #include <maya/MIOStream.h> #include <maya/MFnPlugin.h> #include <maya/MString.h> #include <maya/MArgList.h> #include <maya/MGlobal.h> #include <maya/MItSelectionList.h> #include <maya/MFnDependencyNode.h> #include <maya/MFnTypedAttribute.h> #include <maya/MPxData.h> #include <maya/MTypeId.h> #include <maya/MPlug.h> #include <maya/MFnPluginData.h> #include <tbb/mutex.h> #include <vector> #include <sstream> #include <string> //////////////////////////////////////// namespace openvdb_maya { namespace { struct NodeInfo { MString typeName; MTypeId typeId; MCreatorFunction creatorFunction; MInitializeFunction initFunction; MPxNode::Type type; const MString* classification; }; typedef std::vector<NodeInfo> NodeList; typedef tbb::mutex Mutex; typedef Mutex::scoped_lock Lock; // Declare this at file scope to ensure thread-safe initialization. Mutex sRegistryMutex; NodeList * gNodes = NULL; } // unnamed namespace NodeRegistry::NodeRegistry(const MString& typeName, const MTypeId& typeId, MCreatorFunction creatorFunction, MInitializeFunction initFunction, MPxNode::Type type, const MString* classification) { NodeInfo node; node.typeName = typeName; node.typeId = typeId; node.creatorFunction = creatorFunction; node.initFunction = initFunction; node.type = type; node.classification = classification; Lock lock(sRegistryMutex); if (!gNodes) { OPENVDB_START_THREADSAFE_STATIC_WRITE gNodes = new NodeList(); OPENVDB_FINISH_THREADSAFE_STATIC_WRITE } gNodes->push_back(node); } void NodeRegistry::registerNodes(MFnPlugin& plugin, MStatus& status) { Lock lock(sRegistryMutex); if (gNodes) { for (size_t n = 0, N = gNodes->size(); n < N; ++n) { const NodeInfo& node = (*gNodes)[n]; status = plugin.registerNode(node.typeName, node.typeId, node.creatorFunction, node.initFunction, node.type, node.classification); if (!status) { const std::string msg = "Failed to register '" + std::string(node.typeName.asChar()) + "'"; status.perror(msg.c_str()); break; } } } } void NodeRegistry::deregisterNodes(MFnPlugin& plugin, MStatus& status) { Lock lock(sRegistryMutex); if (gNodes) { for (size_t n = 0, N = gNodes->size(); n < N; ++n) { const NodeInfo& node = (*gNodes)[n]; status = plugin.deregisterNode(node.typeId); if (!status) { const std::string msg = "Failed to deregister '" + std::string(node.typeName.asChar()) + "'"; status.perror(msg.c_str()); break; } } } } } // namespace openvdb_maya //////////////////////////////////////// MStatus initializePlugin(MObject); MStatus uninitializePlugin(MObject); MStatus initializePlugin(MObject obj) { openvdb::initialize(); MStatus status; MFnPlugin plugin(obj, "DreamWorks Animation", "0.5", "Any"); status = plugin.registerData("OpenVDBData", OpenVDBData::id, OpenVDBData::creator); if (!status) { status.perror("Failed to register 'OpenVDBData'"); return status; } openvdb_maya::NodeRegistry::registerNodes(plugin, status); return status; } MStatus uninitializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj); openvdb_maya::NodeRegistry::deregisterNodes(plugin, status); status = plugin.deregisterData(OpenVDBData::id); if (!status) { status.perror("Failed to deregister 'OpenVDBData'"); return status; } return status; } ////////////////////////////////////////
4,108
C++
21.576923
89
0.620983
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBToPolygonsNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file OpenVDBToPolygonsNode.cc /// /// @author Fredrik Salomonsson ([email protected]) #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <openvdb/tools/VolumeToMesh.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFloatPointArray.h> #include <maya/MPointArray.h> #include <maya/MItMeshPolygon.h> #include <maya/MFnMeshData.h> #include <maya/MFnStringData.h> #include <maya/MFnPluginData.h> #include <maya/MGlobal.h> #include <maya/MFnMesh.h> #include <maya/MFnNumericAttribute.h> #include <maya/MArrayDataHandle.h> #include <maya/MArrayDataBuilder.h> #include <tbb/blocked_range.h> #include <tbb/parallel_for.h> #include <memory> #include <string> #include <vector> namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBToPolygonsNode : public MPxNode { OpenVDBToPolygonsNode() {} ~OpenVDBToPolygonsNode() override = default; MStatus compute(const MPlug& plug, MDataBlock& data) override; static void * creator(); static MStatus initialize(); static MTypeId id; static MObject aVdbInput; static MObject aIsovalue; static MObject aAdaptivity; static MObject aVdbAllGridNames; static MObject aVdbSelectedGridNames; static MObject aMeshOutput; }; MTypeId OpenVDBToPolygonsNode::id(0x00108A59); MObject OpenVDBToPolygonsNode::aVdbInput; MObject OpenVDBToPolygonsNode::aIsovalue; MObject OpenVDBToPolygonsNode::aAdaptivity; MObject OpenVDBToPolygonsNode::aVdbAllGridNames; MObject OpenVDBToPolygonsNode::aVdbSelectedGridNames; MObject OpenVDBToPolygonsNode::aMeshOutput; //////////////////////////////////////// namespace { mvdb::NodeRegistry registerNode("OpenVDBToPolygons", OpenVDBToPolygonsNode::id, OpenVDBToPolygonsNode::creator, OpenVDBToPolygonsNode::initialize); // Internal utility methods class VDBToMayaMesh { public: MObject mesh; VDBToMayaMesh(openvdb::tools::VolumeToMesh& mesher): mesh(), mMesher(&mesher) { } template<typename GridType> inline void operator()(typename GridType::ConstPtr); private: openvdb::tools::VolumeToMesh * const mMesher; struct PointCopyOp; struct FaceCopyOp; }; // VDBToMayaMesh struct VDBToMayaMesh::PointCopyOp { PointCopyOp(MFloatPointArray& mayaPoints, const openvdb::tools::PointList& vdbPoints) : mMayaPoints(&mayaPoints) , mVdbPoints(&vdbPoints) { } void operator()(const tbb::blocked_range<size_t>& range) const { for (size_t n = range.begin(), N = range.end(); n < N; ++n) { const openvdb::Vec3s& p_vdb = (*mVdbPoints)[n]; MFloatPoint& p_maya = (*mMayaPoints)[static_cast<unsigned int>(n)]; p_maya[0] = p_vdb[0]; p_maya[1] = p_vdb[1]; p_maya[2] = p_vdb[2]; } } private: MFloatPointArray * const mMayaPoints; openvdb::tools::PointList const * const mVdbPoints; }; struct VDBToMayaMesh::FaceCopyOp { using UInt32Array = std::unique_ptr<uint32_t[]>; FaceCopyOp(MIntArray& indices, MIntArray& polyCount, const UInt32Array& numQuadsPrefix, const UInt32Array& numTrianglesPrefix, const openvdb::tools::PolygonPoolList& polygonPoolList) : mIndices(&indices) , mPolyCount(&polyCount) , mNumQuadsPrefix(numQuadsPrefix.get()) , mNumTrianglesPrefix(numTrianglesPrefix.get()) , mPolygonPoolList(&polygonPoolList) { } void operator()(const tbb::blocked_range<size_t>& range) const { const uint32_t numQuads = mNumQuadsPrefix[range.begin()]; const uint32_t numTriangles = mNumTrianglesPrefix[range.begin()]; uint32_t face = numQuads + numTriangles; uint32_t vertex = 4*numQuads + 3*numTriangles; MIntArray& indices = *mIndices; MIntArray& polyCount = *mPolyCount; // Setup the polygon count and polygon indices for (size_t n = range.begin(), N = range.end(); n < N; ++n) { const openvdb::tools::PolygonPool& polygons = (*mPolygonPoolList)[n]; // Add all quads in the polygon pool for (size_t i = 0, I = polygons.numQuads(); i < I; ++i) { polyCount[face++] = 4; const openvdb::Vec4I& quad = polygons.quad(i); indices[vertex++] = quad[0]; indices[vertex++] = quad[1]; indices[vertex++] = quad[2]; indices[vertex++] = quad[3]; } // Add all triangles in the polygon pool for (size_t i = 0, I = polygons.numTriangles(); i < I; ++i) { polyCount[face++] = 3; const openvdb::Vec3I& triangle = polygons.triangle(i); indices[vertex++] = triangle[0]; indices[vertex++] = triangle[1]; indices[vertex++] = triangle[2]; } } } private: MIntArray * const mIndices; MIntArray * const mPolyCount; uint32_t const * const mNumQuadsPrefix; uint32_t const * const mNumTrianglesPrefix; openvdb::tools::PolygonPoolList const * const mPolygonPoolList; }; template<typename GridType> inline void VDBToMayaMesh::operator()(typename GridType::ConstPtr grid) { // extract polygonal surface (*mMesher)(*grid); // transfer quads and triangles MIntArray polygonCounts, polygonConnects; { const size_t polygonPoolListSize = mMesher->polygonPoolListSize(); std::unique_ptr<uint32_t[]> numQuadsPrefix(new uint32_t[polygonPoolListSize]); std::unique_ptr<uint32_t[]> numTrianglesPrefix(new uint32_t[polygonPoolListSize]); uint32_t numQuads = 0, numTriangles = 0; openvdb::tools::PolygonPoolList& polygonPoolList = mMesher->polygonPoolList(); for (size_t n = 0; n < polygonPoolListSize; ++n) { numQuadsPrefix[n] = numQuads; numTrianglesPrefix[n] = numTriangles; numQuads += uint32_t(polygonPoolList[n].numQuads()); numTriangles += uint32_t(polygonPoolList[n].numTriangles()); } polygonCounts.setLength(numQuads + numTriangles); polygonConnects.setLength(4*numQuads + 3*numTriangles); tbb::parallel_for(tbb::blocked_range<size_t>(0, polygonPoolListSize), FaceCopyOp(polygonConnects, polygonCounts, numQuadsPrefix, numTrianglesPrefix, polygonPoolList)); polygonPoolList.reset(); // delete polygons } // transfer points const size_t numPoints = mMesher->pointListSize(); MFloatPointArray vertexArray(static_cast<unsigned int>(numPoints)); tbb::parallel_for(tbb::blocked_range<size_t>(0, numPoints), PointCopyOp(vertexArray, mMesher->pointList())); mMesher->pointList().reset(); // delete points mesh = MFnMeshData().create(); MFnMesh().create(vertexArray.length(), polygonCounts.length(), vertexArray, polygonCounts, polygonConnects, mesh); } } // unnamed namespace //////////////////////////////////////// void* OpenVDBToPolygonsNode::creator() { return new OpenVDBToPolygonsNode(); } MStatus OpenVDBToPolygonsNode::initialize() { MStatus stat; MFnNumericAttribute nAttr; MFnTypedAttribute tAttr; // Setup input / output attributes aVdbInput = tAttr.create( "vdbInput", "input", OpenVDBData::id, MObject::kNullObj, &stat ); if (stat != MS::kSuccess) return stat; tAttr.setReadable(false); stat = addAttribute(aVdbInput); if (stat != MS::kSuccess) return stat; aMeshOutput = tAttr.create("meshOutput", "mesh", MFnData::kMesh, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setReadable(true); tAttr.setWritable(false); tAttr.setStorable(false); tAttr.setArray(true); tAttr.setUsesArrayDataBuilder(true); stat = addAttribute(aMeshOutput); if (stat != MS::kSuccess) return stat; // Setup UI attributes aIsovalue = nAttr.create("isovalue", "iso", MFnNumericData::kFloat); nAttr.setDefault(0.0); nAttr.setSoftMin(-1.0); nAttr.setSoftMax( 1.0); nAttr.setConnectable(false); stat = addAttribute(aIsovalue); if (stat != MS::kSuccess) return stat; aAdaptivity = nAttr.create("adaptivity", "adapt", MFnNumericData::kFloat); nAttr.setDefault(0.0); nAttr.setMin(0.0); nAttr.setMax( 1.0); nAttr.setConnectable(false); stat = addAttribute(aAdaptivity); if (stat != MS::kSuccess) return stat; MFnStringData fnStringData; MObject defaultStringData = fnStringData.create(""); aVdbAllGridNames = tAttr.create("vdbAllGridNames", "allgrids", MFnData::kString, defaultStringData, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); tAttr.setReadable(false); tAttr.setHidden(true); stat = addAttribute(aVdbAllGridNames); if (stat != MS::kSuccess) return stat; aVdbSelectedGridNames = tAttr.create("vdbSelectedGridNames", "selectedgrids", MFnData::kString, defaultStringData, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); tAttr.setReadable(false); tAttr.setHidden(true); stat = addAttribute(aVdbSelectedGridNames); if (stat != MS::kSuccess) return stat; // Setup dependencies attributeAffects(aVdbInput, aVdbAllGridNames); attributeAffects(aVdbInput, aMeshOutput); attributeAffects(aIsovalue, aMeshOutput); attributeAffects(aAdaptivity, aMeshOutput); attributeAffects(aVdbSelectedGridNames, aMeshOutput); return MS::kSuccess; } //////////////////////////////////////// MStatus OpenVDBToPolygonsNode::compute(const MPlug& plug, MDataBlock& data) { MStatus status; const OpenVDBData* inputVdb = mvdb::getInputVDB(aVdbInput, data); if (!inputVdb) return MS::kFailure; if (plug == aVdbAllGridNames) { MString names = mvdb::getGridNames(*inputVdb).c_str(); MDataHandle outHandle = data.outputValue(aVdbAllGridNames); outHandle.set(names); return data.setClean(plug); } // Get selected grids MDataHandle selectionHandle = data.inputValue(aVdbSelectedGridNames, &status); if (status != MS::kSuccess) return status; std::string names = selectionHandle.asString().asChar(); std::vector<openvdb::GridBase::ConstPtr> grids; mvdb::getGrids(grids, *inputVdb, names); if (grids.empty()) { return MS::kUnknownParameter; } // Convert Openvdbs to meshes if (plug == aMeshOutput) { MDataHandle isoHandle = data.inputValue(aIsovalue, &status); if (status != MS::kSuccess) return status; MDataHandle adaptHandle = data.inputValue(aAdaptivity, &status); if (status != MS::kSuccess) return status; openvdb::tools::VolumeToMesh mesher(isoHandle.asFloat(), adaptHandle.asFloat()); MArrayDataHandle outArrayHandle = data.outputArrayValue(aMeshOutput, &status); if (status != MS::kSuccess) return status; MArrayDataBuilder builder(aMeshOutput, static_cast<unsigned int>(grids.size()), &status); for (size_t n = 0, N = grids.size(); n < N; ++n) { VDBToMayaMesh converter(mesher); if (mvdb::processTypedScalarGrid(grids[n], converter)) { MDataHandle outHandle = builder.addElement(static_cast<unsigned int>(n)); outHandle.set(converter.mesh); } } status = outArrayHandle.set(builder); if (status != MS::kSuccess) return status; status = outArrayHandle.setAllClean(); if (status != MS::kSuccess) return status; } else { return MS::kUnknownParameter; } return data.setClean(plug); }
11,872
C++
30.16273
97
0.655997
NVIDIA-Omniverse/ext-openvdb/openvdb_maya/openvdb_maya/OpenVDBFromPolygonsNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @author FX R&D OpenVDB team #include "OpenVDBPlugin.h" #include <openvdb_maya/OpenVDBData.h> #include <openvdb_maya/OpenVDBUtil.h> #include <openvdb/tools/MeshToVolume.h> #include <openvdb/tools/LevelSetUtil.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFloatPointArray.h> #include <maya/MPointArray.h> #include <maya/MItMeshPolygon.h> #include <maya/MFnMeshData.h> #include <maya/MFnStringData.h> #include <maya/MFnPluginData.h> #include <maya/MGlobal.h> #include <maya/MFnMesh.h> #include <maya/MFnNumericAttribute.h> #include <memory> // std::auto_ptr namespace mvdb = openvdb_maya; //////////////////////////////////////// struct OpenVDBFromPolygonsNode : public MPxNode { OpenVDBFromPolygonsNode() {} virtual ~OpenVDBFromPolygonsNode() {} virtual MStatus compute(const MPlug& plug, MDataBlock& data); static void* creator(); static MStatus initialize(); static MTypeId id; static MObject aMeshInput; static MObject aVdbOutput; static MObject aExportDistanceGrid; static MObject aDistanceGridName; static MObject aExportDensityGrid; static MObject aDensityGridName; static MObject aVoxelSize; static MObject aExteriorBandWidth; static MObject aInteriorBandWidth; static MObject aFillInterior; static MObject aUnsignedDistanceField; static MObject aEstimatedGridResolution; static MObject aNodeInfo; }; MTypeId OpenVDBFromPolygonsNode::id(0x00108A54); MObject OpenVDBFromPolygonsNode::aMeshInput; MObject OpenVDBFromPolygonsNode::aVdbOutput; MObject OpenVDBFromPolygonsNode::aExportDistanceGrid; MObject OpenVDBFromPolygonsNode::aDistanceGridName; MObject OpenVDBFromPolygonsNode::aExportDensityGrid; MObject OpenVDBFromPolygonsNode::aDensityGridName; MObject OpenVDBFromPolygonsNode::aVoxelSize; MObject OpenVDBFromPolygonsNode::aExteriorBandWidth; MObject OpenVDBFromPolygonsNode::aInteriorBandWidth; MObject OpenVDBFromPolygonsNode::aFillInterior; MObject OpenVDBFromPolygonsNode::aUnsignedDistanceField; MObject OpenVDBFromPolygonsNode::aEstimatedGridResolution; MObject OpenVDBFromPolygonsNode::aNodeInfo; namespace { mvdb::NodeRegistry registerNode("OpenVDBFromPolygons", OpenVDBFromPolygonsNode::id, OpenVDBFromPolygonsNode::creator, OpenVDBFromPolygonsNode::initialize); } //////////////////////////////////////// void* OpenVDBFromPolygonsNode::creator() { return new OpenVDBFromPolygonsNode(); } MStatus OpenVDBFromPolygonsNode::initialize() { MStatus stat; MFnTypedAttribute tAttr; MFnNumericAttribute nAttr; // Setup the input mesh attribute MFnMeshData meshCreator; MObject emptyMesh = meshCreator.create(&stat); if (stat != MS::kSuccess) return stat; MFnStringData fnStringData; MObject distName = fnStringData.create("surface"); MObject densName = fnStringData.create("density"); MObject emptyStr = fnStringData.create(""); aMeshInput = tAttr.create("MeshInput", "mesh", MFnData::kMesh, emptyMesh, &stat); if (stat != MS::kSuccess) return stat; stat = addAttribute(aMeshInput); if (stat != MS::kSuccess) return stat; // Conversion settings aExportDistanceGrid = nAttr.create( "ExportDistanceVDB", "exportdistance", MFnNumericData::kBoolean); nAttr.setDefault(true); nAttr.setConnectable(false); stat = addAttribute(aExportDistanceGrid); if (stat != MS::kSuccess) return stat; aDistanceGridName = tAttr.create( "DistanceGridName", "distancename", MFnData::kString, distName, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aDistanceGridName); if (stat != MS::kSuccess) return stat; aExportDensityGrid = nAttr.create( "ExportDensityVDB", "exportdensity", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aExportDensityGrid); if (stat != MS::kSuccess) return stat; aDensityGridName = tAttr.create( "DensityGridName", "densityname", MFnData::kString, densName, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); stat = addAttribute(aDensityGridName); if (stat != MS::kSuccess) return stat; aVoxelSize = nAttr.create("VoxelSize", "voxelsize", MFnNumericData::kFloat); nAttr.setDefault(1.0); nAttr.setMin(1e-5); nAttr.setSoftMin(0.0); nAttr.setSoftMax(10.0); stat = addAttribute(aVoxelSize); if (stat != MS::kSuccess) return stat; aExteriorBandWidth = nAttr.create( "ExteriorBandWidth", "exteriorbandwidth", MFnNumericData::kFloat); nAttr.setDefault(3.0); nAttr.setMin(1.0); nAttr.setSoftMin(1.0); nAttr.setSoftMax(10.0); stat = addAttribute(aExteriorBandWidth); if (stat != MS::kSuccess) return stat; aInteriorBandWidth = nAttr.create( "InteriorBandWidth", "interiorbandwidth", MFnNumericData::kFloat); nAttr.setDefault(3.0); nAttr.setMin(1.0); nAttr.setSoftMin(1.0); nAttr.setSoftMax(10.0); stat = addAttribute(aInteriorBandWidth); if (stat != MS::kSuccess) return stat; aFillInterior = nAttr.create("FillInterior", "fillinterior", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aFillInterior); if (stat != MS::kSuccess) return stat; aUnsignedDistanceField = nAttr.create( "UnsignedDistanceField", "udf", MFnNumericData::kBoolean); nAttr.setDefault(false); nAttr.setConnectable(false); stat = addAttribute(aUnsignedDistanceField); if (stat != MS::kSuccess) return stat; // Setup the output attributes aVdbOutput = tAttr.create("VdbOutput", "vdb", OpenVDBData::id, MObject::kNullObj, &stat); if (stat != MS::kSuccess) return stat; tAttr.setWritable(false); tAttr.setStorable(false); stat = addAttribute(aVdbOutput); if (stat != MS::kSuccess) return stat; // VDB Info aEstimatedGridResolution = tAttr.create( "EstimatedGridResolution", "res", MFnData::kString, emptyStr, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); stat = addAttribute(aEstimatedGridResolution); if (stat != MS::kSuccess) return stat; aNodeInfo = tAttr.create("NodeInfo", "info", MFnData::kString, emptyStr, &stat); if (stat != MS::kSuccess) return stat; tAttr.setConnectable(false); tAttr.setWritable(false); stat = addAttribute(aNodeInfo); if (stat != MS::kSuccess) return stat; // Set the attribute dependencies attributeAffects(aMeshInput, aVdbOutput); attributeAffects(aExportDistanceGrid, aVdbOutput); attributeAffects(aDistanceGridName, aVdbOutput); attributeAffects(aExportDensityGrid, aVdbOutput); attributeAffects(aDensityGridName, aVdbOutput); attributeAffects(aVoxelSize, aVdbOutput); attributeAffects(aExteriorBandWidth, aVdbOutput); attributeAffects(aInteriorBandWidth, aVdbOutput); attributeAffects(aFillInterior, aVdbOutput); attributeAffects(aUnsignedDistanceField, aVdbOutput); attributeAffects(aMeshInput, aEstimatedGridResolution); attributeAffects(aVoxelSize, aEstimatedGridResolution); attributeAffects(aMeshInput, aNodeInfo); attributeAffects(aExportDistanceGrid, aNodeInfo); attributeAffects(aDistanceGridName, aNodeInfo); attributeAffects(aExportDensityGrid, aNodeInfo); attributeAffects(aDensityGridName, aNodeInfo); attributeAffects(aVoxelSize, aNodeInfo); attributeAffects(aExteriorBandWidth, aNodeInfo); attributeAffects(aInteriorBandWidth, aNodeInfo); attributeAffects(aFillInterior, aNodeInfo); attributeAffects(aUnsignedDistanceField, aNodeInfo); return MS::kSuccess; } //////////////////////////////////////// MStatus OpenVDBFromPolygonsNode::compute(const MPlug& plug, MDataBlock& data) { MStatus status; if (plug == aEstimatedGridResolution) { const float voxelSize = data.inputValue(aVoxelSize, &status).asFloat(); if (status != MS::kSuccess) return status; if (!(voxelSize > 0.0)) return MS::kFailure; MDataHandle meshHandle = data.inputValue(aMeshInput, &status); if (status != MS::kSuccess) return status; MObject tmpObj = meshHandle.asMesh(); if (tmpObj == MObject::kNullObj) return MS::kFailure; MObject obj = meshHandle.asMeshTransformed(); if (obj == MObject::kNullObj) return MS::kFailure; MFnMesh mesh(obj); MFloatPointArray vertexArray; status = mesh.getPoints(vertexArray, MSpace::kWorld); if (status != MS::kSuccess) return status; openvdb::Vec3s pmin(std::numeric_limits<float>::max()), pmax(-std::numeric_limits<float>::max()); for(unsigned i = 0, I = vertexArray.length(); i < I; ++i) { pmin[0] = std::min(pmin[0], vertexArray[i].x); pmin[1] = std::min(pmin[1], vertexArray[i].y); pmin[2] = std::min(pmin[2], vertexArray[i].z); pmax[0] = std::max(pmax[0], vertexArray[i].x); pmax[1] = std::max(pmax[1], vertexArray[i].y); pmax[2] = std::max(pmax[2], vertexArray[i].z); } pmax = (pmax - pmin) / voxelSize; int xres = int(std::ceil(pmax[0])); int yres = int(std::ceil(pmax[1])); int zres = int(std::ceil(pmax[2])); std::stringstream txt; txt << xres << " x " << yres << " x " << zres << " voxels"; MString str = txt.str().c_str(); MDataHandle strHandle = data.outputValue(aEstimatedGridResolution); strHandle.set(str); return data.setClean(plug); } else if (plug == aVdbOutput || plug == aNodeInfo) { MDataHandle meshHandle = data.inputValue(aMeshInput, &status); if (status != MS::kSuccess) return status; { MObject obj = meshHandle.asMesh(); if (obj == MObject::kNullObj) return MS::kFailure; } MObject obj = meshHandle.asMeshTransformed(); if (obj == MObject::kNullObj) return MS::kFailure; MFnMesh mesh(obj); mvdb::Timer computeTimer; std::stringstream infoStr; const bool exportDistanceGrid = data.inputValue(aExportDistanceGrid, &status).asBool(); const bool exportDensityGrid = data.inputValue(aExportDensityGrid, &status).asBool(); MFnPluginData pluginData; pluginData.create(OpenVDBData::id, &status); if (status != MS::kSuccess) { MGlobal::displayError("Failed to create a new OpenVDBData object."); return MS::kFailure; } OpenVDBData* vdb = static_cast<OpenVDBData*>(pluginData.data(&status)); if (status != MS::kSuccess || !vdb) return MS::kFailure; MDataHandle outHandle = data.outputValue(aVdbOutput); float voxelSize = data.inputValue(aVoxelSize, &status).asFloat(); if (status != MS::kSuccess) return status; if (!(voxelSize > 0.0)) return MS::kFailure; openvdb::math::Transform::Ptr transform; try { transform = openvdb::math::Transform::createLinearTransform(voxelSize); } catch (openvdb::ArithmeticError) { MGlobal::displayError("Invalid voxel size."); return MS::kFailure; } MFloatPointArray vertexArray; status = mesh.getPoints(vertexArray, MSpace::kWorld); if (status != MS::kSuccess) return status; openvdb::Vec3d pos; std::vector<openvdb::Vec3s> pointList(vertexArray.length()); for(unsigned i = 0, I = vertexArray.length(); i < I; ++i) { pos[0] = double(vertexArray[i].x); pos[1] = double(vertexArray[i].y); pos[2] = double(vertexArray[i].z); pos = transform->worldToIndex(pos); pointList[i][0] = float(pos[0]); pointList[i][1] = float(pos[1]); pointList[i][2] = float(pos[2]); } std::vector<openvdb::Vec4I> primList; MIntArray vertices; for (MItMeshPolygon mIt(obj); !mIt.isDone(); mIt.next()) { mIt.getVertices(vertices); if (vertices.length() < 3) { MGlobal::displayWarning( "Skipped unsupported geometry, single point or line primitive."); } else if (vertices.length() > 4) { MPointArray points; MIntArray triangleVerts; mIt.getTriangles(points, triangleVerts); for(unsigned idx = 0; idx < triangleVerts.length(); idx+=3) { openvdb::Vec4I prim( triangleVerts[idx], triangleVerts[idx+1], triangleVerts[idx+2], openvdb::util::INVALID_IDX); primList.push_back(prim); } } else { mIt.getVertices(vertices); openvdb::Vec4I prim(vertices[0], vertices[1], vertices[2], (vertices.length() < 4) ? openvdb::util::INVALID_IDX : vertices[3]); primList.push_back(prim); } } infoStr << "Input Mesh\n"; infoStr << " nr of points: " << vertexArray.length() << "\n"; infoStr << " nr of primitives: " << primList.size() << "\n"; if (exportDistanceGrid || exportDensityGrid) { float exteriorBandWidth = data.inputValue(aExteriorBandWidth, &status).asFloat(); float interiorBandWidth = exteriorBandWidth; int conversionFlags = 0; // convert to SDF if (!data.inputValue(aUnsignedDistanceField, &status).asBool()) { if (!data.inputValue(aFillInterior, &status).asBool()) { interiorBandWidth = data.inputValue(aInteriorBandWidth, &status).asFloat(); } else { interiorBandWidth = std::numeric_limits<float>::max(); } } else { conversionFlags = openvdb::tools::UNSIGNED_DISTANCE_FIELD; } openvdb::tools::QuadAndTriangleDataAdapter<openvdb::Vec3s, openvdb::Vec4I> theMesh(pointList, primList); openvdb::FloatGrid::Ptr grid = openvdb::tools::meshToVolume<openvdb::FloatGrid>( theMesh, *transform, exteriorBandWidth, interiorBandWidth, conversionFlags); // export distance grid if (exportDistanceGrid) { std::string name = data.inputValue(aDistanceGridName, &status).asString().asChar(); if (!name.empty()) grid->setName(name); vdb->insert(grid); } // export density grid if (exportDensityGrid) { std::string name = data.inputValue(aDensityGridName, &status).asString().asChar(); openvdb::FloatGrid::Ptr densityGrid; if (exportDistanceGrid) { densityGrid = grid->deepCopy(); } else { densityGrid = grid; } openvdb::tools::sdfToFogVolume(*densityGrid); if (!name.empty()) densityGrid->setName(name); vdb->insert(densityGrid); } } std::string elapsedTime = computeTimer.elapsedTime(); mvdb::printGridInfo(infoStr, *vdb); infoStr << "Compute Time: " << elapsedTime << "\n"; mvdb::updateNodeInfo(infoStr, data, aNodeInfo); outHandle.set(vdb); return data.setClean(plug); } return MS::kUnknownParameter; }
15,767
C++
31.311475
99
0.640578
NVIDIA-Omniverse/ext-openvdb/openvdb/openvdb/Types.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #ifndef OPENVDB_TYPES_HAS_BEEN_INCLUDED #define OPENVDB_TYPES_HAS_BEEN_INCLUDED #include "version.h" #include "Platform.h" #include "TypeList.h" // backwards compat #include <OpenEXR/half.h> #include <openvdb/math/Math.h> #include <openvdb/math/BBox.h> #include <openvdb/math/Quat.h> #include <openvdb/math/Vec2.h> #include <openvdb/math/Vec3.h> #include <openvdb/math/Vec4.h> #include <openvdb/math/Mat3.h> #include <openvdb/math/Mat4.h> #include <openvdb/math/Coord.h> #include <cstdint> #include <memory> #include <type_traits> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { // One-dimensional scalar types using Index32 = uint32_t; using Index64 = uint64_t; using Index = Index32; using Int16 = int16_t; using Int32 = int32_t; using Int64 = int64_t; using Int = Int32; using Byte = unsigned char; using Real = double; // Two-dimensional vector types using Vec2R = math::Vec2<Real>; using Vec2I = math::Vec2<Index32>; using Vec2f = math::Vec2<float>; using Vec2H = math::Vec2<half>; using math::Vec2i; using math::Vec2s; using math::Vec2d; // Three-dimensional vector types using Vec3R = math::Vec3<Real>; using Vec3I = math::Vec3<Index32>; using Vec3f = math::Vec3<float>; using Vec3H = math::Vec3<half>; using Vec3U8 = math::Vec3<uint8_t>; using Vec3U16 = math::Vec3<uint16_t>; using math::Vec3i; using math::Vec3s; using math::Vec3d; using math::Coord; using math::CoordBBox; using BBoxd = math::BBox<Vec3d>; // Four-dimensional vector types using Vec4R = math::Vec4<Real>; using Vec4I = math::Vec4<Index32>; using Vec4f = math::Vec4<float>; using Vec4H = math::Vec4<half>; using math::Vec4i; using math::Vec4s; using math::Vec4d; // Three-dimensional matrix types using Mat3R = math::Mat3<Real>; using math::Mat3s; using math::Mat3d; // Four-dimensional matrix types using Mat4R = math::Mat4<Real>; using math::Mat4s; using math::Mat4d; // Quaternions using QuatR = math::Quat<Real>; using math::Quats; using math::Quatd; // Dummy type for a voxel with a binary mask value, e.g. the active state class ValueMask {}; // Use STL shared pointers from OpenVDB 4 on. template<typename T> using SharedPtr = std::shared_ptr<T>; template<typename T> using WeakPtr = std::weak_ptr<T>; /// @brief Return a new shared pointer that points to the same object /// as the given pointer but with possibly different <TT>const</TT>-ness. /// @par Example: /// @code /// FloatGrid::ConstPtr grid = ...; /// FloatGrid::Ptr nonConstGrid = ConstPtrCast<FloatGrid>(grid); /// FloatGrid::ConstPtr constGrid = ConstPtrCast<const FloatGrid>(nonConstGrid); /// @endcode template<typename T, typename U> inline SharedPtr<T> ConstPtrCast(const SharedPtr<U>& ptr) { return std::const_pointer_cast<T, U>(ptr); } /// @brief Return a new shared pointer that is either null or points to /// the same object as the given pointer after a @c dynamic_cast. /// @par Example: /// @code /// GridBase::ConstPtr grid = ...; /// FloatGrid::ConstPtr floatGrid = DynamicPtrCast<const FloatGrid>(grid); /// @endcode template<typename T, typename U> inline SharedPtr<T> DynamicPtrCast(const SharedPtr<U>& ptr) { return std::dynamic_pointer_cast<T, U>(ptr); } /// @brief Return a new shared pointer that points to the same object /// as the given pointer after a @c static_cast. /// @par Example: /// @code /// FloatGrid::Ptr floatGrid = ...; /// GridBase::Ptr grid = StaticPtrCast<GridBase>(floatGrid); /// @endcode template<typename T, typename U> inline SharedPtr<T> StaticPtrCast(const SharedPtr<U>& ptr) { return std::static_pointer_cast<T, U>(ptr); } //////////////////////////////////////// /// @brief Integer wrapper, required to distinguish PointIndexGrid and /// PointDataGrid from Int32Grid and Int64Grid /// @note @c Kind is a dummy parameter used to create distinct types. template<typename IntType_, Index Kind> struct PointIndex { static_assert(std::is_integral<IntType_>::value, "PointIndex requires an integer value type"); using IntType = IntType_; PointIndex(IntType i = IntType(0)): mIndex(i) {} /// Explicit type conversion constructor template<typename T> explicit PointIndex(T i): mIndex(static_cast<IntType>(i)) {} operator IntType() const { return mIndex; } /// Needed to support the <tt>(zeroVal<PointIndex>() + val)</tt> idiom. template<typename T> PointIndex operator+(T x) { return PointIndex(mIndex + IntType(x)); } private: IntType mIndex; }; using PointIndex32 = PointIndex<Index32, 0>; using PointIndex64 = PointIndex<Index64, 0>; using PointDataIndex32 = PointIndex<Index32, 1>; using PointDataIndex64 = PointIndex<Index64, 1>; //////////////////////////////////////// /// @brief Helper metafunction used to determine if the first template /// parameter is a specialization of the class template given in the second /// template parameter template <typename T, template <typename...> class Template> struct IsSpecializationOf: public std::false_type {}; template <typename... Args, template <typename...> class Template> struct IsSpecializationOf<Template<Args...>, Template>: public std::true_type {}; //////////////////////////////////////// template<typename T, bool = IsSpecializationOf<T, math::Vec2>::value || IsSpecializationOf<T, math::Vec3>::value || IsSpecializationOf<T, math::Vec4>::value> struct VecTraits { static const bool IsVec = true; static const int Size = T::size; using ElementType = typename T::ValueType; }; template<typename T> struct VecTraits<T, false> { static const bool IsVec = false; static const int Size = 1; using ElementType = T; }; template<typename T, bool = IsSpecializationOf<T, math::Quat>::value> struct QuatTraits { static const bool IsQuat = true; static const int Size = T::size; using ElementType = typename T::ValueType; }; template<typename T> struct QuatTraits<T, false> { static const bool IsQuat = false; static const int Size = 1; using ElementType = T; }; template<typename T, bool = IsSpecializationOf<T, math::Mat3>::value || IsSpecializationOf<T, math::Mat4>::value> struct MatTraits { static const bool IsMat = true; static const int Size = T::size; using ElementType = typename T::ValueType; }; template<typename T> struct MatTraits<T, false> { static const bool IsMat = false; static const int Size = 1; using ElementType = T; }; template<typename T, bool = VecTraits<T>::IsVec || QuatTraits<T>::IsQuat || MatTraits<T>::IsMat> struct ValueTraits { static const bool IsVec = VecTraits<T>::IsVec; static const bool IsQuat = QuatTraits<T>::IsQuat; static const bool IsMat = MatTraits<T>::IsMat; static const bool IsScalar = false; static const int Size = T::size; static const int Elements = IsMat ? Size*Size : Size; using ElementType = typename T::ValueType; }; template<typename T> struct ValueTraits<T, false> { static const bool IsVec = false; static const bool IsQuat = false; static const bool IsMat = false; static const bool IsScalar = true; static const int Size = 1; static const int Elements = 1; using ElementType = T; }; //////////////////////////////////////// /// @brief CanConvertType<FromType, ToType>::value is @c true if a value /// of type @a ToType can be constructed from a value of type @a FromType. template<typename FromType, typename ToType> struct CanConvertType { enum { value = std::is_constructible<ToType, FromType>::value }; }; // Specializations for vector types, which can be constructed from values // of their own ValueTypes (or values that can be converted to their ValueTypes), // but only explicitly template<typename T> struct CanConvertType<T, math::Vec2<T> > { enum { value = true }; }; template<typename T> struct CanConvertType<T, math::Vec3<T> > { enum { value = true }; }; template<typename T> struct CanConvertType<T, math::Vec4<T> > { enum { value = true }; }; template<typename T> struct CanConvertType<math::Vec2<T>, math::Vec2<T> > { enum {value = true}; }; template<typename T> struct CanConvertType<math::Vec3<T>, math::Vec3<T> > { enum {value = true}; }; template<typename T> struct CanConvertType<math::Vec4<T>, math::Vec4<T> > { enum {value = true}; }; template<typename T0, typename T1> struct CanConvertType<T0, math::Vec2<T1> > { enum { value = CanConvertType<T0, T1>::value }; }; template<typename T0, typename T1> struct CanConvertType<T0, math::Vec3<T1> > { enum { value = CanConvertType<T0, T1>::value }; }; template<typename T0, typename T1> struct CanConvertType<T0, math::Vec4<T1> > { enum { value = CanConvertType<T0, T1>::value }; }; template<> struct CanConvertType<PointIndex32, PointDataIndex32> { enum {value = true}; }; template<> struct CanConvertType<PointDataIndex32, PointIndex32> { enum {value = true}; }; template<typename T> struct CanConvertType<T, ValueMask> { enum {value = CanConvertType<T, bool>::value}; }; template<typename T> struct CanConvertType<ValueMask, T> { enum {value = CanConvertType<bool, T>::value}; }; //////////////////////////////////////// /// @brief CopyConstness<T1, T2>::Type is either <tt>const T2</tt> /// or @c T2 with no @c const qualifier, depending on whether @c T1 is @c const. /// @details For example, /// - CopyConstness<int, int>::Type is @c int /// - CopyConstness<int, const int>::Type is @c int /// - CopyConstness<const int, int>::Type is <tt>const int</tt> /// - CopyConstness<const int, const int>::Type is <tt>const int</tt> template<typename FromType, typename ToType> struct CopyConstness { using Type = typename std::remove_const<ToType>::type; }; /// @cond OPENVDB_TYPES_INTERNAL template<typename FromType, typename ToType> struct CopyConstness<const FromType, ToType> { using Type = const ToType; }; /// @endcond //////////////////////////////////////// // Add new items to the *end* of this list, and update NUM_GRID_CLASSES. enum GridClass { GRID_UNKNOWN = 0, GRID_LEVEL_SET, GRID_FOG_VOLUME, GRID_STAGGERED }; enum { NUM_GRID_CLASSES = GRID_STAGGERED + 1 }; static const Real LEVEL_SET_HALF_WIDTH = 3; /// The type of a vector determines how transforms are applied to it: /// <dl> /// <dt><b>Invariant</b> /// <dd>Does not transform (e.g., tuple, uvw, color) /// /// <dt><b>Covariant</b> /// <dd>Apply inverse-transpose transformation: @e w = 0, ignores translation /// (e.g., gradient/normal) /// /// <dt><b>Covariant Normalize</b> /// <dd>Apply inverse-transpose transformation: @e w = 0, ignores translation, /// vectors are renormalized (e.g., unit normal) /// /// <dt><b>Contravariant Relative</b> /// <dd>Apply "regular" transformation: @e w = 0, ignores translation /// (e.g., displacement, velocity, acceleration) /// /// <dt><b>Contravariant Absolute</b> /// <dd>Apply "regular" transformation: @e w = 1, vector translates (e.g., position) /// </dl> enum VecType { VEC_INVARIANT = 0, VEC_COVARIANT, VEC_COVARIANT_NORMALIZE, VEC_CONTRAVARIANT_RELATIVE, VEC_CONTRAVARIANT_ABSOLUTE }; enum { NUM_VEC_TYPES = VEC_CONTRAVARIANT_ABSOLUTE + 1 }; /// Specify how grids should be merged during certain (typically multithreaded) operations. /// <dl> /// <dt><b>MERGE_ACTIVE_STATES</b> /// <dd>The output grid is active wherever any of the input grids is active. /// /// <dt><b>MERGE_NODES</b> /// <dd>The output grid's tree has a node wherever any of the input grids' trees /// has a node, regardless of any active states. /// /// <dt><b>MERGE_ACTIVE_STATES_AND_NODES</b> /// <dd>The output grid is active wherever any of the input grids is active, /// and its tree has a node wherever any of the input grids' trees has a node. /// </dl> enum MergePolicy { MERGE_ACTIVE_STATES = 0, MERGE_NODES, MERGE_ACTIVE_STATES_AND_NODES }; //////////////////////////////////////// template<typename T> const char* typeNameAsString() { return typeid(T).name(); } template<> inline const char* typeNameAsString<bool>() { return "bool"; } template<> inline const char* typeNameAsString<ValueMask>() { return "mask"; } template<> inline const char* typeNameAsString<half>() { return "half"; } template<> inline const char* typeNameAsString<float>() { return "float"; } template<> inline const char* typeNameAsString<double>() { return "double"; } template<> inline const char* typeNameAsString<int8_t>() { return "int8"; } template<> inline const char* typeNameAsString<uint8_t>() { return "uint8"; } template<> inline const char* typeNameAsString<int16_t>() { return "int16"; } template<> inline const char* typeNameAsString<uint16_t>() { return "uint16"; } template<> inline const char* typeNameAsString<int32_t>() { return "int32"; } template<> inline const char* typeNameAsString<uint32_t>() { return "uint32"; } template<> inline const char* typeNameAsString<int64_t>() { return "int64"; } template<> inline const char* typeNameAsString<Vec2i>() { return "vec2i"; } template<> inline const char* typeNameAsString<Vec2s>() { return "vec2s"; } template<> inline const char* typeNameAsString<Vec2d>() { return "vec2d"; } template<> inline const char* typeNameAsString<Vec3U8>() { return "vec3u8"; } template<> inline const char* typeNameAsString<Vec3U16>() { return "vec3u16"; } template<> inline const char* typeNameAsString<Vec3i>() { return "vec3i"; } template<> inline const char* typeNameAsString<Vec3f>() { return "vec3s"; } template<> inline const char* typeNameAsString<Vec3d>() { return "vec3d"; } template<> inline const char* typeNameAsString<Vec4i>() { return "vec4i"; } template<> inline const char* typeNameAsString<Vec4f>() { return "vec4s"; } template<> inline const char* typeNameAsString<Vec4d>() { return "vec4d"; } template<> inline const char* typeNameAsString<std::string>() { return "string"; } template<> inline const char* typeNameAsString<Mat3s>() { return "mat3s"; } template<> inline const char* typeNameAsString<Mat3d>() { return "mat3d"; } template<> inline const char* typeNameAsString<Mat4s>() { return "mat4s"; } template<> inline const char* typeNameAsString<Mat4d>() { return "mat4d"; } template<> inline const char* typeNameAsString<math::Quats>() { return "quats"; } template<> inline const char* typeNameAsString<math::Quatd>() { return "quatd"; } template<> inline const char* typeNameAsString<PointIndex32>() { return "ptidx32"; } template<> inline const char* typeNameAsString<PointIndex64>() { return "ptidx64"; } template<> inline const char* typeNameAsString<PointDataIndex32>() { return "ptdataidx32"; } template<> inline const char* typeNameAsString<PointDataIndex64>() { return "ptdataidx64"; } //////////////////////////////////////// /// @brief This struct collects both input and output arguments to "grid combiner" functors /// used with the tree::TypedGrid::combineExtended() and combine2Extended() methods. /// AValueType and BValueType are the value types of the two grids being combined. /// /// @see openvdb/tree/Tree.h for usage information. /// /// Setter methods return references to this object, to facilitate the following usage: /// @code /// CombineArgs<float> args; /// myCombineOp(args.setARef(aVal).setBRef(bVal).setAIsActive(true).setBIsActive(false)); /// @endcode template<typename AValueType, typename BValueType = AValueType> class CombineArgs { public: using AValueT = AValueType; using BValueT = BValueType; CombineArgs() : mAValPtr(nullptr) , mBValPtr(nullptr) , mResultValPtr(&mResultVal) , mAIsActive(false) , mBIsActive(false) , mResultIsActive(false) { } /// Use this constructor when the result value is stored externally. CombineArgs(const AValueType& a, const BValueType& b, AValueType& result, bool aOn = false, bool bOn = false) : mAValPtr(&a) , mBValPtr(&b) , mResultValPtr(&result) , mAIsActive(aOn) , mBIsActive(bOn) { this->updateResultActive(); } /// Use this constructor when the result value should be stored in this struct. CombineArgs(const AValueType& a, const BValueType& b, bool aOn = false, bool bOn = false) : mAValPtr(&a) , mBValPtr(&b) , mResultValPtr(&mResultVal) , mAIsActive(aOn) , mBIsActive(bOn) { this->updateResultActive(); } /// Get the A input value. const AValueType& a() const { return *mAValPtr; } /// Get the B input value. const BValueType& b() const { return *mBValPtr; } //@{ /// Get the output value. const AValueType& result() const { return *mResultValPtr; } AValueType& result() { return *mResultValPtr; } //@} /// Set the output value. CombineArgs& setResult(const AValueType& val) { *mResultValPtr = val; return *this; } /// Redirect the A value to a new external source. CombineArgs& setARef(const AValueType& a) { mAValPtr = &a; return *this; } /// Redirect the B value to a new external source. CombineArgs& setBRef(const BValueType& b) { mBValPtr = &b; return *this; } /// Redirect the result value to a new external destination. CombineArgs& setResultRef(AValueType& val) { mResultValPtr = &val; return *this; } /// @return true if the A value is active bool aIsActive() const { return mAIsActive; } /// @return true if the B value is active bool bIsActive() const { return mBIsActive; } /// @return true if the output value is active bool resultIsActive() const { return mResultIsActive; } /// Set the active state of the A value. CombineArgs& setAIsActive(bool b) { mAIsActive = b; updateResultActive(); return *this; } /// Set the active state of the B value. CombineArgs& setBIsActive(bool b) { mBIsActive = b; updateResultActive(); return *this; } /// Set the active state of the output value. CombineArgs& setResultIsActive(bool b) { mResultIsActive = b; return *this; } protected: /// By default, the result value is active if either of the input values is active, /// but this behavior can be overridden by calling setResultIsActive(). void updateResultActive() { mResultIsActive = mAIsActive || mBIsActive; } const AValueType* mAValPtr; // pointer to input value from A grid const BValueType* mBValPtr; // pointer to input value from B grid AValueType mResultVal; // computed output value (unused if stored externally) AValueType* mResultValPtr; // pointer to either mResultVal or an external value bool mAIsActive, mBIsActive; // active states of A and B values bool mResultIsActive; // computed active state (default: A active || B active) }; /// This struct adapts a "grid combiner" functor to swap the A and B grid values /// (e.g., so that if the original functor computes a + 2 * b, the adapted functor /// will compute b + 2 * a). template<typename ValueType, typename CombineOp> struct SwappedCombineOp { SwappedCombineOp(CombineOp& _op): op(_op) {} void operator()(CombineArgs<ValueType>& args) { CombineArgs<ValueType> swappedArgs(args.b(), args.a(), args.result(), args.bIsActive(), args.aIsActive()); op(swappedArgs); } CombineOp& op; }; //////////////////////////////////////// /// @brief Tag dispatch class that distinguishes shallow copy constructors /// from deep copy constructors class ShallowCopy {}; /// @brief Tag dispatch class that distinguishes topology copy constructors /// from deep copy constructors class TopologyCopy {}; /// @brief Tag dispatch class that distinguishes constructors that deep copy class DeepCopy {}; /// @brief Tag dispatch class that distinguishes constructors that steal class Steal {}; /// @brief Tag dispatch class that distinguishes constructors during file input class PartialCreate {}; } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_TYPES_HAS_BEEN_INCLUDED
20,462
C
35.87027
99
0.669925