python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
---|---|---|
# Check that we can inject commands at the beginning of a ShTest.
# RUN: %{lit} -j 1 %{inputs}/shtest-inject/test-empty.txt --show-all | FileCheck --check-prefix=CHECK-TEST1 %s
#
# CHECK-TEST1: Script:
# CHECK-TEST1: --
# CHECK-TEST1: echo "THIS WAS"
# CHECK-TEST1: echo "INJECTED"
# CHECK-TEST1: --
#
# CHECK-TEST1: THIS WAS
# CHECK-TEST1: INJECTED
#
# CHECK-TEST1: Passed: 1
# RUN: %{lit} -j 1 %{inputs}/shtest-inject/test-one.txt --show-all | FileCheck --check-prefix=CHECK-TEST2 %s
#
# CHECK-TEST2: Script:
# CHECK-TEST2: --
# CHECK-TEST2: echo "THIS WAS"
# CHECK-TEST2: echo "INJECTED"
# CHECK-TEST2: echo "IN THE FILE"
# CHECK-TEST2: --
#
# CHECK-TEST2: THIS WAS
# CHECK-TEST2: INJECTED
# CHECK-TEST2: IN THE FILE
#
# CHECK-TEST2: Passed: 1
# RUN: %{lit} -j 1 %{inputs}/shtest-inject/test-many.txt --show-all | FileCheck --check-prefix=CHECK-TEST3 %s
#
# CHECK-TEST3: Script:
# CHECK-TEST3: --
# CHECK-TEST3: echo "THIS WAS"
# CHECK-TEST3: echo "INJECTED"
# CHECK-TEST3: echo "IN THE FILE"
# CHECK-TEST3: echo "IF IT WORKS"
# CHECK-TEST3: echo "AS EXPECTED"
# CHECK-TEST3: --
#
# CHECK-TEST3: THIS WAS
# CHECK-TEST3: INJECTED
# CHECK-TEST3: IN THE FILE
# CHECK-TEST3: IF IT WORKS
# CHECK-TEST3: AS EXPECTED
#
# CHECK-TEST3: Passed: 1
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/shtest-inject.py |
# Test features related to formats which support reporting additional test data.
# RUN: %{lit} -j 1 -v %{inputs}/test-data > %t.out
# RUN: FileCheck < %t.out %s
# CHECK: -- Testing:
# CHECK: PASS: test-data :: metrics.ini
# CHECK-NEXT: *** TEST 'test-data :: metrics.ini' RESULTS ***
# CHECK-NEXT: value0: 1
# CHECK-NEXT: value1: 2.3456
# CHECK-NEXT: ***
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/test-data.py |
# UNSUPPORTED: system-windows
# Test overall lit timeout (--max-time).
#
# RUN: %{lit} %{inputs}/max-time --max-time=5 2>&1 | FileCheck %s
# CHECK: reached timeout, skipping remaining tests
# CHECK: Skipped: 1
# CHECK: Passed : 1
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/max-time.py |
# RUN: %{python} %s %{inputs}/unparsed-requirements
import sys
from lit.Test import Result, Test, TestSuite
from lit.TestRunner import parseIntegratedTestScript
from lit.TestingConfig import TestingConfig
config = TestingConfig(None, "config", [".txt"], None, [], [], False, sys.argv[1], sys.argv[1], [], [], True)
suite = TestSuite("suite", sys.argv[1], sys.argv[1], config)
test = Test(suite, ["test.py"], config)
test.requires = ["meow"]
test.unsupported = ["alpha"]
test.xfails = ["foo"]
parseIntegratedTestScript(test)
error_count = 0
if test.requires != ["meow", "woof", "quack"]:
error_count += 1
if test.unsupported != ["alpha", "beta", "gamma"]:
error_count += 1
if test.xfails != ["foo", "bar", "baz"]:
error_count += 1
exit(error_count)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/unparsed-requirements.py |
# Check the various features of the GoogleTest format.
#
# RUN: not %{lit} -j 1 -v %{inputs}/googletest-upstream-format > %t.out
# RUN: FileCheck < %t.out %s
#
# END.
# CHECK: -- Testing:
# CHECK: PASS: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/FirstTest.subTestA
# CHECK: FAIL: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/FirstTest.subTestB
# CHECK-NEXT: *** TEST 'googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/FirstTest.subTestB' FAILED ***
# CHECK-NEXT: Running main() from gtest_main.cc
# CHECK-NEXT: I am subTest B, I FAIL
# CHECK-NEXT: And I have two lines of output
# CHECK: ***
# CHECK: PASS: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/ParameterizedTest/0.subTest
# CHECK: PASS: googletest-upstream-format :: {{[Dd]ummy[Ss]ub[Dd]ir}}/OneTest.py/ParameterizedTest/1.subTest
# CHECK: Failed Tests (1)
# CHECK: Passed: 3
# CHECK: Failed: 1
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/googletest-upstream-format.py |
# Check the lit adaption to run under unittest.
#
# RUN: %{python} %s %{inputs}/unittest-adaptor 2> %t.err
# RUN: FileCheck < %t.err %s
#
# CHECK-DAG: unittest-adaptor :: test-two.txt ... FAIL
# CHECK-DAG: unittest-adaptor :: test-one.txt ... ok
import sys
import unittest
import lit.LitTestCase
input_path = sys.argv[1]
unittest_suite = lit.LitTestCase.load_test_suite([input_path])
runner = unittest.TextTestRunner(verbosity=2)
runner.run(unittest_suite)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/unittest-adaptor.py |
# Check the various features of the ShTest format.
#
# RUN: not %{lit} -j 1 -v %{inputs}/shtest-output-printing > %t.out
# RUN: FileCheck --input-file %t.out %s
#
# END.
# CHECK: -- Testing:
# CHECK: FAIL: shtest-output-printing :: basic.txt
# CHECK-NEXT: *** TEST 'shtest-output-printing :: basic.txt' FAILED ***
# CHECK-NEXT: Script:
# CHECK-NEXT: --
# CHECK: --
# CHECK-NEXT: Exit Code: 1
#
# CHECK: Command Output
# CHECK-NEXT: --
# CHECK-NEXT: $ ":" "RUN: at line 1"
# CHECK-NEXT: $ "true"
# CHECK-NEXT: $ ":" "RUN: at line 2"
# CHECK-NEXT: $ "echo" "hi"
# CHECK-NEXT: # command output:
# CHECK-NEXT: hi
#
# CHECK: $ ":" "RUN: at line 3"
# CHECK-NEXT: $ "not" "not" "wc" "missing-file"
# CHECK-NEXT: # redirected output from '{{.*(/|\\\\)}}basic.txt.tmp.out':
# CHECK-NEXT: {{cannot open missing-file|missing-file.* No such file or directory}}
# CHECK: note: command had no output on stdout or stderr
# CHECK-NEXT: error: command failed with exit status: 1
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/shtest-output-printing.py |
# Test the --show-<result-code> {pass,unsupported,xfail,...} options.
#
# RUN: not %{lit} %{inputs}/show-result-codes | FileCheck %s --check-prefix=NONE
# RUN: not %{lit} %{inputs}/show-result-codes --show-unsupported | FileCheck %s --check-prefix=ONE
# RUN: not %{lit} %{inputs}/show-result-codes --show-pass --show-xfail | FileCheck %s --check-prefix=MULTIPLE
# Failing tests are always shown
# NONE-NOT: Unsupported Tests (1)
# NONE-NOT: Passed Tests (1)
# NONE-NOT: Expectedly Failed Tests (1)
# NONE: Failed Tests (1)
# ONE: Unsupported Tests (1)
# ONE-NOT: Passed Tests (1)
# ONE-NOT: Expectedly Failed Tests (1)
# ONE: Failed Tests (1)
# MULTIPLE-NOT: Unsupported Tests (1)
# MULTIPLE: Passed Tests (1)
# MULTIPLE: Expectedly Failed Tests (1)
# MULTIPLE: Failed Tests (1)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/show-result-codes.py |
# UNSUPPORTED: system-windows
# Test lit.main.add_result_category() extension API.
# RUN: not %{lit} -j 1 %{inputs}/custom-result-category | FileCheck %s
# CHECK: CUSTOM_PASS: custom-result-category :: test1.txt
# CHECK: CUSTOM_FAILURE: custom-result-category :: test2.txt
# CHECK-NOT: My Passed Tests (1)
# CHECK-NOT: custom-result-category :: test1.txt
# CHECK: My Failed Tests (1)
# CHECK: custom-result-category :: test2.txt
# CHECK: My Passed: 1
# CHECK: My Failed: 1
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/custom-result-category.py |
# Check the env command
#
# RUN: not %{lit} -j 1 -a -v %{inputs}/shtest-env \
# RUN: | FileCheck -match-full-lines %s
#
# END.
# Make sure env commands are included in printed commands.
# CHECK: -- Testing: 16 tests{{.*}}
# CHECK: FAIL: shtest-env :: env-args-last-is-assign.txt ({{[^)]*}})
# CHECK: $ "env" "FOO=1"
# CHECK: Error: 'env' requires a subcommand
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-args-last-is-u-arg.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO"
# CHECK: Error: 'env' requires a subcommand
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-args-last-is-u.txt ({{[^)]*}})
# CHECK: $ "env" "-u"
# CHECK: Error: 'env' requires a subcommand
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-args-nested-none.txt ({{[^)]*}})
# CHECK: $ "env" "env" "env"
# CHECK: Error: 'env' requires a subcommand
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-args-none.txt ({{[^)]*}})
# CHECK: $ "env"
# CHECK: Error: 'env' requires a subcommand
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-calls-cd.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO" "BAR=3" "cd" "foobar"
# CHECK: Error: 'env' cannot call 'cd'
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-calls-colon.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO" "BAR=3" ":"
# CHECK: Error: 'env' cannot call ':'
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-calls-echo.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO" "BAR=3" "echo" "hello" "world"
# CHECK: Error: 'env' cannot call 'echo'
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: PASS: shtest-env :: env-calls-env.txt ({{[^)]*}})
# CHECK: $ "env" "env" "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "FOO=2" "env" "BAR=1" "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "-u" "FOO" "env" "-u" "BAR" "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "-u" "FOO" "BAR=1" "env" "-u" "BAR" "FOO=2" "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "-u" "FOO" "BAR=1" "env" "-u" "BAR" "FOO=2" "env" "BAZ=3" "{{[^"]*}}" "print_environment.py"
# CHECK-NOT: ${{.*}}print_environment.py
# CHECK: FAIL: shtest-env :: env-calls-export.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO" "BAR=3" "export" "BAZ=3"
# CHECK: Error: 'env' cannot call 'export'
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-calls-mkdir.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO" "BAR=3" "mkdir" "foobar"
# CHECK: Error: 'env' cannot call 'mkdir'
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-calls-not-builtin.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO" "BAR=3" "not" "rm" "{{.*}}.no-such-file"
# CHECK: Error: 'env' cannot call 'rm'
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: FAIL: shtest-env :: env-calls-rm.txt ({{[^)]*}})
# CHECK: $ "env" "-u" "FOO" "BAR=3" "rm" "foobar"
# CHECK: Error: 'env' cannot call 'rm'
# CHECK: error: command failed with exit status: {{.*}}
# CHECK: PASS: shtest-env :: env-u.txt ({{[^)]*}})
# CHECK: $ "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "-u" "FOO" "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "-u" "FOO" "-u" "BAR" "{{[^"]*}}" "print_environment.py"
# CHECK-NOT: ${{.*}}print_environment.py
# CHECK: PASS: shtest-env :: env.txt ({{[^)]*}})
# CHECK: $ "env" "A_FOO=999" "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "A_FOO=1" "B_BAR=2" "C_OOF=3" "{{[^"]*}}" "print_environment.py"
# CHECK-NOT: ${{.*}}print_environment.py
# CHECK: PASS: shtest-env :: mixed.txt ({{[^)]*}})
# CHECK: $ "env" "A_FOO=999" "-u" "FOO" "{{[^"]*}}" "print_environment.py"
# CHECK: $ "env" "A_FOO=1" "-u" "FOO" "B_BAR=2" "-u" "BAR" "C_OOF=3" "{{[^"]*}}" "print_environment.py"
# CHECK-NOT: ${{.*}}print_environment.py
# CHECK: Passed: 4
# CHECK: Failed: 12
# CHECK-NOT: {{.}}
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/shtest-env.py |
# REQUIRES: shell
# Check xunit output
# RUN: rm -rf %t.xunit.xml
# RUN: not %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/xunit-output
# If xmllint is installed verify that the generated xml is well-formed
# RUN: sh -c 'if command -v xmllint 2>/dev/null; then xmllint --noout %t.xunit.xml; fi'
# RUN: FileCheck < %t.xunit.xml %s
# CHECK: <?xml version="1.0" encoding="UTF-8"?>
# CHECK-NEXT: <testsuites time="{{[0-9.]+}}">
# CHECK-NEXT: <testsuite name="test-data" tests="5" failures="1" skipped="3">
# CHECK-NEXT: <testcase classname="test-data.test-data" name="bad&name.ini" time="{{[0-1]\.[0-9]+}}">
# CHECK-NEXT: <failure><![CDATA[& < > ]]]]><![CDATA[> &"]]></failure>
# CHECK-NEXT: </testcase>
# CHECK-NEXT: <testcase classname="test-data.test-data" name="excluded.ini" time="{{[0-1]\.[0-9]+}}">
# CHECK-NEXT: <skipped message="Test not selected (--filter, --max-tests)"/>
# CHECK-NEXT: </testcase>
# CHECK-NEXT: <testcase classname="test-data.test-data" name="missing_feature.ini" time="{{[0-1]\.[0-9]+}}">
# CHECK-NEXT: <skipped message="Missing required feature(s): dummy_feature"/>
# CHECK-NEXT: </testcase>
# CHECK-NEXT: <testcase classname="test-data.test-data" name="pass.ini" time="{{[0-1]\.[0-9]+}}"/>
# CHECK-NEXT: <testcase classname="test-data.test-data" name="unsupported.ini" time="{{[0-1]\.[0-9]+}}">
# CHECK-NEXT: <skipped message="Unsupported configuration"/>
# CHECK-NEXT: </testcase>
# CHECK-NEXT: </testsuite>
# CHECK-NEXT: </testsuites>
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/xunit-output.py |
# Basic sanity check for `--help` and `--version` options.
#
# RUN: %{lit} --help | FileCheck %s --check-prefix=HELP
# RUN: %{lit} --version 2>&1 | FileCheck %s --check-prefix=VERSION
#
# HELP: usage: lit [-h]
# VERSION: lit {{[0-9]+\.[0-9]+\.[0-9]+[a-zA-Z0-9]*}}
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/usage.py |
# Check that --show-used-features works correctly.
#
# RUN: %{lit} %{inputs}/show-used-features --show-used-features | FileCheck %s
# CHECK: my-require-feature-1 my-require-feature-2 my-require-feature-3
# CHECK: my-unsupported-feature-1 my-unsupported-feature-2 my-unsupported-feature-3
# CHECK: my-xfail-feature-1 my-xfail-feature-2 my-xfail-feature-3
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/show-used-features.py |
# Check that the config.recursiveExpansionLimit is picked up and will cause
# lit substitutions to be expanded recursively.
# RUN: %{lit} -j 1 %{inputs}/shtest-recursive-substitution/substitutes-within-limit --show-all | FileCheck --check-prefix=CHECK-TEST1 %s
# CHECK-TEST1: PASS: substitutes-within-limit :: test.py
# CHECK-TEST1: $ "echo" "STOP"
# RUN: not %{lit} -j 1 %{inputs}/shtest-recursive-substitution/does-not-substitute-within-limit --show-all | FileCheck --check-prefix=CHECK-TEST2 %s
# CHECK-TEST2: UNRESOLVED: does-not-substitute-within-limit :: test.py
# CHECK-TEST2: ValueError: Recursive substitution of
# RUN: %{lit} -j 1 %{inputs}/shtest-recursive-substitution/does-not-substitute-no-limit --show-all | FileCheck --check-prefix=CHECK-TEST3 %s
# CHECK-TEST3: PASS: does-not-substitute-no-limit :: test.py
# CHECK-TEST3: $ "echo" "%rec4"
# RUN: not %{lit} -j 1 %{inputs}/shtest-recursive-substitution/not-an-integer --show-all 2>&1 | FileCheck --check-prefix=CHECK-TEST4 %s
# CHECK-TEST4: recursiveExpansionLimit must be either None or an integer
# RUN: not %{lit} -j 1 %{inputs}/shtest-recursive-substitution/negative-integer --show-all 2>&1 | FileCheck --check-prefix=CHECK-TEST5 %s
# CHECK-TEST5: recursiveExpansionLimit must be a non-negative integer
# RUN: %{lit} -j 1 %{inputs}/shtest-recursive-substitution/set-to-none --show-all | FileCheck --check-prefix=CHECK-TEST6 %s
# CHECK-TEST6: PASS: set-to-none :: test.py
# RUN: %{lit} -j 1 %{inputs}/shtest-recursive-substitution/escaping --show-all | FileCheck --check-prefix=CHECK-TEST7 %s
# CHECK-TEST7: PASS: escaping :: test.py
# CHECK-TEST7: $ "echo" "%s" "%s" "%%s"
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/shtest-recursive-substitution.py |
# RUN: %{python} %s
import unittest
from lit.ShUtil import Command, Pipeline, Seq, ShLexer, ShParser
class TestShLexer(unittest.TestCase):
def lex(self, str, *args, **kwargs):
return list(ShLexer(str, *args, **kwargs).lex())
def test_basic(self):
self.assertEqual(self.lex('a|b>c&d<e;f'),
['a', ('|',), 'b', ('>',), 'c', ('&',), 'd',
('<',), 'e', (';',), 'f'])
def test_redirection_tokens(self):
self.assertEqual(self.lex('a2>c'),
['a2', ('>',), 'c'])
self.assertEqual(self.lex('a 2>c'),
['a', ('>',2), 'c'])
def test_quoting(self):
self.assertEqual(self.lex(""" 'a' """),
['a'])
self.assertEqual(self.lex(""" "hello\\"world" """),
['hello"world'])
self.assertEqual(self.lex(""" "hello\\'world" """),
["hello\\'world"])
self.assertEqual(self.lex(""" "hello\\\\world" """),
["hello\\world"])
self.assertEqual(self.lex(""" he"llo wo"rld """),
["hello world"])
self.assertEqual(self.lex(""" a\\ b a\\\\b """),
["a b", "a\\b"])
self.assertEqual(self.lex(""" "" "" """),
["", ""])
self.assertEqual(self.lex(""" a\\ b """, win32Escapes = True),
['a\\', 'b'])
class TestShParse(unittest.TestCase):
def parse(self, str):
return ShParser(str).parse()
def test_basic(self):
self.assertEqual(self.parse('echo hello'),
Pipeline([Command(['echo', 'hello'], [])], False))
self.assertEqual(self.parse('echo ""'),
Pipeline([Command(['echo', ''], [])], False))
self.assertEqual(self.parse("""echo -DFOO='a'"""),
Pipeline([Command(['echo', '-DFOO=a'], [])], False))
self.assertEqual(self.parse('echo -DFOO="a"'),
Pipeline([Command(['echo', '-DFOO=a'], [])], False))
def test_redirection(self):
self.assertEqual(self.parse('echo hello > c'),
Pipeline([Command(['echo', 'hello'],
[((('>'),), 'c')])], False))
self.assertEqual(self.parse('echo hello > c >> d'),
Pipeline([Command(['echo', 'hello'], [(('>',), 'c'),
(('>>',), 'd')])], False))
self.assertEqual(self.parse('a 2>&1'),
Pipeline([Command(['a'], [(('>&',2), '1')])], False))
def test_pipeline(self):
self.assertEqual(self.parse('a | b'),
Pipeline([Command(['a'], []),
Command(['b'], [])],
False))
self.assertEqual(self.parse('a | b | c'),
Pipeline([Command(['a'], []),
Command(['b'], []),
Command(['c'], [])],
False))
def test_list(self):
self.assertEqual(self.parse('a ; b'),
Seq(Pipeline([Command(['a'], [])], False),
';',
Pipeline([Command(['b'], [])], False)))
self.assertEqual(self.parse('a & b'),
Seq(Pipeline([Command(['a'], [])], False),
'&',
Pipeline([Command(['b'], [])], False)))
self.assertEqual(self.parse('a && b'),
Seq(Pipeline([Command(['a'], [])], False),
'&&',
Pipeline([Command(['b'], [])], False)))
self.assertEqual(self.parse('a || b'),
Seq(Pipeline([Command(['a'], [])], False),
'||',
Pipeline([Command(['b'], [])], False)))
self.assertEqual(self.parse('a && b || c'),
Seq(Seq(Pipeline([Command(['a'], [])], False),
'&&',
Pipeline([Command(['b'], [])], False)),
'||',
Pipeline([Command(['c'], [])], False)))
self.assertEqual(self.parse('a; b'),
Seq(Pipeline([Command(['a'], [])], False),
';',
Pipeline([Command(['b'], [])], False)))
if __name__ == '__main__':
unittest.main()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/unit/ShUtil.py |
# RUN: %{python} %s
#
# END.
import os.path
import platform
import unittest
import lit.discovery
import lit.LitConfig
import lit.Test as Test
from lit.TestRunner import ParserKind, IntegratedTestKeywordParser, \
parseIntegratedTestScript
class TestIntegratedTestKeywordParser(unittest.TestCase):
inputTestCase = None
@staticmethod
def load_keyword_parser_lit_tests():
"""
Create and load the LIT test suite and test objects used by
TestIntegratedTestKeywordParser
"""
# Create the global config object.
lit_config = lit.LitConfig.LitConfig(progname='lit',
path=[],
quiet=False,
useValgrind=False,
valgrindLeakCheck=False,
valgrindArgs=[],
noExecute=False,
debug=False,
isWindows=(
platform.system() == 'Windows'),
params={})
TestIntegratedTestKeywordParser.litConfig = lit_config
# Perform test discovery.
test_path = os.path.dirname(os.path.dirname(__file__))
inputs = [os.path.join(test_path, 'Inputs/testrunner-custom-parsers/')]
assert os.path.isdir(inputs[0])
tests = lit.discovery.find_tests_for_inputs(lit_config, inputs, False)
assert len(tests) == 1 and "there should only be one test"
TestIntegratedTestKeywordParser.inputTestCase = tests[0]
@staticmethod
def make_parsers():
def custom_parse(line_number, line, output):
if output is None:
output = []
output += [part for part in line.split(' ') if part.strip()]
return output
return [
IntegratedTestKeywordParser("MY_TAG.", ParserKind.TAG),
IntegratedTestKeywordParser("MY_DNE_TAG.", ParserKind.TAG),
IntegratedTestKeywordParser("MY_LIST:", ParserKind.LIST),
IntegratedTestKeywordParser("MY_BOOL:", ParserKind.BOOLEAN_EXPR),
IntegratedTestKeywordParser("MY_INT:", ParserKind.INTEGER),
IntegratedTestKeywordParser("MY_RUN:", ParserKind.COMMAND),
IntegratedTestKeywordParser("MY_CUSTOM:", ParserKind.CUSTOM,
custom_parse),
]
@staticmethod
def get_parser(parser_list, keyword):
for p in parser_list:
if p.keyword == keyword:
return p
assert False and "parser not found"
@staticmethod
def parse_test(parser_list, allow_result=False):
script = parseIntegratedTestScript(
TestIntegratedTestKeywordParser.inputTestCase,
additional_parsers=parser_list, require_script=False)
if isinstance(script, lit.Test.Result):
assert allow_result
else:
assert isinstance(script, list)
assert len(script) == 0
return script
def test_tags(self):
parsers = self.make_parsers()
self.parse_test(parsers)
tag_parser = self.get_parser(parsers, 'MY_TAG.')
dne_tag_parser = self.get_parser(parsers, 'MY_DNE_TAG.')
self.assertTrue(tag_parser.getValue())
self.assertFalse(dne_tag_parser.getValue())
def test_lists(self):
parsers = self.make_parsers()
self.parse_test(parsers)
list_parser = self.get_parser(parsers, 'MY_LIST:')
self.assertEqual(list_parser.getValue(),
['one', 'two', 'three', 'four'])
def test_commands(self):
parsers = self.make_parsers()
self.parse_test(parsers)
cmd_parser = self.get_parser(parsers, 'MY_RUN:')
value = cmd_parser.getValue()
self.assertEqual(len(value), 2) # there are only two run lines
self.assertEqual(value[0].strip(), "%dbg(MY_RUN: at line 4) baz")
self.assertEqual(value[1].strip(), "%dbg(MY_RUN: at line 7) foo bar")
def test_boolean(self):
parsers = self.make_parsers()
self.parse_test(parsers)
bool_parser = self.get_parser(parsers, 'MY_BOOL:')
value = bool_parser.getValue()
self.assertEqual(len(value), 2) # there are only two run lines
self.assertEqual(value[0].strip(), "a && (b)")
self.assertEqual(value[1].strip(), "d")
def test_integer(self):
parsers = self.make_parsers()
self.parse_test(parsers)
int_parser = self.get_parser(parsers, 'MY_INT:')
value = int_parser.getValue()
self.assertEqual(len(value), 2) # there are only two MY_INT: lines
self.assertEqual(type(value[0]), int)
self.assertEqual(value[0], 4)
self.assertEqual(type(value[1]), int)
self.assertEqual(value[1], 6)
def test_bad_parser_type(self):
parsers = self.make_parsers() + ["BAD_PARSER_TYPE"]
script = self.parse_test(parsers, allow_result=True)
self.assertTrue(isinstance(script, lit.Test.Result))
self.assertEqual(script.code, lit.Test.UNRESOLVED)
self.assertEqual('Additional parser must be an instance of '
'IntegratedTestKeywordParser',
script.output)
def test_duplicate_keyword(self):
parsers = self.make_parsers() + \
[IntegratedTestKeywordParser("KEY:", ParserKind.BOOLEAN_EXPR),
IntegratedTestKeywordParser("KEY:", ParserKind.BOOLEAN_EXPR)]
script = self.parse_test(parsers, allow_result=True)
self.assertTrue(isinstance(script, lit.Test.Result))
self.assertEqual(script.code, lit.Test.UNRESOLVED)
self.assertEqual("Parser for keyword 'KEY:' already exists",
script.output)
def test_boolean_unterminated(self):
parsers = self.make_parsers() + \
[IntegratedTestKeywordParser("MY_BOOL_UNTERMINATED:", ParserKind.BOOLEAN_EXPR)]
script = self.parse_test(parsers, allow_result=True)
self.assertTrue(isinstance(script, lit.Test.Result))
self.assertEqual(script.code, lit.Test.UNRESOLVED)
self.assertEqual("Test has unterminated 'MY_BOOL_UNTERMINATED:' lines "
"(with '\\')",
script.output)
def test_custom(self):
parsers = self.make_parsers()
self.parse_test(parsers)
custom_parser = self.get_parser(parsers, 'MY_CUSTOM:')
value = custom_parser.getValue()
self.assertEqual(value, ['a', 'b', 'c'])
def test_bad_keywords(self):
def custom_parse(line_number, line, output):
return output
try:
IntegratedTestKeywordParser("TAG_NO_SUFFIX", ParserKind.TAG),
self.fail("TAG_NO_SUFFIX failed to raise an exception")
except ValueError as e:
pass
except BaseException as e:
self.fail("TAG_NO_SUFFIX raised the wrong exception: %r" % e)
try:
IntegratedTestKeywordParser("TAG_WITH_COLON:", ParserKind.TAG),
self.fail("TAG_WITH_COLON: failed to raise an exception")
except ValueError as e:
pass
except BaseException as e:
self.fail("TAG_WITH_COLON: raised the wrong exception: %r" % e)
try:
IntegratedTestKeywordParser("LIST_WITH_DOT.", ParserKind.LIST),
self.fail("LIST_WITH_DOT. failed to raise an exception")
except ValueError as e:
pass
except BaseException as e:
self.fail("LIST_WITH_DOT. raised the wrong exception: %r" % e)
try:
IntegratedTestKeywordParser("CUSTOM_NO_SUFFIX",
ParserKind.CUSTOM, custom_parse),
self.fail("CUSTOM_NO_SUFFIX failed to raise an exception")
except ValueError as e:
pass
except BaseException as e:
self.fail("CUSTOM_NO_SUFFIX raised the wrong exception: %r" % e)
# Both '.' and ':' are allowed for CUSTOM keywords.
try:
IntegratedTestKeywordParser("CUSTOM_WITH_DOT.",
ParserKind.CUSTOM, custom_parse),
except BaseException as e:
self.fail("CUSTOM_WITH_DOT. raised an exception: %r" % e)
try:
IntegratedTestKeywordParser("CUSTOM_WITH_COLON:",
ParserKind.CUSTOM, custom_parse),
except BaseException as e:
self.fail("CUSTOM_WITH_COLON: raised an exception: %r" % e)
try:
IntegratedTestKeywordParser("CUSTOM_NO_PARSER:",
ParserKind.CUSTOM),
self.fail("CUSTOM_NO_PARSER: failed to raise an exception")
except ValueError as e:
pass
except BaseException as e:
self.fail("CUSTOM_NO_PARSER: raised the wrong exception: %r" % e)
class TestApplySubtitutions(unittest.TestCase):
def test_simple(self):
script = ["echo %bar"]
substitutions = [("%bar", "hello")]
result = lit.TestRunner.applySubstitutions(script, substitutions)
self.assertEqual(result, ["echo hello"])
def test_multiple_substitutions(self):
script = ["echo %bar %baz"]
substitutions = [("%bar", "hello"),
("%baz", "world"),
("%useless", "shouldnt expand")]
result = lit.TestRunner.applySubstitutions(script, substitutions)
self.assertEqual(result, ["echo hello world"])
def test_multiple_script_lines(self):
script = ["%cxx %compile_flags -c -o %t.o",
"%cxx %link_flags %t.o -o %t.exe"]
substitutions = [("%cxx", "clang++"),
("%compile_flags", "-std=c++11 -O3"),
("%link_flags", "-lc++")]
result = lit.TestRunner.applySubstitutions(script, substitutions)
self.assertEqual(result, ["clang++ -std=c++11 -O3 -c -o %t.o",
"clang++ -lc++ %t.o -o %t.exe"])
def test_recursive_substitution_real(self):
script = ["%build %s"]
substitutions = [("%cxx", "clang++"),
("%compile_flags", "-std=c++11 -O3"),
("%link_flags", "-lc++"),
("%build", "%cxx %compile_flags %link_flags %s -o %t.exe")]
result = lit.TestRunner.applySubstitutions(script, substitutions, recursion_limit=3)
self.assertEqual(result, ["clang++ -std=c++11 -O3 -lc++ %s -o %t.exe %s"])
def test_recursive_substitution_limit(self):
script = ["%rec5"]
# Make sure the substitutions are not in an order where the global
# substitution would appear to be recursive just because they are
# processed in the right order.
substitutions = [("%rec1", "STOP"), ("%rec2", "%rec1"),
("%rec3", "%rec2"), ("%rec4", "%rec3"), ("%rec5", "%rec4")]
for limit in [5, 6, 7]:
result = lit.TestRunner.applySubstitutions(script, substitutions, recursion_limit=limit)
self.assertEqual(result, ["STOP"])
def test_recursive_substitution_limit_exceeded(self):
script = ["%rec5"]
substitutions = [("%rec1", "STOP"), ("%rec2", "%rec1"),
("%rec3", "%rec2"), ("%rec4", "%rec3"), ("%rec5", "%rec4")]
for limit in [0, 1, 2, 3, 4]:
try:
lit.TestRunner.applySubstitutions(script, substitutions, recursion_limit=limit)
self.fail("applySubstitutions should have raised an exception")
except ValueError:
pass
def test_recursive_substitution_invalid_value(self):
script = ["%rec5"]
substitutions = [("%rec1", "STOP"), ("%rec2", "%rec1"),
("%rec3", "%rec2"), ("%rec4", "%rec3"), ("%rec5", "%rec4")]
for limit in [-1, -2, -3, "foo"]:
try:
lit.TestRunner.applySubstitutions(script, substitutions, recursion_limit=limit)
self.fail("applySubstitutions should have raised an exception")
except AssertionError:
pass
if __name__ == '__main__':
TestIntegratedTestKeywordParser.load_keyword_parser_lit_tests()
unittest.main(verbosity=2)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/unit/TestRunner.py |
#!/usr/bin/env python
import print_environment
print_environment.execute()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-not/pass.py |
from __future__ import print_function
import os
def execute():
for name in ['FOO', 'BAR']:
print(name, '=', os.environ.get(name, '[undefined]'))
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-not/print_environment.py |
#!/usr/bin/env python
import print_environment
import sys
print_environment.execute()
sys.exit(1)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-not/fail.py |
# ALLOW_RETRIES: not-an-integer
# RUN: true
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/allow-retries/not-a-valid-integer.py |
# ALLOW_RETRIES: 3
# RUN: false
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/allow-retries/does-not-succeed-within-limit.py |
# ALLOW_RETRIES: 5
# RUN: "%python" "%s" "%counter"
import sys
import os
counter_file = sys.argv[1]
# The first time the test is run, initialize the counter to 1.
if not os.path.exists(counter_file):
with open(counter_file, 'w') as counter:
counter.write("1")
# Succeed if this is the fourth time we're being run.
with open(counter_file, 'r') as counter:
num = int(counter.read())
if num == 4:
sys.exit(0)
# Otherwise, increment the counter and fail
with open(counter_file, 'w') as counter:
counter.write(str(num + 1))
sys.exit(1)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/allow-retries/succeeds-within-limit.py |
# ALLOW_RETRIES: 3
# ALLOW_RETRIES: 5
# RUN: true
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/allow-retries/more-than-one-allow-retries-lines.py |
# RUN: true
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-recursive-substitution/negative-integer/test.py |
# RUN: echo %rec2 %%s %%%%s
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-recursive-substitution/escaping/test.py |
# RUN: echo %rec5
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-recursive-substitution/substitutes-within-limit/test.py |
# RUN: true
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-recursive-substitution/set-to-none/test.py |
# RUN: true
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-recursive-substitution/not-an-integer/test.py |
# RUN: echo %rec5
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-recursive-substitution/does-not-substitute-no-limit/test.py |
# RUN: echo %rec5
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-recursive-substitution/does-not-substitute-within-limit/test.py |
import lit.util
import os
import sys
main_config = sys.argv[1]
main_config = os.path.realpath(main_config)
main_config = os.path.normcase(main_config)
config_map = {main_config : sys.argv[2]}
builtin_parameters = {'config_map' : config_map}
if __name__=='__main__':
from lit.main import main
main_config_dir = os.path.dirname(main_config)
sys.argv = [sys.argv[0]] + sys.argv[3:] + [main_config_dir]
main(builtin_parameters)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/config-map-discovery/driver.py |
import os
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
import lit.formats
import lit.Test
class DummyFormat(lit.formats.FileBasedTest):
def execute(self, test, lit_config):
# In this dummy format, expect that each test file is actually just a
# .ini format dump of the results to report.
source_path = test.getSourcePath()
cfg = ConfigParser.ConfigParser()
cfg.read(source_path)
# Create the basic test result.
result_code = cfg.get('global', 'result_code')
result_output = cfg.get('global', 'result_output')
result = lit.Test.Result(getattr(lit.Test, result_code),
result_output)
# Load additional metrics.
for key,value_str in cfg.items('results'):
value = eval(value_str)
if isinstance(value, int):
metric = lit.Test.IntMetricValue(value)
elif isinstance(value, float):
metric = lit.Test.RealMetricValue(value)
else:
raise RuntimeError("unsupported result type")
result.addMetric(key, metric)
return result
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/test-data/dummy_format.py |
#!/usr/bin/env python
import sys
if len(sys.argv) != 2:
raise ValueError("unexpected number of args")
if sys.argv[1] == "--gtest_list_tests":
print("""\
Running main() from gtest_main.cc
FirstTest.
subTestA
subTestB
ParameterizedTest/0.
subTest
ParameterizedTest/1.
subTest""")
sys.exit(0)
elif not sys.argv[1].startswith("--gtest_filter="):
raise ValueError("unexpected argument: %r" % (sys.argv[1]))
test_name = sys.argv[1].split('=',1)[1]
print('Running main() from gtest_main.cc')
if test_name == 'FirstTest.subTestA':
print('I am subTest A, I PASS')
print('[ PASSED ] 1 test.')
sys.exit(0)
elif test_name == 'FirstTest.subTestB':
print('I am subTest B, I FAIL')
print('And I have two lines of output')
sys.exit(1)
elif test_name in ('ParameterizedTest/0.subTest',
'ParameterizedTest/1.subTest'):
print('I am a parameterized test, I also PASS')
print('[ PASSED ] 1 test.')
sys.exit(0)
else:
raise SystemExit("error: invalid test name: %r" % (test_name,))
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/googletest-upstream-format/DummySubDir/OneTest.py |
# RUN: "%python" "%s" "%counter"
import sys
import os
counter_file = sys.argv[1]
# The first time the test is run, initialize the counter to 1.
if not os.path.exists(counter_file):
with open(counter_file, 'w') as counter:
counter.write("1")
# Succeed if this is the fourth time we're being run.
with open(counter_file, 'r') as counter:
num = int(counter.read())
if num == 4:
sys.exit(0)
# Otherwise, increment the counter and fail
with open(counter_file, 'w') as counter:
counter.write(str(num + 1))
sys.exit(1)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/test_retry_attempts/test.py |
import os
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
import lit.formats
import lit.Test
class DummyFormat(lit.formats.FileBasedTest):
def execute(self, test, lit_config):
# In this dummy format, expect that each test file is actually just a
# .ini format dump of the results to report.
source_path = test.getSourcePath()
cfg = ConfigParser.ConfigParser()
cfg.read(source_path)
# Create the basic test result.
result_code = cfg.get('global', 'result_code')
result_output = cfg.get('global', 'result_output')
result = lit.Test.Result(getattr(lit.Test, result_code),
result_output)
# Load additional metrics.
for key,value_str in cfg.items('results'):
value = eval(value_str)
if isinstance(value, int):
metric = lit.Test.IntMetricValue(value)
elif isinstance(value, float):
metric = lit.Test.RealMetricValue(value)
else:
raise RuntimeError("unsupported result type")
result.addMetric(key, metric)
# Create micro test results
for key,micro_name in cfg.items('micro-tests'):
micro_result = lit.Test.Result(getattr(lit.Test, result_code, ''))
# Load micro test additional metrics
for key,value_str in cfg.items('micro-results'):
value = eval(value_str)
if isinstance(value, int):
metric = lit.Test.IntMetricValue(value)
elif isinstance(value, float):
metric = lit.Test.RealMetricValue(value)
else:
raise RuntimeError("unsupported result type")
micro_result.addMetric(key, metric)
result.addMicroResult(micro_name, micro_result)
return result
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/test-data-micro/dummy_format.py |
# RUN: true
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/discovery/subdir/test-three.py |
# 'sleep 60' in Python because Windows does not have a native sleep command.
#
# RUN: %{python} %s
import time
time.sleep(60)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/max-time/slow.py |
import os
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
import lit.formats
import lit.Test
class DummyFormat(lit.formats.FileBasedTest):
def execute(self, test, lit_config):
# In this dummy format, expect that each test file is actually just a
# .ini format dump of the results to report.
source_path = test.getSourcePath()
cfg = ConfigParser.ConfigParser()
cfg.read(source_path)
# Create the basic test result.
result_code = cfg.get('global', 'result_code')
result_output = cfg.get('global', 'result_output')
result = lit.Test.Result(getattr(lit.Test, result_code),
result_output)
if cfg.has_option('global', 'required_feature'):
required_feature = cfg.get('global', 'required_feature')
if required_feature:
test.requires.append(required_feature)
# Load additional metrics.
for key,value_str in cfg.items('results'):
value = eval(value_str)
if isinstance(value, int):
metric = lit.Test.IntMetricValue(value)
elif isinstance(value, float):
metric = lit.Test.RealMetricValue(value)
else:
raise RuntimeError("unsupported result type")
result.addMetric(key, metric)
return result
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/xunit-output/dummy_format.py |
import os
import sys
def execute(fileName):
sys.stderr.write("error: external '{}' command called unexpectedly\n"
.format(os.path.basename(fileName)));
sys.exit(1)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/fake-externals/fake_external.py |
# Load the discovery suite, but with a separate exec root.
import os
config.test_exec_root = os.path.dirname(__file__)
config.test_source_root = os.path.join(os.path.dirname(config.test_exec_root), "discovery")
lit_config.load_config(config, os.path.join(config.test_source_root, "lit.cfg"))
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/py-config-discovery/lit.site.cfg.py |
#!/usr/bin/env python
import sys
getattr(sys.stdout, "buffer", sys.stdout).write(b"a line with bad encoding: \xc2.")
sys.stdout.flush()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-format/external_shell/write-bad-encoding.py |
#!/usr/bin/env python
from __future__ import print_function
import sys
print("a line with \x1b[2;30;41mcontrol characters\x1b[0m.")
sys.exit(1)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-format/external_shell/write-control-chars.py |
#!/usr/bin/env python
from __future__ import print_function
import os
sorted_environment = sorted(os.environ.items())
for name,value in sorted_environment:
print(name,'=',value)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-env/print_environment.py |
#!/usr/bin/env python
import sys
sys.stdout.write("a line on stdout\n")
sys.stdout.flush()
sys.stderr.write("a line on stderr\n")
sys.stderr.flush()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-shell/write-to-stdout-and-stderr.py |
#!/usr/bin/env python
import sys
sys.stderr.write("a line on stderr\n")
sys.stderr.flush()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-shell/write-to-stderr.py |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
def check_path(argv):
if len(argv) < 3:
print("Wrong number of args")
return 1
type = argv[1]
paths = argv[2:]
exit_code = 0
if type == 'dir':
for idx, dir in enumerate(paths):
print(os.path.isdir(dir))
elif type == 'file':
for idx, file in enumerate(paths):
print(os.path.isfile(file))
else:
print("Unrecognised type {}".format(type))
exit_code = 1
return exit_code
if __name__ == '__main__':
sys.exit (check_path (sys.argv))
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-shell/check_path.py |
#!/usr/bin/env python
import argparse
import platform
parser = argparse.ArgumentParser()
parser.add_argument("--my_arg", "-a")
args = parser.parse_args()
answer = (platform.system() == "Windows" and
args.my_arg == "/dev/null" and "ERROR") or "OK"
print(answer)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-shell/check_args.py |
import lit
import lit.formats
CUSTOM_PASS = lit.Test.ResultCode('CUSTOM_PASS', 'My Passed', False)
CUSTOM_FAILURE = lit.Test.ResultCode('CUSTOM_FAILURE', 'My Failed', True)
class MyFormat(lit.formats.ShTest):
def execute(self, test, lit_config):
result = super(MyFormat, self).execute(test, lit_config)
if result.code.isFailure:
result.code = CUSTOM_FAILURE
else:
result.code = CUSTOM_PASS
return result
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/custom-result-category/format.py |
#!/usr/bin/env python
import sys
if len(sys.argv) != 2:
raise ValueError("unexpected number of args")
if sys.argv[1] == "--gtest_list_tests":
print("""\
FirstTest.
subTestA
subTestB
ParameterizedTest/0.
subTest
ParameterizedTest/1.
subTest""")
sys.exit(0)
elif not sys.argv[1].startswith("--gtest_filter="):
raise ValueError("unexpected argument: %r" % (sys.argv[1]))
test_name = sys.argv[1].split('=',1)[1]
if test_name == 'FirstTest.subTestA':
print('I am subTest A, I PASS')
print('[ PASSED ] 1 test.')
sys.exit(0)
elif test_name == 'FirstTest.subTestB':
print('I am subTest B, I FAIL')
print('And I have two lines of output')
sys.exit(1)
elif test_name in ('ParameterizedTest/0.subTest',
'ParameterizedTest/1.subTest'):
print('I am a parameterized test, I also PASS')
print('[ PASSED ] 1 test.')
sys.exit(0)
else:
raise SystemExit("error: invalid test name: %r" % (test_name,))
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/googletest-format/DummySubDir/OneTest.py |
# RUN: %{python} %s
while True:
pass
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-timeout/infinite_loop.py |
# RUN: %{python} %s
from __future__ import print_function
print("short program")
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/shtest-timeout/short.py |
#!/usr/bin/env python
import sys
import time
if len(sys.argv) != 2:
raise ValueError("unexpected number of args")
if sys.argv[1] == "--gtest_list_tests":
print("""\
T.
QuickSubTest
InfiniteLoopSubTest
""")
sys.exit(0)
elif not sys.argv[1].startswith("--gtest_filter="):
raise ValueError("unexpected argument: %r" % (sys.argv[1]))
test_name = sys.argv[1].split('=',1)[1]
if test_name == 'T.QuickSubTest':
print('I am QuickSubTest, I PASS')
print('[ PASSED ] 1 test.')
sys.exit(0)
elif test_name == 'T.InfiniteLoopSubTest':
print('I am InfiniteLoopSubTest, I will hang')
while True:
pass
else:
raise SystemExit("error: invalid test name: %r" % (test_name,))
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/googletest-timeout/DummySubDir/OneTest.py |
# REQUIRES: woof, quack
# UNSUPPORTED: beta, gamma
# XFAIL: bar, baz
# RUN:
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/unparsed-requirements/test.py |
#!/usr/bin/env python
raise SystemExit("We are not a valid gtest executable!")
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/tests/Inputs/googletest-discovery-failed/subdir/OneTest.py |
from lit import Test
class ManyTests(object):
def __init__(self, N=10000):
self.N = N
def getTestsInDirectory(self, testSuite, path_in_suite, litConfig, localConfig):
for i in range(self.N):
test_name = "test-%04d" % (i,)
yield Test.Test(testSuite, path_in_suite + (test_name,), localConfig)
def execute(self, test, litConfig):
# Do a "non-trivial" amount of Python work.
sum = 0
for i in range(10000):
sum += i
return Test.PASS, ""
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/lit/examples/many-tests/ManyTests.py |
#!/usr/bin/env python
"""Calls `gn` with the right --dotfile= and --root= arguments for LLVM."""
# GN normally expects a file called '.gn' at the root of the repository.
# Since LLVM's GN build isn't supported, putting that file at the root
# is deemed inappropriate, which requires passing --dotfile= and -root= to GN.
# Since that gets old fast, this script automatically passes these arguments.
import os
import subprocess
import sys
THIS_DIR = os.path.dirname(__file__)
ROOT_DIR = os.path.join(THIS_DIR, '..', '..', '..')
def get_platform():
import platform
if sys.platform == 'darwin':
return 'mac-amd64' if platform.machine() != 'arm64' else 'mac-arm64'
if platform.machine() not in ('AMD64', 'x86_64'):
return None
if sys.platform.startswith('linux'):
return 'linux-amd64'
if sys.platform == 'win32':
return 'windows-amd64'
def print_no_gn(mention_get):
print('gn binary not found in PATH')
if mention_get:
print('run llvm/utils/gn/get.py to download a binary and try again, or')
print('follow https://gn.googlesource.com/gn/#getting-started')
return 1
def main():
# Find real gn executable.
gn = 'gn'
if subprocess.call('gn --version', stdout=open(os.devnull, 'w'),
stderr=subprocess.STDOUT,
shell=True) != 0:
# Not on path. See if get.py downloaded a prebuilt binary and run that
# if it's there, or suggest to run get.py if it isn't.
platform = get_platform()
if not platform:
return print_no_gn(mention_get=False)
gn = os.path.join(os.path.dirname(__file__), 'bin', platform, 'gn')
if not os.path.exists(gn + ('.exe' if sys.platform == 'win32' else '')):
return print_no_gn(mention_get=True)
# Compute --dotfile= and --root= args to add.
extra_args = []
gn_main_arg = next((x for x in sys.argv[1:] if not x.startswith('-')), None)
if gn_main_arg != 'help': # `gn help` gets confused by the switches.
cwd = os.getcwd()
dotfile = os.path.relpath(os.path.join(THIS_DIR, '.gn'), cwd)
root = os.path.relpath(ROOT_DIR, cwd)
extra_args = [ '--dotfile=' + dotfile, '--root=' + root ]
# Run GN command with --dotfile= and --root= added.
cmd = [gn] + extra_args + sys.argv[1:]
sys.exit(subprocess.call(cmd))
if __name__ == '__main__':
main()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/gn.py |
#!/usr/bin/env python
"""Downloads a prebuilt gn binary to a place where gn.py can find it."""
from __future__ import print_function
import io
import os
try:
# In Python 3, we need the module urllib.reqest. In Python 2, this
# functionality was in the urllib2 module.
from urllib import request as urllib_request
except ImportError:
import urllib2 as urllib_request
import sys
import zipfile
def download_and_unpack(url, output_dir, gn):
"""Download an archive from url and extract gn from it into output_dir."""
print('downloading %s ...' % url, end='')
sys.stdout.flush()
data = urllib_request.urlopen(url).read()
print(' done')
zipfile.ZipFile(io.BytesIO(data)).extract(gn, path=output_dir)
def set_executable_bit(path):
mode = os.stat(path).st_mode
mode |= (mode & 0o444) >> 2 # Copy R bits to X.
os.chmod(path, mode) # No-op on Windows.
def get_platform():
import platform
if sys.platform == 'darwin':
return 'mac-amd64' if platform.machine() != 'arm64' else 'mac-arm64'
if platform.machine() not in ('AMD64', 'x86_64'):
return None
if sys.platform.startswith('linux'):
return 'linux-amd64'
if sys.platform == 'win32':
return 'windows-amd64'
def main():
platform = get_platform()
if not platform:
print('no prebuilt binary for', sys.platform)
print('build it yourself with:')
print(' rm -rf /tmp/gn &&')
print(' pushd /tmp && git clone https://gn.googlesource.com/gn &&')
print(' cd gn && build/gen.py && ninja -C out gn && popd &&')
print(' cp /tmp/gn/out/gn somewhere/on/PATH')
return 1
dirname = os.path.join(os.path.dirname(__file__), 'bin', platform)
if not os.path.exists(dirname):
os.makedirs(dirname)
url = 'https://chrome-infra-packages.appspot.com/dl/gn/gn/%s/+/latest'
gn = 'gn' + ('.exe' if sys.platform == 'win32' else '')
if platform == 'mac-arm64': # For https://openradar.appspot.com/FB8914243
try: os.remove(os.path.join(dirname, gn))
except OSError: pass
download_and_unpack(url % platform, dirname, gn)
set_executable_bit(os.path.join(dirname, gn))
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/get.py |
#!/usr/bin/env python
"""Runs tablegen."""
import subprocess
import sys
# Prefix with ./ to run built binary, not arbitrary stuff from PATH.
sys.exit(subprocess.call(['./' + sys.argv[1]] + sys.argv[2:]))
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/build/run_tablegen.py |
#!/usr/bin/env python
"""Symlinks, or on Windows copies, an existing file to a second location.
Overwrites the target location if it exists.
Updates the mtime on a stamp file when done."""
import argparse
import errno
import os
import sys
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--stamp', required=True,
help='name of a file whose mtime is updated on run')
parser.add_argument('source')
parser.add_argument('output')
args = parser.parse_args()
# FIXME: This should not check the host platform but the target platform
# (which needs to be passed in as an arg), for cross builds.
if sys.platform != 'win32':
try:
os.makedirs(os.path.dirname(args.output))
except OSError as e:
if e.errno != errno.EEXIST:
raise
try:
os.symlink(args.source, args.output)
except OSError as e:
if e.errno == errno.EEXIST:
os.remove(args.output)
os.symlink(args.source, args.output)
else:
raise
else:
import shutil
output = args.output + ".exe"
source = args.source + ".exe"
shutil.copyfile(os.path.join(os.path.dirname(output), source), output)
open(args.stamp, 'w') # Update mtime on stamp file.
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/build/symlink_or_copy.py |
#!/usr/bin/env python
r"""Emulates the bits of CMake's configure_file() function needed in LLVM.
The CMake build uses configure_file() for several things. This emulates that
function for the GN build. In the GN build, this runs at build time instead
of at generator time.
Takes a list of KEY=VALUE pairs (where VALUE can be empty).
The sequence `\` `n` in each VALUE is replaced by a newline character.
On each line, replaces '${KEY}' or '@KEY@' with VALUE.
Then, handles these special cases (note that FOO= sets the value of FOO to the
empty string, which is falsy, but FOO=0 sets it to '0' which is truthy):
1.) #cmakedefine01 FOO
Checks if key FOO is set to a truthy value, and depending on that prints
one of the following two lines:
#define FOO 1
#define FOO 0
2.) #cmakedefine FOO [...]
Checks if key FOO is set to a truthy value, and depending on that prints
one of the following two lines:
#define FOO [...]
/* #undef FOO */
Fails if any of the KEY=VALUE arguments aren't needed for processing the
input file, or if the input file references keys that weren't passed in.
"""
from __future__ import print_function
import argparse
import os
import re
import sys
def main():
parser = argparse.ArgumentParser(
epilog=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('input', help='input file')
parser.add_argument('values', nargs='*', help='several KEY=VALUE pairs')
parser.add_argument('-o', '--output', required=True,
help='output file')
args = parser.parse_args()
values = {}
for value in args.values:
key, val = value.split('=', 1)
if key in values:
print('duplicate key "%s" in args' % key, file=sys.stderr)
return 1
values[key] = val.replace('\\n', '\n')
unused_values = set(values.keys())
# Matches e.g. '${FOO}' or '@FOO@' and captures FOO in group 1 or 2.
var_re = re.compile(r'\$\{([^}]*)\}|@([^@]*)@')
with open(args.input) as f:
in_lines = f.readlines()
out_lines = []
for in_line in in_lines:
def repl(m):
key = m.group(1) or m.group(2)
unused_values.discard(key)
return values[key]
in_line = var_re.sub(repl, in_line)
if in_line.startswith('#cmakedefine01 '):
_, var = in_line.split()
if values[var] == '0':
print('error: "%s=0" used with #cmakedefine01 %s' % (var, var))
print(" '0' evaluates as truthy with #cmakedefine01")
print(' use "%s=" instead' % var)
return 1
in_line = '#define %s %d\n' % (var, 1 if values[var] else 0)
unused_values.discard(var)
elif in_line.startswith('#cmakedefine '):
_, var = in_line.split(None, 1)
try:
var, val = var.split(None, 1)
in_line = '#define %s %s' % (var, val) # val ends in \n.
except:
var = var.rstrip()
in_line = '#define %s\n' % var
if not values[var]:
in_line = '/* #undef %s */\n' % var
unused_values.discard(var)
out_lines.append(in_line)
if unused_values:
print('unused values args:', file=sys.stderr)
print(' ' + '\n '.join(unused_values), file=sys.stderr)
return 1
output = ''.join(out_lines)
leftovers = var_re.findall(output)
if leftovers:
print(
'unprocessed values:\n',
'\n'.join([x[0] or x[1] for x in leftovers]),
file=sys.stderr)
return 1
def read(filename):
with open(args.output) as f:
return f.read()
if not os.path.exists(args.output) or read(args.output) != output:
with open(args.output, 'w') as f:
f.write(output)
os.chmod(args.output, os.stat(args.input).st_mode & 0o777)
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/build/write_cmake_config.py |
#!/usr/bin/env python
"""Gets the current revision and writes it to VCSRevision.h."""
from __future__ import print_function
import argparse
import os
import subprocess
import sys
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
LLVM_DIR = os.path.dirname(os.path.dirname(os.path.dirname(THIS_DIR)))
def which(program):
# distutils.spawn.which() doesn't find .bat files,
# https://bugs.python.org/issue2200
for path in os.environ["PATH"].split(os.pathsep):
candidate = os.path.join(path, program)
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
return candidate
return None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--depfile',
help='if set, writes a depfile that causes this script '
'to re-run each time the current revision changes')
parser.add_argument('--write-git-rev', action='store_true',
help='if set, writes git revision, else writes #undef')
parser.add_argument('--name', action='append',
help='if set, writes a depfile that causes this script '
'to re-run each time the current revision changes')
parser.add_argument('vcs_header', help='path to the output file to write')
args = parser.parse_args()
vcsrevision_contents = ''
if args.write_git_rev:
git, use_shell = which('git'), False
if not git: git = which('git.exe')
if not git: git, use_shell = which('git.bat'), True
git_dir = subprocess.check_output(
[git, 'rev-parse', '--git-dir'],
cwd=LLVM_DIR, shell=use_shell).decode().strip()
if not os.path.isdir(git_dir):
print('.git dir not found at "%s"' % git_dir, file=sys.stderr)
return 1
rev = subprocess.check_output(
[git, 'rev-parse', '--short', 'HEAD'],
cwd=git_dir, shell=use_shell).decode().strip()
url = subprocess.check_output(
[git, 'remote', 'get-url', 'origin'],
cwd=git_dir, shell=use_shell).decode().strip()
for name in args.name:
vcsrevision_contents += '#define %s_REVISION "%s"\n' % (name, rev)
vcsrevision_contents += '#define %s_REPOSITORY "%s"\n' % (name, url)
else:
for name in args.name:
vcsrevision_contents += '#undef %s_REVISION\n' % name
vcsrevision_contents += '#undef %s_REPOSITORY\n' % name
# If the output already exists and is identical to what we'd write,
# return to not perturb the existing file's timestamp.
if os.path.exists(args.vcs_header) and \
open(args.vcs_header).read() == vcsrevision_contents:
return 0
# http://neugierig.org/software/blog/2014/11/binary-revisions.html
if args.depfile:
build_dir = os.getcwd()
with open(args.depfile, 'w') as depfile:
depfile.write('%s: %s\n' % (
args.vcs_header,
os.path.relpath(os.path.join(git_dir, 'logs', 'HEAD'),
build_dir)))
open(args.vcs_header, 'w').write(vcsrevision_contents)
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/build/write_vcsrevision.py |
#!/usr/bin/env python
"""Helps to keep BUILD.gn files in sync with the corresponding CMakeLists.txt.
For each BUILD.gn file in the tree, checks if the list of cpp files in
it is identical to the list of cpp files in the corresponding CMakeLists.txt
file, and prints the difference if not.
Also checks that each CMakeLists.txt file below unittests/ folders that define
binaries have corresponding BUILD.gn files.
If --write is passed, tries to write modified .gn files and adds one git
commit for each cmake commit this merges. If an error is reported, the state
of HEAD is unspecified; run `git reset --hard origin/master` if this happens.
"""
from __future__ import print_function
from collections import defaultdict
import os
import re
import subprocess
import sys
def patch_gn_file(gn_file, add, remove):
with open(gn_file) as f:
gn_contents = f.read()
if add:
srcs_tok = 'sources = ['
tokloc = gn_contents.find(srcs_tok)
while gn_contents.startswith('sources = []', tokloc):
tokloc = gn_contents.find(srcs_tok, tokloc + 1)
if tokloc == -1: raise ValueError(gn_file + ': No source list')
if gn_contents.find(srcs_tok, tokloc + 1) != -1:
raise ValueError(gn_file + ': Multiple source lists')
if gn_contents.find('# NOSORT', 0, tokloc) != -1:
raise ValueError(gn_file + ': Found # NOSORT, needs manual merge')
tokloc += len(srcs_tok)
for a in add:
gn_contents = (gn_contents[:tokloc] + ('"%s",' % a) +
gn_contents[tokloc:])
for r in remove:
gn_contents = gn_contents.replace('"%s",' % r, '')
with open(gn_file, 'w') as f:
f.write(gn_contents)
# Run `gn format`.
gn = os.path.join(os.path.dirname(__file__), '..', 'gn.py')
subprocess.check_call([sys.executable, gn, 'format', '-q', gn_file])
def sync_source_lists(write):
# Use shell=True on Windows in case git is a bat file.
def git(args): subprocess.check_call(['git'] + args, shell=os.name == 'nt')
def git_out(args):
return subprocess.check_output(['git'] + args, shell=os.name == 'nt')
gn_files = git_out(['ls-files', '*BUILD.gn']).splitlines()
# Matches e.g. | "foo.cpp",|, captures |foo| in group 1.
gn_cpp_re = re.compile(r'^\s*"([^$"]+\.(?:cpp|c|h|S))",$', re.MULTILINE)
# Matches e.g. | bar_sources = [ "foo.cpp" ]|, captures |foo| in group 1.
gn_cpp_re2 = re.compile(
r'^\s*(?:.*_)?sources \+?= \[ "([^$"]+\.(?:cpp|c|h|S))" ]$',
re.MULTILINE)
# Matches e.g. | foo.cpp|, captures |foo| in group 1.
cmake_cpp_re = re.compile(r'^\s*([A-Za-z_0-9./-]+\.(?:cpp|c|h|S))$',
re.MULTILINE)
changes_by_rev = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
def find_gitrev(touched_line, in_file):
# re.escape() escapes e.g. '-', which works in practice but has
# undefined behavior according to the POSIX extended regex spec.
posix_re_escape = lambda s: re.sub(r'([.[{()\\*+?|^$])', r'\\\1', s)
cmd = ['log', '--format=%h', '-1', '--pickaxe-regex',
r'-S\b%s\b' % posix_re_escape(touched_line), in_file]
return git_out(cmd).rstrip()
# Collect changes to gn files, grouped by revision.
for gn_file in gn_files:
# The CMakeLists.txt for llvm/utils/gn/secondary/foo/BUILD.gn is
# at foo/CMakeLists.txt.
strip_prefix = 'llvm/utils/gn/secondary/'
if not gn_file.startswith(strip_prefix):
continue
cmake_file = os.path.join(
os.path.dirname(gn_file[len(strip_prefix):]), 'CMakeLists.txt')
if not os.path.exists(cmake_file):
continue
def get_sources(source_re, text):
return set([m.group(1) for m in source_re.finditer(text)])
gn_cpp = get_sources(gn_cpp_re, open(gn_file).read())
gn_cpp |= get_sources(gn_cpp_re2, open(gn_file).read())
cmake_cpp = get_sources(cmake_cpp_re, open(cmake_file).read())
if gn_cpp == cmake_cpp:
continue
def by_rev(files, key):
for f in files:
rev = find_gitrev(f, cmake_file)
changes_by_rev[rev][gn_file][key].append(f)
by_rev(sorted(cmake_cpp - gn_cpp), 'add')
by_rev(sorted(gn_cpp - cmake_cpp), 'remove')
# Output necessary changes grouped by revision.
for rev in sorted(changes_by_rev):
print('[gn build] Port {0} -- https://reviews.llvm.org/rG{0}'
.format(rev))
for gn_file, data in sorted(changes_by_rev[rev].items()):
add = data.get('add', [])
remove = data.get('remove', [])
if write:
patch_gn_file(gn_file, add, remove)
git(['add', gn_file])
else:
print(' ' + gn_file)
if add:
print(' add:\n' + '\n'.join(' "%s",' % a for a in add))
if remove:
print(' remove:\n ' + '\n '.join(remove))
print()
if write:
git(['commit', '-m', '[gn build] Port %s' % rev])
else:
print()
return bool(changes_by_rev) and not write
def sync_unittests():
# Matches e.g. |add_llvm_unittest_with_input_files|.
unittest_re = re.compile(r'^add_\S+_unittest', re.MULTILINE)
checked = [ 'clang', 'clang-tools-extra', 'lld', 'llvm' ]
changed = False
for c in checked:
for root, _, _ in os.walk(os.path.join(c, 'unittests')):
cmake_file = os.path.join(root, 'CMakeLists.txt')
if not os.path.exists(cmake_file):
continue
if not unittest_re.search(open(cmake_file).read()):
continue # Skip CMake files that just add subdirectories.
gn_file = os.path.join('llvm/utils/gn/secondary', root, 'BUILD.gn')
if not os.path.exists(gn_file):
changed = True
print('missing GN file %s for unittest CMake file %s' %
(gn_file, cmake_file))
return changed
def main():
src = sync_source_lists(len(sys.argv) > 1 and sys.argv[1] == '--write')
tests = sync_unittests()
if src or tests:
sys.exit(1)
if __name__ == '__main__':
main()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/build/sync_source_lists_from_cmake.py |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import re
import sys
# FIXME: This should get outputs from gn.
OUTPUT = """struct AvailableComponent {
/// The name of the component.
const char *Name;
/// The name of the library for this component (or NULL).
const char *Library;
/// Whether the component is installed.
bool IsInstalled;
/// The list of libraries required when linking this component.
const char *RequiredLibraries[84];
} AvailableComponents[84] = {
{ "aggressiveinstcombine", "LLVMAggressiveInstCombine", true, {"analysis", "core", "support", "transformutils"} },
{ "all", nullptr, true, {"demangle", "support", "tablegen", "core", "fuzzmutate", "filecheck", "interfacestub", "irreader", "codegen", "selectiondag", "asmprinter", "mirparser", "globalisel", "binaryformat", "bitreader", "bitwriter", "bitstreamreader", "dwarflinker", "extensions", "frontendopenmp", "transformutils", "instrumentation", "aggressiveinstcombine", "instcombine", "scalaropts", "ipo", "vectorize", "hellonew", "objcarcopts", "coroutines", "cfguard", "linker", "analysis", "lto", "mc", "mcparser", "mcdisassembler", "mca", "object", "objectyaml", "option", "remarks", "debuginfodwarf", "debuginfogsym", "debuginfomsf", "debuginfocodeview", "debuginfopdb", "symbolize", "executionengine", "interpreter", "jitlink", "mcjit", "orcjit", "orcshared", "orctargetprocess", "runtimedyld", "target", "asmparser", "lineeditor", "profiledata", "coverage", "passes", "textapi", "dlltooldriver", "libdriver", "xray", "windowsmanifest"} },
{ "all-targets", nullptr, true, {} },
{ "analysis", "LLVMAnalysis", true, {"binaryformat", "core", "object", "profiledata", "support"} },
{ "asmparser", "LLVMAsmParser", true, {"binaryformat", "core", "support"} },
{ "asmprinter", "LLVMAsmPrinter", true, {"analysis", "binaryformat", "codegen", "core", "debuginfocodeview", "debuginfodwarf", "debuginfomsf", "mc", "mcparser", "remarks", "support", "target"} },
{ "binaryformat", "LLVMBinaryFormat", true, {"support"} },
{ "bitreader", "LLVMBitReader", true, {"bitstreamreader", "core", "support"} },
{ "bitstreamreader", "LLVMBitstreamReader", true, {"support"} },
{ "bitwriter", "LLVMBitWriter", true, {"analysis", "core", "mc", "object", "support"} },
{ "cfguard", "LLVMCFGuard", true, {"core", "support"} },
{ "codegen", "LLVMCodeGen", true, {"analysis", "bitreader", "bitwriter", "core", "mc", "profiledata", "scalaropts", "support", "target", "transformutils"} },
{ "core", "LLVMCore", true, {"binaryformat", "remarks", "support"} },
{ "coroutines", "LLVMCoroutines", true, {"analysis", "core", "ipo", "scalaropts", "support", "transformutils"} },
{ "coverage", "LLVMCoverage", true, {"core", "object", "profiledata", "support"} },
{ "debuginfocodeview", "LLVMDebugInfoCodeView", true, {"support", "debuginfomsf"} },
{ "debuginfodwarf", "LLVMDebugInfoDWARF", true, {"binaryformat", "object", "mc", "support"} },
{ "debuginfogsym", "LLVMDebugInfoGSYM", true, {"mc", "object", "support", "debuginfodwarf"} },
{ "debuginfomsf", "LLVMDebugInfoMSF", true, {"support"} },
{ "debuginfopdb", "LLVMDebugInfoPDB", true, {"binaryformat", "object", "support", "debuginfocodeview", "debuginfomsf"} },
{ "demangle", "LLVMDemangle", true, {} },
{ "dlltooldriver", "LLVMDlltoolDriver", true, {"object", "option", "support"} },
{ "dwarflinker", "LLVMDWARFLinker", true, {"debuginfodwarf", "asmprinter", "codegen", "mc", "object", "support"} },
{ "engine", nullptr, true, {"interpreter"} },
{ "executionengine", "LLVMExecutionEngine", true, {"core", "mc", "object", "runtimedyld", "support", "target"} },
{ "extensions", "LLVMExtensions", true, {"support"} },
{ "filecheck", "LLVMFileCheck", true, {} },
{ "frontendopenmp", "LLVMFrontendOpenMP", true, {"core", "support", "transformutils"} },
{ "fuzzmutate", "LLVMFuzzMutate", true, {"analysis", "bitreader", "bitwriter", "core", "scalaropts", "support", "target"} },
{ "globalisel", "LLVMGlobalISel", true, {"analysis", "codegen", "core", "mc", "selectiondag", "support", "target", "transformutils"} },
{ "hellonew", "LLVMHelloNew", true, {"core", "support"} },
{ "instcombine", "LLVMInstCombine", true, {"analysis", "core", "support", "transformutils"} },
{ "instrumentation", "LLVMInstrumentation", true, {"analysis", "core", "mc", "support", "transformutils", "profiledata"} },
{ "interfacestub", "LLVMInterfaceStub", true, {"object", "support"} },
{ "interpreter", "LLVMInterpreter", true, {"codegen", "core", "executionengine", "support"} },
{ "ipo", "LLVMipo", true, {"aggressiveinstcombine", "analysis", "bitreader", "bitwriter", "core", "frontendopenmp", "instcombine", "irreader", "linker", "object", "profiledata", "scalaropts", "support", "transformutils", "vectorize", "instrumentation"} },
{ "irreader", "LLVMIRReader", true, {"asmparser", "bitreader", "core", "support"} },
{ "jitlink", "LLVMJITLink", true, {"binaryformat", "object", "orctargetprocess", "support"} },
{ "libdriver", "LLVMLibDriver", true, {"binaryformat", "bitreader", "object", "option", "support", "binaryformat", "bitreader", "object", "option", "support"} },
{ "lineeditor", "LLVMLineEditor", true, {"support"} },
{ "linker", "LLVMLinker", true, {"core", "support", "transformutils"} },
{ "lto", "LLVMLTO", true, {"aggressiveinstcombine", "analysis", "binaryformat", "bitreader", "bitwriter", "codegen", "core", "extensions", "ipo", "instcombine", "linker", "mc", "objcarcopts", "object", "passes", "remarks", "scalaropts", "support", "target", "transformutils"} },
{ "mc", "LLVMMC", true, {"support", "binaryformat", "debuginfocodeview"} },
{ "mca", "LLVMMCA", true, {"mc", "support"} },
{ "mcdisassembler", "LLVMMCDisassembler", true, {"mc", "support"} },
{ "mcjit", "LLVMMCJIT", true, {"core", "executionengine", "object", "runtimedyld", "support", "target"} },
{ "mcparser", "LLVMMCParser", true, {"mc", "support"} },
{ "mirparser", "LLVMMIRParser", true, {"asmparser", "binaryformat", "codegen", "core", "mc", "support", "target"} },
{ "native", nullptr, true, {} },
{ "nativecodegen", nullptr, true, {} },
{ "objcarcopts", "LLVMObjCARCOpts", true, {"analysis", "core", "support", "transformutils"} },
{ "object", "LLVMObject", true, {"bitreader", "core", "mc", "binaryformat", "mcparser", "support", "textapi"} },
{ "objectyaml", "LLVMObjectYAML", true, {"binaryformat", "object", "support", "debuginfocodeview", "mc"} },
{ "option", "LLVMOption", true, {"support"} },
{ "orcjit", "LLVMOrcJIT", true, {"core", "executionengine", "jitlink", "object", "orcshared", "orctargetprocess", "mc", "passes", "runtimedyld", "support", "target", "transformutils"} },
{ "orcshared", "LLVMOrcShared", true, {"support"} },
{ "orctargetprocess", "LLVMOrcTargetProcess", true, {"orcshared", "support"} },
{ "passes", "LLVMPasses", true, {"aggressiveinstcombine", "analysis", "core", "coroutines", "hellonew", "ipo", "instcombine", "objcarcopts", "scalaropts", "support", "target", "transformutils", "vectorize", "instrumentation"} },
{ "profiledata", "LLVMProfileData", true, {"core", "support", "demangle"} },
{ "remarks", "LLVMRemarks", true, {"bitstreamreader", "support"} },
{ "runtimedyld", "LLVMRuntimeDyld", true, {"core", "mc", "object", "support"} },
{ "scalaropts", "LLVMScalarOpts", true, {"aggressiveinstcombine", "analysis", "core", "instcombine", "support", "transformutils"} },
{ "selectiondag", "LLVMSelectionDAG", true, {"analysis", "codegen", "core", "mc", "support", "target", "transformutils"} },
{ "support", "LLVMSupport", true, {"demangle"} },
{ "symbolize", "LLVMSymbolize", true, {"debuginfodwarf", "debuginfopdb", "object", "support", "demangle"} },
{ "tablegen", "LLVMTableGen", true, {"support"} },
{ "target", "LLVMTarget", true, {"analysis", "core", "mc", "support"} },
{ "textapi", "LLVMTextAPI", true, {"support", "binaryformat"} },
{ "transformutils", "LLVMTransformUtils", true, {"analysis", "core", "support"} },
{ "vectorize", "LLVMVectorize", true, {"analysis", "core", "support", "transformutils"} },
{ "windowsmanifest", "LLVMWindowsManifest", true, {"support"} },
{ "xray", "LLVMXRay", true, {"support", "object"} },
};
"""
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', required=True, help='output file')
args = parser.parse_args()
with open(args.output, 'w') as f:
f.write(OUTPUT)
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/build/write_library_dependencies.py |
#!/usr/bin/env python
#===----------------------------------------------------------------------===##
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===----------------------------------------------------------------------===##
"""
Generate a linker script that links libc++ to the proper ABI library.
An example script for c++abi would look like "INPUT(libc++.so.1 -lc++abi)".
"""
import argparse
import os
import sys
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", help="Path to libc++ library", required=True)
parser.add_argument("--output", help="Path to libc++ linker script",
required=True)
parser.add_argument("libraries", nargs="+",
help="List of libraries libc++ depends on")
args = parser.parse_args()
# Use the relative path for the libc++ library.
libcxx = os.path.relpath(args.input, os.path.dirname(args.output))
# Prepare the list of public libraries to link.
public_libs = ['-l%s' % l for l in args.libraries]
# Generate the linker script contents.
contents = "INPUT(%s)" % ' '.join([libcxx] + public_libs)
# Remove the existing libc++ symlink if it exists.
if os.path.islink(args.output):
os.unlink(args.output)
# Replace it with the linker script.
with open(args.output, 'w') as f:
f.write(contents + "\n")
return 0
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/secondary/libcxx/utils/gen_link_script.py |
#!/usr/bin/env python
r"""Writes ExtensionDepencencies.inc."""
from __future__ import print_function
import argparse
import os
import re
import sys
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-o', '--output', required=True,
help='output file')
args = parser.parse_args()
source = """\
#include <array>
struct ExtensionDescriptor {
const char* Name;
const char* const RequiredLibraries[1 + 1];
};
std::array<ExtensionDescriptor, 0> AvailableExtensions{};
"""
open(args.output, 'w').write(source)
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/secondary/llvm/tools/llvm-config/write_extension_dependencies.py |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('exts', nargs='*', help='list of supported extensions')
parser.add_argument('-o', '--output', required=True, help='output file')
args = parser.parse_args()
output = ''.join(['HANDLE_EXTENSION(%s)\n' % ext for ext in args.exts])
output += '#undef HANDLE_EXTENSION\n'
if not os.path.exists(args.output) or open(args.output).read() != output:
open(args.output, 'w').write(output)
if __name__ == '__main__':
sys.exit(main())
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/gn/secondary/llvm/include/llvm/Support/write_extension_def.py |
MDL-SDK-master | src/mdl/jit/llvm/dist/utils/UpdateTestChecks/__init__.py |
|
from __future__ import print_function
import re
import sys
from . import common
if sys.version_info[0] > 2:
class string:
expandtabs = str.expandtabs
else:
import string
# RegEx: this is where the magic happens.
##### Assembly parser
ASM_FUNCTION_X86_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*(@"?(?P=func)"?| -- Begin function (?P=func))\n(?:\s*\.?Lfunc_begin[^:\n]*:\n)?'
r'(?:\.L[^$]+\$local:\n)?' # drop .L<func>$local:
r'(?:[ \t]+.cfi_startproc\n|.seh_proc[^\n]+\n)?' # drop optional cfi
r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section|#+ -- End function)',
flags=(re.M | re.S))
ASM_FUNCTION_ARM_RE = re.compile(
r'^(?P<func>[0-9a-zA-Z_]+):\n' # f: (name of function)
r'\s+\.fnstart\n' # .fnstart
r'(?P<body>.*?)\n' # (body of the function)
r'.Lfunc_end[0-9]+:', # .Lfunc_end0: or # -- End function
flags=(re.M | re.S))
ASM_FUNCTION_AARCH64_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*\/\/[ \t]*@"?(?P=func)"?( (Function|Tail Call))?\n'
r'(?:[ \t]+.cfi_startproc\n)?' # drop optional cfi noise
r'(?P<body>.*?)\n'
# This list is incomplete
r'.Lfunc_end[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_AMDGPU_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*;+[ \t]*@"?(?P=func)"?\n[^:]*?'
r'(?P<body>.*?)\n' # (body of the function)
# This list is incomplete
r'^\s*(\.Lfunc_end[0-9]+:\n|\.section)',
flags=(re.M | re.S))
ASM_FUNCTION_HEXAGON_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*//[ \t]*@"?(?P=func)"?\n[^:]*?'
r'(?P<body>.*?)\n' # (body of the function)
# This list is incomplete
r'.Lfunc_end[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_MIPS_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@"?(?P=func)"?\n[^:]*?' # f: (name of func)
r'(?:^[ \t]+\.(frame|f?mask|set).*?\n)+' # Mips+LLVM standard asm prologue
r'(?P<body>.*?)\n' # (body of the function)
# Mips+LLVM standard asm epilogue
r'(?:(^[ \t]+\.set[^\n]*?\n)*^[ \t]+\.end.*?\n)'
r'(\$|\.L)func_end[0-9]+:\n', # $func_end0: (mips32 - O32) or
# .Lfunc_end0: (mips64 - NewABI)
flags=(re.M | re.S))
ASM_FUNCTION_MSP430_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*;+[ \t]*@"?(?P=func)"?\n[^:]*?'
r'(?P<body>.*?)\n'
r'(\$|\.L)func_end[0-9]+:\n', # $func_end0:
flags=(re.M | re.S))
ASM_FUNCTION_AVR_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*;+[ \t]*@"?(?P=func)"?\n[^:]*?'
r'(?P<body>.*?)\n'
r'.Lfunc_end[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_PPC_RE = re.compile(
r'#[ \-\t]*Begin function (?P<func>[^.:]+)\n'
r'.*?'
r'^[_.]?(?P=func):(?:[ \t]*#+[ \t]*@"?(?P=func)"?)?\n'
r'(?:^[^#]*\n)*'
r'(?P<body>.*?)\n'
# This list is incomplete
r'(?:^[ \t]*(?:\.(?:long|quad|v?byte)[ \t]+[^\n]+)\n)*'
r'(?:\.Lfunc_end|L\.\.(?P=func))[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_RISCV_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@"?(?P=func)"?\n'
r'(?:\s*\.?L(?P=func)\$local:\n)?' # optional .L<func>$local: due to -fno-semantic-interposition
r'(?:\s*\.?Lfunc_begin[^:\n]*:\n)?[^:]*?'
r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
r'.Lfunc_end[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_LANAI_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*!+[ \t]*@"?(?P=func)"?\n'
r'(?:[ \t]+.cfi_startproc\n)?' # drop optional cfi noise
r'(?P<body>.*?)\s*'
r'.Lfunc_end[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_SPARC_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*!+[ \t]*@"?(?P=func)"?\n'
r'(?P<body>.*?)\s*'
r'.Lfunc_end[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_SYSTEMZ_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@"?(?P=func)"?\n'
r'[ \t]+.cfi_startproc\n'
r'(?P<body>.*?)\n'
r'.Lfunc_end[0-9]+:\n',
flags=(re.M | re.S))
ASM_FUNCTION_AARCH64_DARWIN_RE = re.compile(
r'^_(?P<func>[^:]+):[ \t]*;[ \t]@"?(?P=func)"?\n'
r'([ \t]*.cfi_startproc\n[\s]*)?'
r'(?P<body>.*?)'
r'([ \t]*.cfi_endproc\n[\s]*)?'
r'^[ \t]*;[ \t]--[ \t]End[ \t]function',
flags=(re.M | re.S))
ASM_FUNCTION_ARM_DARWIN_RE = re.compile(
r'^[ \t]*\.globl[ \t]*_(?P<func>[^ \t])[ \t]*@[ \t]--[ \t]Begin[ \t]function[ \t]"?(?P=func)"?'
r'(?P<directives>.*?)'
r'^_(?P=func):\n[ \t]*'
r'(?P<body>.*?)'
r'^[ \t]*@[ \t]--[ \t]End[ \t]function',
flags=(re.M | re.S ))
ASM_FUNCTION_ARM_MACHO_RE = re.compile(
r'^_(?P<func>[^:]+):[ \t]*\n'
r'([ \t]*.cfi_startproc\n[ \t]*)?'
r'(?P<body>.*?)\n'
r'[ \t]*\.cfi_endproc\n',
flags=(re.M | re.S))
ASM_FUNCTION_ARM_IOS_RE = re.compile(
r'^_(?P<func>[^:]+):[ \t]*\n'
r'^Lfunc_begin(?P<id>[0-9][1-9]*):\n'
r'(?P<body>.*?)'
r'^Lfunc_end(?P=id):\n'
r'^[ \t]*@[ \t]--[ \t]End[ \t]function',
flags=(re.M | re.S))
ASM_FUNCTION_WASM32_RE = re.compile(
r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@"?(?P=func)"?\n'
r'(?P<body>.*?)\n'
r'^\s*(\.Lfunc_end[0-9]+:\n|end_function)',
flags=(re.M | re.S))
SCRUB_X86_SHUFFLES_RE = (
re.compile(
r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem)( \{%k\d+\}( \{z\})?)? = .*)$',
flags=re.M))
SCRUB_X86_SHUFFLES_NO_MEM_RE = (
re.compile(
r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem)( \{%k\d+\}( \{z\})?)? = (?!.*(?:mem)).*)$',
flags=re.M))
SCRUB_X86_SPILL_RELOAD_RE = (
re.compile(
r'-?\d+\(%([er])[sb]p\)(.*(?:Spill|Reload))$',
flags=re.M))
SCRUB_X86_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
SCRUB_X86_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
SCRUB_X86_LCP_RE = re.compile(r'\.LCPI[0-9]+_[0-9]+')
SCRUB_X86_RET_RE = re.compile(r'ret[l|q]')
def scrub_asm_x86(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Detect shuffle asm comments and hide the operands in favor of the comments.
if getattr(args, 'no_x86_scrub_mem_shuffle', True):
asm = SCRUB_X86_SHUFFLES_NO_MEM_RE.sub(r'\1 {{.*#+}} \2', asm)
else:
asm = SCRUB_X86_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
# Detect stack spills and reloads and hide their exact offset and whether
# they used the stack pointer or frame pointer.
asm = SCRUB_X86_SPILL_RELOAD_RE.sub(r'{{[-0-9]+}}(%\1{{[sb]}}p)\2', asm)
if getattr(args, 'x86_scrub_sp', True):
# Generically match the stack offset of a memory operand.
asm = SCRUB_X86_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
if getattr(args, 'x86_scrub_rip', False):
# Generically match a RIP-relative memory operand.
asm = SCRUB_X86_RIP_RE.sub(r'{{.*}}(%rip)', asm)
# Generically match a LCP symbol.
asm = SCRUB_X86_LCP_RE.sub(r'{{\.LCPI.*}}', asm)
if getattr(args, 'extra_scrub', False):
# Avoid generating different checks for 32- and 64-bit because of 'retl' vs 'retq'.
asm = SCRUB_X86_RET_RE.sub(r'ret{{[l|q]}}', asm)
# Strip kill operands inserted into the asm.
asm = common.SCRUB_KILL_COMMENT_RE.sub('', asm)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_amdgpu(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_arm_eabi(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip kill operands inserted into the asm.
asm = common.SCRUB_KILL_COMMENT_RE.sub('', asm)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_hexagon(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_powerpc(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip unimportant comments, but leave the token '#' in place.
asm = common.SCRUB_LOOP_COMMENT_RE.sub(r'#', asm)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
# Strip the tailing token '#', except the line only has token '#'.
asm = common.SCRUB_TAILING_COMMENT_TOKEN_RE.sub(r'', asm)
return asm
def scrub_asm_mips(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_msp430(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_avr(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_riscv(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_lanai(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_sparc(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_systemz(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def scrub_asm_wasm32(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
def get_triple_from_march(march):
triples = {
'amdgcn': 'amdgcn',
'r600': 'r600',
'mips': 'mips',
'sparc': 'sparc',
'hexagon': 'hexagon',
}
for prefix, triple in triples.items():
if march.startswith(prefix):
return triple
print("Cannot find a triple. Assume 'x86'", file=sys.stderr)
return 'x86'
def get_run_handler(triple):
target_handlers = {
'i686': (scrub_asm_x86, ASM_FUNCTION_X86_RE),
'x86': (scrub_asm_x86, ASM_FUNCTION_X86_RE),
'i386': (scrub_asm_x86, ASM_FUNCTION_X86_RE),
'aarch64': (scrub_asm_arm_eabi, ASM_FUNCTION_AARCH64_RE),
'aarch64-apple-darwin': (scrub_asm_arm_eabi, ASM_FUNCTION_AARCH64_DARWIN_RE),
'hexagon': (scrub_asm_hexagon, ASM_FUNCTION_HEXAGON_RE),
'r600': (scrub_asm_amdgpu, ASM_FUNCTION_AMDGPU_RE),
'amdgcn': (scrub_asm_amdgpu, ASM_FUNCTION_AMDGPU_RE),
'arm': (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_RE),
'arm64': (scrub_asm_arm_eabi, ASM_FUNCTION_AARCH64_RE),
'arm64e': (scrub_asm_arm_eabi, ASM_FUNCTION_AARCH64_DARWIN_RE),
'arm64-apple-ios': (scrub_asm_arm_eabi, ASM_FUNCTION_AARCH64_DARWIN_RE),
'armv7-apple-ios' : (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_IOS_RE),
'armv7-apple-darwin': (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_DARWIN_RE),
'thumb': (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_RE),
'thumb-macho': (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_MACHO_RE),
'thumbv5-macho': (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_MACHO_RE),
'thumbv7-apple-ios' : (scrub_asm_arm_eabi, ASM_FUNCTION_ARM_IOS_RE),
'mips': (scrub_asm_mips, ASM_FUNCTION_MIPS_RE),
'msp430': (scrub_asm_msp430, ASM_FUNCTION_MSP430_RE),
'avr': (scrub_asm_avr, ASM_FUNCTION_AVR_RE),
'ppc32': (scrub_asm_powerpc, ASM_FUNCTION_PPC_RE),
'powerpc': (scrub_asm_powerpc, ASM_FUNCTION_PPC_RE),
'riscv32': (scrub_asm_riscv, ASM_FUNCTION_RISCV_RE),
'riscv64': (scrub_asm_riscv, ASM_FUNCTION_RISCV_RE),
'lanai': (scrub_asm_lanai, ASM_FUNCTION_LANAI_RE),
'sparc': (scrub_asm_sparc, ASM_FUNCTION_SPARC_RE),
's390x': (scrub_asm_systemz, ASM_FUNCTION_SYSTEMZ_RE),
'wasm32': (scrub_asm_wasm32, ASM_FUNCTION_WASM32_RE),
}
handler = None
best_prefix = ''
for prefix, s in target_handlers.items():
if triple.startswith(prefix) and len(prefix) > len(best_prefix):
handler = s
best_prefix = prefix
if handler is None:
raise KeyError('Triple %r is not supported' % (triple))
return handler
##### Generator of assembly CHECK lines
def add_asm_checks(output_lines, comment_marker, prefix_list, func_dict, func_name):
# Label format is based on ASM string.
check_label_format = '{} %s-LABEL: %s%s:'.format(comment_marker)
global_vars_seen_dict = {}
common.add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, True, False, global_vars_seen_dict)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/UpdateTestChecks/asm.py |
from __future__ import print_function
import copy
import glob
import re
import subprocess
import sys
if sys.version_info[0] > 2:
class string:
expandtabs = str.expandtabs
else:
import string
##### Common utilities for update_*test_checks.py
_verbose = False
def parse_commandline_args(parser):
parser.add_argument('--include-generated-funcs', action='store_true',
help='Output checks for functions not in source')
parser.add_argument('-v', '--verbose', action='store_true',
help='Show verbose output')
parser.add_argument('-u', '--update-only', action='store_true',
help='Only update test if it was already autogened')
parser.add_argument('--force-update', action='store_true',
help='Update test even if it was autogened by a different script')
parser.add_argument('--enable', action='store_true', dest='enabled', default=True,
help='Activate CHECK line generation from this point forward')
parser.add_argument('--disable', action='store_false', dest='enabled',
help='Deactivate CHECK line generation from this point forward')
args = parser.parse_args()
global _verbose
_verbose = args.verbose
return args
class InputLineInfo(object):
def __init__(self, line, line_number, args, argv):
self.line = line
self.line_number = line_number
self.args = args
self.argv = argv
class TestInfo(object):
def __init__(self, test, parser, script_name, input_lines, args, argv,
comment_prefix, argparse_callback):
self.parser = parser
self.argparse_callback = argparse_callback
self.path = test
self.args = args
self.argv = argv
self.input_lines = input_lines
self.run_lines = find_run_lines(test, self.input_lines)
self.comment_prefix = comment_prefix
if self.comment_prefix is None:
if self.path.endswith('.mir'):
self.comment_prefix = '#'
else:
self.comment_prefix = ';'
self.autogenerated_note_prefix = self.comment_prefix + ' ' + UTC_ADVERT
self.test_autogenerated_note = self.autogenerated_note_prefix + script_name
self.test_autogenerated_note += get_autogennote_suffix(parser, self.args)
def ro_iterlines(self):
for line_num, input_line in enumerate(self.input_lines):
args, argv = check_for_command(input_line, self.parser,
self.args, self.argv, self.argparse_callback)
yield InputLineInfo(input_line, line_num, args, argv)
def iterlines(self, output_lines):
output_lines.append(self.test_autogenerated_note)
for line_info in self.ro_iterlines():
input_line = line_info.line
# Discard any previous script advertising.
if input_line.startswith(self.autogenerated_note_prefix):
continue
self.args = line_info.args
self.argv = line_info.argv
if not self.args.enabled:
output_lines.append(input_line)
continue
yield line_info
def itertests(test_patterns, parser, script_name, comment_prefix=None, argparse_callback=None):
for pattern in test_patterns:
# On Windows we must expand the patterns ourselves.
tests_list = glob.glob(pattern)
if not tests_list:
warn("Test file pattern '%s' was not found. Ignoring it." % (pattern,))
continue
for test in tests_list:
with open(test) as f:
input_lines = [l.rstrip() for l in f]
args = parser.parse_args()
if argparse_callback is not None:
argparse_callback(args)
argv = sys.argv[:]
first_line = input_lines[0] if input_lines else ""
if UTC_ADVERT in first_line:
if script_name not in first_line and not args.force_update:
warn("Skipping test which wasn't autogenerated by " + script_name, test)
continue
args, argv = check_for_command(first_line, parser, args, argv, argparse_callback)
elif args.update_only:
assert UTC_ADVERT not in first_line
warn("Skipping test which isn't autogenerated: " + test)
continue
yield TestInfo(test, parser, script_name, input_lines, args, argv,
comment_prefix, argparse_callback)
def should_add_line_to_output(input_line, prefix_set):
# Skip any blank comment lines in the IR.
if input_line.strip() == ';':
return False
# Skip any blank lines in the IR.
#if input_line.strip() == '':
# return False
# And skip any CHECK lines. We're building our own.
m = CHECK_RE.match(input_line)
if m and m.group(1) in prefix_set:
return False
return True
# Invoke the tool that is being tested.
def invoke_tool(exe, cmd_args, ir):
with open(ir) as ir_file:
# TODO Remove the str form which is used by update_test_checks.py and
# update_llc_test_checks.py
# The safer list form is used by update_cc_test_checks.py
if isinstance(cmd_args, list):
stdout = subprocess.check_output([exe] + cmd_args, stdin=ir_file)
else:
stdout = subprocess.check_output(exe + ' ' + cmd_args,
shell=True, stdin=ir_file)
if sys.version_info[0] > 2:
stdout = stdout.decode()
# Fix line endings to unix CR style.
return stdout.replace('\r\n', '\n')
##### LLVM IR parser
RUN_LINE_RE = re.compile(r'^\s*(?://|[;#])\s*RUN:\s*(.*)$')
CHECK_PREFIX_RE = re.compile(r'--?check-prefix(?:es)?[= ](\S+)')
PREFIX_RE = re.compile('^[a-zA-Z0-9_-]+$')
CHECK_RE = re.compile(r'^\s*(?://|[;#])\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL|-SAME|-EMPTY)?:')
UTC_ARGS_KEY = 'UTC_ARGS:'
UTC_ARGS_CMD = re.compile(r'.*' + UTC_ARGS_KEY + '\s*(?P<cmd>.*)\s*$')
UTC_ADVERT = 'NOTE: Assertions have been autogenerated by '
OPT_FUNCTION_RE = re.compile(
r'^(\s*;\s*Function\sAttrs:\s(?P<attrs>[\w\s]+?))?\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w.$-]+?)\s*'
r'(?P<args_and_sig>\((\)|(.*?[\w.-]+?)\))[^{]*\{)\n(?P<body>.*?)^\}$',
flags=(re.M | re.S))
ANALYZE_FUNCTION_RE = re.compile(
r'^\s*\'(?P<analysis>[\w\s-]+?)\'\s+for\s+function\s+\'(?P<func>[\w.$-]+?)\':'
r'\s*\n(?P<body>.*)$',
flags=(re.X | re.S))
IR_FUNCTION_RE = re.compile(r'^\s*define\s+(?:internal\s+)?[^@]*@"?([\w.$-]+)"?\s*\(')
TRIPLE_IR_RE = re.compile(r'^\s*target\s+triple\s*=\s*"([^"]+)"$')
TRIPLE_ARG_RE = re.compile(r'-mtriple[= ]([^ ]+)')
MARCH_ARG_RE = re.compile(r'-march[= ]([^ ]+)')
SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)')
SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M)
SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
SCRUB_TRAILING_WHITESPACE_TEST_RE = SCRUB_TRAILING_WHITESPACE_RE
SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE = re.compile(r'([ \t]|(#[0-9]+))+$', flags=re.M)
SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
SCRUB_LOOP_COMMENT_RE = re.compile(
r'# =>This Inner Loop Header:.*|# in Loop:.*', flags=re.M)
SCRUB_TAILING_COMMENT_TOKEN_RE = re.compile(r'(?<=\S)+[ \t]*#$', flags=re.M)
def error(msg, test_file=None):
if test_file:
msg = '{}: {}'.format(msg, test_file)
print('ERROR: {}'.format(msg), file=sys.stderr)
def warn(msg, test_file=None):
if test_file:
msg = '{}: {}'.format(msg, test_file)
print('WARNING: {}'.format(msg), file=sys.stderr)
def debug(*args, **kwargs):
# Python2 does not allow def debug(*args, file=sys.stderr, **kwargs):
if 'file' not in kwargs:
kwargs['file'] = sys.stderr
if _verbose:
print(*args, **kwargs)
def find_run_lines(test, lines):
debug('Scanning for RUN lines in test file:', test)
raw_lines = [m.group(1)
for m in [RUN_LINE_RE.match(l) for l in lines] if m]
run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
for l in raw_lines[1:]:
if run_lines[-1].endswith('\\'):
run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l
else:
run_lines.append(l)
debug('Found {} RUN lines in {}:'.format(len(run_lines), test))
for l in run_lines:
debug(' RUN: {}'.format(l))
return run_lines
def scrub_body(body):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
body = SCRUB_WHITESPACE_RE.sub(r' ', body)
# Expand the tabs used for indentation.
body = string.expandtabs(body, 2)
# Strip trailing whitespace.
body = SCRUB_TRAILING_WHITESPACE_TEST_RE.sub(r'', body)
return body
def do_scrub(body, scrubber, scrubber_args, extra):
if scrubber_args:
local_args = copy.deepcopy(scrubber_args)
local_args[0].extra_scrub = extra
return scrubber(body, *local_args)
return scrubber(body, *scrubber_args)
# Build up a dictionary of all the function bodies.
class function_body(object):
def __init__(self, string, extra, args_and_sig, attrs):
self.scrub = string
self.extrascrub = extra
self.args_and_sig = args_and_sig
self.attrs = attrs
def is_same_except_arg_names(self, extrascrub, args_and_sig, attrs):
arg_names = set()
def drop_arg_names(match):
arg_names.add(match.group(3))
return match.group(1) + match.group(match.lastindex)
def repl_arg_names(match):
if match.group(3) is not None and match.group(3) in arg_names:
return match.group(1) + match.group(match.lastindex)
return match.group(1) + match.group(2) + match.group(match.lastindex)
if self.attrs != attrs:
return False
ans0 = IR_VALUE_RE.sub(drop_arg_names, self.args_and_sig)
ans1 = IR_VALUE_RE.sub(drop_arg_names, args_and_sig)
if ans0 != ans1:
return False
es0 = IR_VALUE_RE.sub(repl_arg_names, self.extrascrub)
es1 = IR_VALUE_RE.sub(repl_arg_names, extrascrub)
es0 = SCRUB_IR_COMMENT_RE.sub(r'', es0)
es1 = SCRUB_IR_COMMENT_RE.sub(r'', es1)
return es0 == es1
def __str__(self):
return self.scrub
class FunctionTestBuilder:
def __init__(self, run_list, flags, scrubber_args):
self._verbose = flags.verbose
self._record_args = flags.function_signature
self._check_attributes = flags.check_attributes
self._scrubber_args = scrubber_args
self._func_dict = {}
self._func_order = {}
for tuple in run_list:
for prefix in tuple[0]:
self._func_dict.update({prefix:dict()})
self._func_order.update({prefix: []})
def finish_and_get_func_dict(self):
for prefix in self._get_failed_prefixes():
warn('Prefix %s had conflicting output from different RUN lines for all functions' % (prefix,))
return self._func_dict
def func_order(self):
return self._func_order
def process_run_line(self, function_re, scrubber, raw_tool_output, prefixes):
for m in function_re.finditer(raw_tool_output):
if not m:
continue
func = m.group('func')
body = m.group('body')
attrs = m.group('attrs') if self._check_attributes else ''
# Determine if we print arguments, the opening brace, or nothing after the
# function name
if self._record_args and 'args_and_sig' in m.groupdict():
args_and_sig = scrub_body(m.group('args_and_sig').strip())
elif 'args_and_sig' in m.groupdict():
args_and_sig = '('
else:
args_and_sig = ''
scrubbed_body = do_scrub(body, scrubber, self._scrubber_args,
extra=False)
scrubbed_extra = do_scrub(body, scrubber, self._scrubber_args,
extra=True)
if 'analysis' in m.groupdict():
analysis = m.group('analysis')
if analysis.lower() != 'cost model analysis':
warn('Unsupported analysis mode: %r!' % (analysis,))
if func.startswith('stress'):
# We only use the last line of the function body for stress tests.
scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
if self._verbose:
print('Processing function: ' + func, file=sys.stderr)
for l in scrubbed_body.splitlines():
print(' ' + l, file=sys.stderr)
for prefix in prefixes:
if func in self._func_dict[prefix]:
if (self._func_dict[prefix][func] is None or
str(self._func_dict[prefix][func]) != scrubbed_body or
self._func_dict[prefix][func].args_and_sig != args_and_sig or
self._func_dict[prefix][func].attrs != attrs):
if (self._func_dict[prefix][func] is not None and
self._func_dict[prefix][func].is_same_except_arg_names(
scrubbed_extra,
args_and_sig,
attrs)):
self._func_dict[prefix][func].scrub = scrubbed_extra
self._func_dict[prefix][func].args_and_sig = args_and_sig
continue
else:
# This means a previous RUN line produced a body for this function
# that is different from the one produced by this current RUN line,
# so the body can't be common accross RUN lines. We use None to
# indicate that.
self._func_dict[prefix][func] = None
continue
self._func_dict[prefix][func] = function_body(
scrubbed_body, scrubbed_extra, args_and_sig, attrs)
self._func_order[prefix].append(func)
def _get_failed_prefixes(self):
# This returns the list of those prefixes that failed to match any function,
# because there were conflicting bodies produced by different RUN lines, in
# all instances of the prefix. Effectively, this prefix is unused and should
# be removed.
for prefix in self._func_dict:
if (self._func_dict[prefix] and
(not [fct for fct in self._func_dict[prefix]
if self._func_dict[prefix][fct] is not None])):
yield prefix
##### Generator of LLVM IR CHECK lines
SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*')
# TODO: We should also derive check lines for global, debug, loop declarations, etc..
class NamelessValue:
def __init__(self, check_prefix, ir_prefix, ir_regexp):
self.check_prefix = check_prefix
self.ir_prefix = ir_prefix
self.ir_regexp = ir_regexp
# Description of the different "unnamed" values we match in the IR, e.g.,
# (local) ssa values, (debug) metadata, etc.
nameless_values = [
NamelessValue(r'TMP', r'%', r'[\w.-]+?'),
NamelessValue(r'GLOB', r'@', r'[0-9]+?'),
NamelessValue(r'ATTR', r'#', r'[0-9]+?'),
NamelessValue(r'DBG', r'!dbg !', r'[0-9]+?'),
NamelessValue(r'TBAA', r'!tbaa !', r'[0-9]+?'),
NamelessValue(r'RNG', r'!range !', r'[0-9]+?'),
NamelessValue(r'LOOP', r'!llvm.loop !', r'[0-9]+?'),
NamelessValue(r'META', r'metadata !', r'[0-9]+?'),
]
# Build the regexp that matches an "IR value". This can be a local variable,
# argument, global, or metadata, anything that is "named". It is important that
# the PREFIX and SUFFIX below only contain a single group, if that changes
# other locations will need adjustment as well.
IR_VALUE_REGEXP_PREFIX = r'(\s+)'
IR_VALUE_REGEXP_STRING = r''
for nameless_value in nameless_values:
if IR_VALUE_REGEXP_STRING:
IR_VALUE_REGEXP_STRING += '|'
IR_VALUE_REGEXP_STRING += nameless_value.ir_prefix + r'(' + nameless_value.ir_regexp + r')'
IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)'
IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX)
# The entire match is group 0, the prefix has one group (=1), the entire
# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start.
first_nameless_group_in_ir_value_match = 3
# Check a match for IR_VALUE_RE and inspect it to determine if it was a local
# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above.
def get_idx_from_ir_value_match(match):
for i in range(first_nameless_group_in_ir_value_match, match.lastindex):
if match.group(i) is not None:
return i - first_nameless_group_in_ir_value_match
error("Unable to identify the kind of IR value from the match!")
return 0;
# See get_idx_from_ir_value_match
def get_name_from_ir_value_match(match):
return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match)
# Return the nameless prefix we use for this kind or IR value, see also
# get_idx_from_ir_value_match
def get_nameless_check_prefix_from_ir_value_match(match):
return nameless_values[get_idx_from_ir_value_match(match)].check_prefix
# Return the IR prefix we use for this kind or IR value, e.g., % for locals,
# see also get_idx_from_ir_value_match
def get_ir_prefix_from_ir_value_match(match):
return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix
# Return true if this kind or IR value is "local", basically if it matches '%{{.*}}'.
def is_local_ir_value_match(match):
return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%'
# Create a FileCheck variable name based on an IR name.
def get_value_name(var, match):
if var.isdigit():
var = get_nameless_check_prefix_from_ir_value_match(match) + var
var = var.replace('.', '_')
var = var.replace('-', '_')
return var.upper()
# Create a FileCheck variable from regex.
def get_value_definition(var, match):
return '[[' + get_value_name(var, match) + ':' + get_ir_prefix_from_ir_value_match(match) + '.*]]'
# Use a FileCheck variable.
def get_value_use(var, match):
return '[[' + get_value_name(var, match) + ']]'
# Replace IR value defs and uses with FileCheck variables.
def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen):
# This gets called for each match that occurs in
# a line. We transform variables we haven't seen
# into defs, and variables we have seen into uses.
def transform_line_vars(match):
pre = get_ir_prefix_from_ir_value_match(match)
var = get_name_from_ir_value_match(match)
for nameless_value in nameless_values:
if re.match(r'^' + nameless_value.check_prefix + r'[0-9]+?$', var, re.IGNORECASE):
warn("Change IR value name '%s' to prevent possible conflict with scripted FileCheck name." % (var,))
if (pre, var) in vars_seen or (pre, var) in global_vars_seen:
rv = get_value_use(var, match)
else:
if is_local_ir_value_match(match):
vars_seen.add((pre, var))
else:
global_vars_seen.add((pre, var))
rv = get_value_definition(var, match)
# re.sub replaces the entire regex match
# with whatever you return, so we have
# to make sure to hand it back everything
# including the commas and spaces.
return match.group(1) + rv + match.group(match.lastindex)
lines_with_def = []
for i, line in enumerate(lines):
# An IR variable named '%.' matches the FileCheck regex string.
line = line.replace('%.', '%dot')
# Ignore any comments, since the check lines will too.
scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line)
lines[i] = scrubbed_line
if not is_analyze:
# It can happen that two matches are back-to-back and for some reason sub
# will not replace both of them. For now we work around this by
# substituting until there is no more match.
changed = True
while changed:
(lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1)
return lines
def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze, global_vars_seen_dict):
# prefix_exclusions are prefixes we cannot use to print the function because it doesn't exist in run lines that use these prefixes as well.
prefix_exclusions = set()
printed_prefixes = []
for p in prefix_list:
checkprefixes = p[0]
# If not all checkprefixes of this run line produced the function we cannot check for it as it does not
# exist for this run line. A subset of the check prefixes might know about the function but only because
# other run lines created it.
if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)):
prefix_exclusions |= set(checkprefixes)
continue
# prefix_exclusions is constructed, we can now emit the output
for p in prefix_list:
checkprefixes = p[0]
for checkprefix in checkprefixes:
if checkprefix in printed_prefixes:
break
# Check if the prefix is excluded.
if checkprefix in prefix_exclusions:
continue
# If we do not have output for this prefix we skip it.
if not func_dict[checkprefix][func_name]:
continue
# Add some space between different check prefixes, but not after the last
# check line (before the test code).
if is_asm:
if len(printed_prefixes) != 0:
output_lines.append(comment_marker)
if checkprefix not in global_vars_seen_dict:
global_vars_seen_dict[checkprefix] = set()
global_vars_seen = global_vars_seen_dict[checkprefix]
vars_seen = set()
printed_prefixes.append(checkprefix)
attrs = str(func_dict[checkprefix][func_name].attrs)
attrs = '' if attrs == 'None' else attrs
if attrs:
output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs))
args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig)
args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0]
if '[[' in args_and_sig:
output_lines.append(check_label_format % (checkprefix, func_name, ''))
output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig))
else:
output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig))
func_body = str(func_dict[checkprefix][func_name]).splitlines()
# For ASM output, just emit the check lines.
if is_asm:
output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0]))
for func_line in func_body[1:]:
if func_line.strip() == '':
output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix))
else:
output_lines.append('%s %s-NEXT: %s' % (comment_marker, checkprefix, func_line))
break
# For IR output, change all defs to FileCheck variables, so we're immune
# to variable naming fashions.
func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen)
# This could be selectively enabled with an optional invocation argument.
# Disabled for now: better to check everything. Be safe rather than sorry.
# Handle the first line of the function body as a special case because
# it's often just noise (a useless asm comment or entry label).
#if func_body[0].startswith("#") or func_body[0].startswith("entry:"):
# is_blank_line = True
#else:
# output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0]))
# is_blank_line = False
is_blank_line = False
for func_line in func_body:
if func_line.strip() == '':
is_blank_line = True
continue
# Do not waste time checking IR comments.
func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line)
# Skip blank lines instead of checking them.
if is_blank_line:
output_lines.append('{} {}: {}'.format(
comment_marker, checkprefix, func_line))
else:
output_lines.append('{} {}-NEXT: {}'.format(
comment_marker, checkprefix, func_line))
is_blank_line = False
# Add space between different check prefixes and also before the first
# line of code in the test function.
output_lines.append(comment_marker)
break
def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict,
func_name, preserve_names, function_sig, global_vars_seen_dict):
# Label format is based on IR string.
function_def_regex = 'define {{[^@]+}}' if function_sig else ''
check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex)
add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
check_label_format, False, preserve_names, global_vars_seen_dict)
def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name):
check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker)
global_vars_seen_dict = {}
add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
check_label_format, False, True, global_vars_seen_dict)
def check_prefix(prefix):
if not PREFIX_RE.match(prefix):
hint = ""
if ',' in prefix:
hint = " Did you mean '--check-prefixes=" + prefix + "'?"
warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) %
(prefix))
def verify_filecheck_prefixes(fc_cmd):
fc_cmd_parts = fc_cmd.split()
for part in fc_cmd_parts:
if "check-prefix=" in part:
prefix = part.split('=', 1)[1]
check_prefix(prefix)
elif "check-prefixes=" in part:
prefixes = part.split('=', 1)[1].split(',')
for prefix in prefixes:
check_prefix(prefix)
if prefixes.count(prefix) > 1:
warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,))
def get_autogennote_suffix(parser, args):
autogenerated_note_args = ''
for action in parser._actions:
if not hasattr(args, action.dest):
continue # Ignore options such as --help that aren't included in args
# Ignore parameters such as paths to the binary or the list of tests
if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary',
'clang', 'opt', 'llvm_bin', 'verbose'):
continue
value = getattr(args, action.dest)
if action.const is not None: # action stores a constant (usually True/False)
# Skip actions with different constant values (this happens with boolean
# --foo/--no-foo options)
if value != action.const:
continue
if parser.get_default(action.dest) == value:
continue # Don't add default values
autogenerated_note_args += action.option_strings[0] + ' '
if action.const is None: # action takes a parameter
autogenerated_note_args += '%s ' % value
if autogenerated_note_args:
autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1])
return autogenerated_note_args
def check_for_command(line, parser, args, argv, argparse_callback):
cmd_m = UTC_ARGS_CMD.match(line)
if cmd_m:
cmd = cmd_m.group('cmd').strip().split(' ')
argv = argv + cmd
args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv))
if argparse_callback is not None:
argparse_callback(args)
return args, argv
def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global):
result = get_arg_to_check(test_info.args)
if not result and is_global:
# See if this has been specified via UTC_ARGS. This is a "global" option
# that affects the entire generation of test checks. If it exists anywhere
# in the test, apply it to everything.
saw_line = False
for line_info in test_info.ro_iterlines():
line = line_info.line
if not line.startswith(';') and line.strip() != '':
saw_line = True
result = get_arg_to_check(line_info.args)
if result:
if warn and saw_line:
# We saw the option after already reading some test input lines.
# Warn about it.
print('WARNING: Found {} in line following test start: '.format(arg_string)
+ line, file=sys.stderr)
print('WARNING: Consider moving {} to top of file'.format(arg_string),
file=sys.stderr)
break
return result
def dump_input_lines(output_lines, test_info, prefix_set, comment_string):
for input_line_info in test_info.iterlines(output_lines):
line = input_line_info.line
args = input_line_info.args
if line.strip() == comment_string:
continue
if line.lstrip().startswith(comment_string):
m = CHECK_RE.match(line)
if m and m.group(1) in prefix_set:
continue
output_lines.append(line.rstrip('\n'))
def add_checks_at_end(output_lines, prefix_list, func_order,
comment_string, check_generator):
added = set()
for prefix in prefix_list:
prefixes = prefix[0]
tool_args = prefix[1]
for prefix in prefixes:
for func in func_order[prefix]:
if added:
output_lines.append(comment_string)
added.add(func)
# The add_*_checks routines expect a run list whose items are
# tuples that have a list of prefixes as their first element and
# tool command args string as their second element. They output
# checks for each prefix in the list of prefixes. By doing so, it
# implicitly assumes that for each function every run line will
# generate something for that function. That is not the case for
# generated functions as some run lines might not generate them
# (e.g. -fopenmp vs. no -fopenmp).
#
# Therefore, pass just the prefix we're interested in. This has
# the effect of generating all of the checks for functions of a
# single prefix before moving on to the next prefix. So checks
# are ordered by prefix instead of by function as in "normal"
# mode.
check_generator(output_lines,
[([prefix], tool_args)],
func)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/UpdateTestChecks/common.py |
#!/usr/bin/env python
from __future__ import print_function
def analyze_match_table(path):
# Extract the instruction table.
data = open(path).read()
start = data.index("static const MatchEntry MatchTable")
end = data.index("\n};\n", start)
lines = data[start:end].split("\n")[1:]
# Parse the instructions.
insns = []
for ln in lines:
ln = ln.split("{", 1)[1]
ln = ln.rsplit("}", 1)[0]
a,bc = ln.split("{", 1)
b,c = bc.split("}", 1)
code, string, converter, _ = [s.strip()
for s in a.split(",")]
items = [s.strip() for s in b.split(",")]
_,features = [s.strip() for s in c.split(",")]
assert string[0] == string[-1] == '"'
string = string[1:-1]
insns.append((code,string,converter,items,features))
# For every mnemonic, compute whether or not it can have a carry setting
# operand and whether or not it can have a predication code.
mnemonic_flags = {}
for insn in insns:
mnemonic = insn[1]
items = insn[3]
flags = mnemonic_flags[mnemonic] = mnemonic_flags.get(mnemonic, set())
flags.update(items)
mnemonics = set(mnemonic_flags)
ccout_mnemonics = set(m for m in mnemonics
if 'MCK_CCOut' in mnemonic_flags[m])
condcode_mnemonics = set(m for m in mnemonics
if 'MCK_CondCode' in mnemonic_flags[m])
noncondcode_mnemonics = mnemonics - condcode_mnemonics
print(' || '.join('Mnemonic == "%s"' % m
for m in ccout_mnemonics))
print(' || '.join('Mnemonic == "%s"' % m
for m in noncondcode_mnemonics))
def main():
import sys
if len(sys.argv) == 1:
import os
from lit.Util import capture
llvm_obj_root = capture(["llvm-config", "--obj-root"])
file = os.path.join(llvm_obj_root,
"lib/Target/ARM/ARMGenAsmMatcher.inc")
elif len(sys.argv) == 2:
file = sys.argv[1]
else:
raise NotImplementedError
analyze_match_table(file)
if __name__ == '__main__':
main()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/Target/ARM/analyze-match-table.py |
#!/usr/bin/env python
# Auto-generates an exhaustive and repetitive test for correct bundle-locked
# alignment on x86.
# For every possible offset in an aligned bundle, a bundle-locked group of every
# size in the inclusive range [1, bundle_size] is inserted. An appropriate CHECK
# is added to verify that NOP padding occurred (or did not occur) as expected.
# Run with --align-to-end to generate a similar test with align_to_end for each
# .bundle_lock directive.
# This script runs with Python 2.7 and 3.2+
from __future__ import print_function
import argparse
BUNDLE_SIZE_POW2 = 4
BUNDLE_SIZE = 2 ** BUNDLE_SIZE_POW2
PREAMBLE = '''
# RUN: llvm-mc -filetype=obj -triple i386-pc-linux-gnu %s -o - \\
# RUN: | llvm-objdump -triple i386 -disassemble -no-show-raw-insn - | FileCheck %s
# !!! This test is auto-generated from utils/testgen/mc-bundling-x86-gen.py !!!
# It tests that bundle-aligned grouping works correctly in MC. Read the
# source of the script for more details.
.text
.bundle_align_mode {0}
'''.format(BUNDLE_SIZE_POW2).lstrip()
ALIGNTO = ' .align {0}, 0x90'
NOPFILL = ' .fill {0}, 1, 0x90'
def print_bundle_locked_sequence(len, align_to_end=False):
print(' .bundle_lock{0}'.format(' align_to_end' if align_to_end else ''))
print(' .rept {0}'.format(len))
print(' inc %eax')
print(' .endr')
print(' .bundle_unlock')
def generate(align_to_end=False):
print(PREAMBLE)
ntest = 0
for instlen in range(1, BUNDLE_SIZE + 1):
for offset in range(0, BUNDLE_SIZE):
# Spread out all the instructions to not worry about cross-bundle
# interference.
print(ALIGNTO.format(2 * BUNDLE_SIZE))
print('INSTRLEN_{0}_OFFSET_{1}:'.format(instlen, offset))
if offset > 0:
print(NOPFILL.format(offset))
print_bundle_locked_sequence(instlen, align_to_end)
# Now generate an appropriate CHECK line
base_offset = ntest * 2 * BUNDLE_SIZE
inst_orig_offset = base_offset + offset # had it not been padded...
def print_check(adjusted_offset=None, nop_split_offset=None):
if adjusted_offset is not None:
print('# CHECK: {0:x}: nop'.format(inst_orig_offset))
if nop_split_offset is not None:
print('# CHECK: {0:x}: nop'.format(nop_split_offset))
print('# CHECK: {0:x}: incl'.format(adjusted_offset))
else:
print('# CHECK: {0:x}: incl'.format(inst_orig_offset))
if align_to_end:
if offset + instlen == BUNDLE_SIZE:
# No padding needed
print_check()
elif offset + instlen < BUNDLE_SIZE:
# Pad to end at nearest bundle boundary
offset_to_end = base_offset + (BUNDLE_SIZE - instlen)
print_check(offset_to_end)
else: # offset + instlen > BUNDLE_SIZE
# Pad to end at next bundle boundary, splitting the nop sequence
# at the nearest bundle boundary
offset_to_nearest_bundle = base_offset + BUNDLE_SIZE
offset_to_end = base_offset + (BUNDLE_SIZE * 2 - instlen)
if offset_to_nearest_bundle == offset_to_end:
offset_to_nearest_bundle = None
print_check(offset_to_end, offset_to_nearest_bundle)
else:
if offset + instlen > BUNDLE_SIZE:
# Padding needed
aligned_offset = (inst_orig_offset + instlen) & ~(BUNDLE_SIZE - 1)
print_check(aligned_offset)
else:
# No padding needed
print_check()
print()
ntest += 1
if __name__ == '__main__':
argparser = argparse.ArgumentParser()
argparser.add_argument('--align-to-end',
action='store_true',
help='generate .bundle_lock with align_to_end option')
args = argparser.parse_args()
generate(align_to_end=args.align_to_end)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/testgen/mc-bundling-x86-gen.py |
#!/usr/bin/env python
from __future__ import print_function
import re, string, sys, os, time
DEBUG = 0
testDirName = 'llvm-test'
test = ['compile', 'llc', 'jit', 'cbe']
exectime = ['llc-time', 'jit-time', 'cbe-time',]
comptime = ['llc', 'jit-comptime', 'compile']
(tp, exp) = ('compileTime_', 'executeTime_')
def parse(file):
f=open(file, 'r')
d = f.read()
#Cleanup weird stuff
d = re.sub(r',\d+:\d','', d)
r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d)
test = {}
fname = ''
for t in r:
if DEBUG:
print(t)
if t[0] == 'PASS' or t[0] == 'FAIL' :
tmp = t[2].split(testDirName)
if DEBUG:
print(tmp)
if len(tmp) == 2:
fname = tmp[1].strip('\r\n')
else:
fname = tmp[0].strip('\r\n')
if fname not in test :
test[fname] = {}
for k in test:
test[fname][k] = 'NA'
test[fname][t[1]] = t[0]
if DEBUG:
print(test[fname][t[1]])
else :
try:
n = t[0].split('RESULT-')[1]
if DEBUG:
print(n);
if n == 'llc' or n == 'jit-comptime' or n == 'compile':
test[fname][tp + n] = float(t[2].split(' ')[2])
if DEBUG:
print(test[fname][tp + n])
elif n.endswith('-time') :
test[fname][exp + n] = float(t[2].strip('\r\n'))
if DEBUG:
print(test[fname][exp + n])
else :
print("ERROR!")
sys.exit(1)
except:
continue
return test
# Diff results and look for regressions.
def diffResults(d_old, d_new):
for t in sorted(d_old.keys()) :
if DEBUG:
print(t)
if t in d_new :
# Check if the test passed or failed.
for x in test:
if x in d_old[t]:
if x in d_new[t]:
if d_old[t][x] == 'PASS':
if d_new[t][x] != 'PASS':
print(t + " *** REGRESSION (" + x + ")\n")
else:
if d_new[t][x] == 'PASS':
print(t + " * NEW PASS (" + x + ")\n")
else :
print(t + "*** REGRESSION (" + x + ")\n")
# For execution time, if there is no result, its a fail.
for x in exectime:
if tp + x in d_old[t]:
if tp + x not in d_new[t]:
print(t + " *** REGRESSION (" + tp + x + ")\n")
else :
if tp + x in d_new[t]:
print(t + " * NEW PASS (" + tp + x + ")\n")
for x in comptime:
if exp + x in d_old[t]:
if exp + x not in d_new[t]:
print(t + " *** REGRESSION (" + exp + x + ")\n")
else :
if exp + x in d_new[t]:
print(t + " * NEW PASS (" + exp + x + ")\n")
else :
print(t + ": Removed from test-suite.\n")
#Main
if len(sys.argv) < 3 :
print('Usage:', sys.argv[0], \
'<old log> <new log>')
sys.exit(-1)
d_old = parse(sys.argv[1])
d_new = parse(sys.argv[2])
diffResults(d_old, d_new)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/release/findRegressions-nightly.py |
#!/usr/bin/env python
from __future__ import print_function
import re, string, sys, os, time, math
DEBUG = 0
(tp, exp) = ('compile', 'exec')
def parse(file):
f = open(file, 'r')
d = f.read()
# Cleanup weird stuff
d = re.sub(r',\d+:\d', '', d)
r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d)
test = {}
fname = ''
for t in r:
if DEBUG:
print(t)
if t[0] == 'PASS' or t[0] == 'FAIL' :
tmp = t[2].split('llvm-test/')
if DEBUG:
print(tmp)
if len(tmp) == 2:
fname = tmp[1].strip('\r\n')
else:
fname = tmp[0].strip('\r\n')
if fname not in test:
test[fname] = {}
test[fname][t[1] + ' state'] = t[0]
test[fname][t[1] + ' time'] = float('nan')
else :
try:
n = t[0].split('RESULT-')[1]
if DEBUG:
print("n == ", n);
if n == 'compile-success':
test[fname]['compile time'] = float(t[2].split('program')[1].strip('\r\n'))
elif n == 'exec-success':
test[fname]['exec time'] = float(t[2].split('program')[1].strip('\r\n'))
if DEBUG:
print(test[fname][string.replace(n, '-success', '')])
else :
# print "ERROR!"
sys.exit(1)
except:
continue
return test
# Diff results and look for regressions.
def diffResults(d_old, d_new):
regressions = {}
passes = {}
removed = ''
for x in ['compile state', 'compile time', 'exec state', 'exec time']:
regressions[x] = ''
passes[x] = ''
for t in sorted(d_old.keys()) :
if t in d_new:
# Check if the test passed or failed.
for x in ['compile state', 'compile time', 'exec state', 'exec time']:
if x not in d_old[t] and x not in d_new[t]:
continue
if x in d_old[t]:
if x in d_new[t]:
if d_old[t][x] == 'PASS':
if d_new[t][x] != 'PASS':
regressions[x] += t + "\n"
else:
if d_new[t][x] == 'PASS':
passes[x] += t + "\n"
else :
regressions[x] += t + "\n"
if x == 'compile state' or x == 'exec state':
continue
# For execution time, if there is no result it's a fail.
if x not in d_old[t] and x not in d_new[t]:
continue
elif x not in d_new[t]:
regressions[x] += t + "\n"
elif x not in d_old[t]:
passes[x] += t + "\n"
if math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]):
continue
elif math.isnan(d_old[t][x]) and not math.isnan(d_new[t][x]):
passes[x] += t + "\n"
elif not math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]):
regressions[x] += t + ": NaN%\n"
if d_new[t][x] > d_old[t][x] and d_old[t][x] > 0.0 and \
(d_new[t][x] - d_old[t][x]) / d_old[t][x] > .05:
regressions[x] += t + ": " + "{0:.1f}".format(100 * (d_new[t][x] - d_old[t][x]) / d_old[t][x]) + "%\n"
else :
removed += t + "\n"
if len(regressions['compile state']) != 0:
print('REGRESSION: Compilation Failed')
print(regressions['compile state'])
if len(regressions['exec state']) != 0:
print('REGRESSION: Execution Failed')
print(regressions['exec state'])
if len(regressions['compile time']) != 0:
print('REGRESSION: Compilation Time')
print(regressions['compile time'])
if len(regressions['exec time']) != 0:
print('REGRESSION: Execution Time')
print(regressions['exec time'])
if len(passes['compile state']) != 0:
print('NEW PASSES: Compilation')
print(passes['compile state'])
if len(passes['exec state']) != 0:
print('NEW PASSES: Execution')
print(passes['exec state'])
if len(removed) != 0:
print('REMOVED TESTS')
print(removed)
# Main
if len(sys.argv) < 3 :
print('Usage:', sys.argv[0], '<old log> <new log>')
sys.exit(-1)
d_old = parse(sys.argv[1])
d_new = parse(sys.argv[2])
diffResults(d_old, d_new)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/release/findRegressions-simple.py |
#!/usr/bin/env python3
# ===-- github-upload-release.py ------------------------------------------===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===------------------------------------------------------------------------===#
#
# Create and manage releases in the llvm github project.
#
# This script requires python3 and the PyGithub module.
#
# Example Usage:
#
# You will need to obtain a personal access token for your github account in
# order to use this script. Instructions for doing this can be found here:
# https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line
#
# Create a new release from an existing tag:
# ./github-upload-release.py --token $github_token --release 8.0.1-rc4 create
#
# Upload files for a release
# ./github-upload-release.py --token $github_token --release 8.0.1-rc4 upload --files llvm-8.0.1rc4.src.tar.xz
#
# You can upload as many files as you want at a time and use wildcards e.g.
# ./github-upload-release.py --token $github_token --release 8.0.1-rc4 upload --files *.src.*
#===------------------------------------------------------------------------===#
import argparse
import github
def create_release(repo, release, tag = None, name = None, message = None):
if not tag:
tag = 'llvmorg-{}'.format(release)
if not name:
name = 'LLVM {}'.format(release)
if not message:
message = 'LLVM {} Release'.format(release)
prerelease = True if "rc" in release else False
repo.create_git_release(tag = tag, name = name, message = message,
prerelease = prerelease)
def upload_files(repo, release, files):
release = repo.get_release('llvmorg-{}'.format(release))
for f in files:
print('Uploading {}'.format(f))
release.upload_asset(f)
print("Done")
parser = argparse.ArgumentParser()
parser.add_argument('command', type=str, choices=['create', 'upload'])
# All args
parser.add_argument('--token', type=str)
parser.add_argument('--release', type=str)
# Upload args
parser.add_argument('--files', nargs='+', type=str)
args = parser.parse_args()
github = github.Github(args.token)
llvm_repo = github.get_organization('llvm').get_repo('llvm-project')
if args.command == 'create':
create_release(llvm_repo, args.release)
if args.command == 'upload':
upload_files(llvm_repo, args.release, args.files)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/release/github-upload-release.py |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import email.mime.multipart
import email.mime.text
import logging
import os.path
import pickle
import re
import smtplib
import subprocess
import sys
from datetime import datetime, timedelta
from phabricator import Phabricator
# Setting up a virtualenv to run this script can be done by running the
# following commands:
# $ virtualenv venv
# $ . ./venv/bin/activate
# $ pip install Phabricator
GIT_REPO_METADATA = (("llvm-monorepo", "https://github.com/llvm/llvm-project"),
)
# The below PhabXXX classes represent objects as modelled by Phabricator.
# The classes can be serialized to disk, to try and make sure that we don't
# needlessly have to re-fetch lots of data from Phabricator, as that would
# make this script unusably slow.
class PhabObject:
OBJECT_KIND = None
def __init__(self, id):
self.id = id
class PhabObjectCache:
def __init__(self, PhabObjectClass):
self.PhabObjectClass = PhabObjectClass
self.most_recent_info = None
self.oldest_info = None
self.id2PhabObjects = {}
def get_name(self):
return self.PhabObjectClass.OBJECT_KIND + "sCache"
def get(self, id):
if id not in self.id2PhabObjects:
self.id2PhabObjects[id] = self.PhabObjectClass(id)
return self.id2PhabObjects[id]
def get_ids_in_cache(self):
return list(self.id2PhabObjects.keys())
def get_objects(self):
return list(self.id2PhabObjects.values())
DEFAULT_DIRECTORY = "PhabObjectCache"
def _get_pickle_name(self, directory):
file_name = "Phab" + self.PhabObjectClass.OBJECT_KIND + "s.pickle"
return os.path.join(directory, file_name)
def populate_cache_from_disk(self, directory=DEFAULT_DIRECTORY):
"""
FIXME: consider if serializing to JSON would bring interoperability
advantages over serializing to pickle.
"""
try:
f = open(self._get_pickle_name(directory), "rb")
except IOError as err:
print("Could not find cache. Error message: {0}. Continuing..."
.format(err))
else:
with f:
try:
d = pickle.load(f)
self.__dict__.update(d)
except EOFError as err:
print("Cache seems to be corrupt. " +
"Not using cache. Error message: {0}".format(err))
def write_cache_to_disk(self, directory=DEFAULT_DIRECTORY):
if not os.path.exists(directory):
os.makedirs(directory)
with open(self._get_pickle_name(directory), "wb") as f:
pickle.dump(self.__dict__, f)
print("wrote cache to disk, most_recent_info= {0}".format(
datetime.fromtimestamp(self.most_recent_info)
if self.most_recent_info is not None else None))
class PhabReview(PhabObject):
OBJECT_KIND = "Review"
def __init__(self, id):
PhabObject.__init__(self, id)
def update(self, title, dateCreated, dateModified, author):
self.title = title
self.dateCreated = dateCreated
self.dateModified = dateModified
self.author = author
def setPhabDiffs(self, phabDiffs):
self.phabDiffs = phabDiffs
class PhabUser(PhabObject):
OBJECT_KIND = "User"
def __init__(self, id):
PhabObject.__init__(self, id)
def update(self, phid, realName):
self.phid = phid
self.realName = realName
class PhabHunk:
def __init__(self, rest_api_hunk):
self.oldOffset = int(rest_api_hunk["oldOffset"])
self.oldLength = int(rest_api_hunk["oldLength"])
# self.actual_lines_changed_offset will contain the offsets of the
# lines that were changed in this hunk.
self.actual_lines_changed_offset = []
offset = self.oldOffset
inHunk = False
hunkStart = -1
contextLines = 3
for line in rest_api_hunk["corpus"].split("\n"):
if line.startswith("+"):
# line is a new line that got introduced in this patch.
# Do not record it as a changed line.
if inHunk is False:
inHunk = True
hunkStart = max(self.oldOffset, offset - contextLines)
continue
if line.startswith("-"):
# line was changed or removed from the older version of the
# code. Record it as a changed line.
if inHunk is False:
inHunk = True
hunkStart = max(self.oldOffset, offset - contextLines)
offset += 1
continue
# line is a context line.
if inHunk is True:
inHunk = False
hunkEnd = offset + contextLines
self.actual_lines_changed_offset.append((hunkStart, hunkEnd))
offset += 1
if inHunk is True:
hunkEnd = offset + contextLines
self.actual_lines_changed_offset.append((hunkStart, hunkEnd))
# The above algorithm could result in adjacent or overlapping ranges
# being recorded into self.actual_lines_changed_offset.
# Merge the adjacent and overlapping ranges in there:
t = []
lastRange = None
for start, end in self.actual_lines_changed_offset + \
[(sys.maxsize, sys.maxsize)]:
if lastRange is None:
lastRange = (start, end)
else:
if lastRange[1] >= start:
lastRange = (lastRange[0], end)
else:
t.append(lastRange)
lastRange = (start, end)
self.actual_lines_changed_offset = t
class PhabChange:
def __init__(self, rest_api_change):
self.oldPath = rest_api_change["oldPath"]
self.hunks = [PhabHunk(h) for h in rest_api_change["hunks"]]
class PhabDiff(PhabObject):
OBJECT_KIND = "Diff"
def __init__(self, id):
PhabObject.__init__(self, id)
def update(self, rest_api_results):
self.revisionID = rest_api_results["revisionID"]
self.dateModified = int(rest_api_results["dateModified"])
self.dateCreated = int(rest_api_results["dateCreated"])
self.changes = [PhabChange(c) for c in rest_api_results["changes"]]
class ReviewsCache(PhabObjectCache):
def __init__(self):
PhabObjectCache.__init__(self, PhabReview)
class UsersCache(PhabObjectCache):
def __init__(self):
PhabObjectCache.__init__(self, PhabUser)
reviews_cache = ReviewsCache()
users_cache = UsersCache()
def init_phab_connection():
phab = Phabricator()
phab.update_interfaces()
return phab
def update_cached_info(phab, cache, phab_query, order, record_results,
max_nr_entries_per_fetch, max_nr_days_to_cache):
q = phab
LIMIT = max_nr_entries_per_fetch
for query_step in phab_query:
q = getattr(q, query_step)
results = q(order=order, limit=LIMIT)
most_recent_info, oldest_info = record_results(cache, results, phab)
oldest_info_to_fetch = datetime.fromtimestamp(most_recent_info) - \
timedelta(days=max_nr_days_to_cache)
most_recent_info_overall = most_recent_info
cache.write_cache_to_disk()
after = results["cursor"]["after"]
print("after: {0!r}".format(after))
print("most_recent_info: {0}".format(
datetime.fromtimestamp(most_recent_info)))
while (after is not None
and datetime.fromtimestamp(oldest_info) > oldest_info_to_fetch):
need_more_older_data = \
(cache.oldest_info is None or
datetime.fromtimestamp(cache.oldest_info) > oldest_info_to_fetch)
print(("need_more_older_data={0} cache.oldest_info={1} " +
"oldest_info_to_fetch={2}").format(
need_more_older_data,
datetime.fromtimestamp(cache.oldest_info)
if cache.oldest_info is not None else None,
oldest_info_to_fetch))
need_more_newer_data = \
(cache.most_recent_info is None or
cache.most_recent_info < most_recent_info)
print(("need_more_newer_data={0} cache.most_recent_info={1} " +
"most_recent_info={2}")
.format(need_more_newer_data, cache.most_recent_info,
most_recent_info))
if not need_more_older_data and not need_more_newer_data:
break
results = q(order=order, after=after, limit=LIMIT)
most_recent_info, oldest_info = record_results(cache, results, phab)
after = results["cursor"]["after"]
print("after: {0!r}".format(after))
print("most_recent_info: {0}".format(
datetime.fromtimestamp(most_recent_info)))
cache.write_cache_to_disk()
cache.most_recent_info = most_recent_info_overall
if after is None:
# We did fetch all records. Mark the cache to contain all info since
# the start of time.
oldest_info = 0
cache.oldest_info = oldest_info
cache.write_cache_to_disk()
def record_reviews(cache, reviews, phab):
most_recent_info = None
oldest_info = None
for reviewInfo in reviews["data"]:
if reviewInfo["type"] != "DREV":
continue
id = reviewInfo["id"]
# phid = reviewInfo["phid"]
dateModified = int(reviewInfo["fields"]["dateModified"])
dateCreated = int(reviewInfo["fields"]["dateCreated"])
title = reviewInfo["fields"]["title"]
author = reviewInfo["fields"]["authorPHID"]
phabReview = cache.get(id)
if "dateModified" not in phabReview.__dict__ or \
dateModified > phabReview.dateModified:
diff_results = phab.differential.querydiffs(revisionIDs=[id])
diff_ids = sorted(diff_results.keys())
phabDiffs = []
for diff_id in diff_ids:
diffInfo = diff_results[diff_id]
d = PhabDiff(diff_id)
d.update(diffInfo)
phabDiffs.append(d)
phabReview.update(title, dateCreated, dateModified, author)
phabReview.setPhabDiffs(phabDiffs)
print("Updated D{0} modified on {1} ({2} diffs)".format(
id, datetime.fromtimestamp(dateModified), len(phabDiffs)))
if most_recent_info is None:
most_recent_info = dateModified
elif most_recent_info < dateModified:
most_recent_info = dateModified
if oldest_info is None:
oldest_info = dateModified
elif oldest_info > dateModified:
oldest_info = dateModified
return most_recent_info, oldest_info
def record_users(cache, users, phab):
most_recent_info = None
oldest_info = None
for info in users["data"]:
if info["type"] != "USER":
continue
id = info["id"]
phid = info["phid"]
dateModified = int(info["fields"]["dateModified"])
# dateCreated = int(info["fields"]["dateCreated"])
realName = info["fields"]["realName"]
phabUser = cache.get(id)
phabUser.update(phid, realName)
if most_recent_info is None:
most_recent_info = dateModified
elif most_recent_info < dateModified:
most_recent_info = dateModified
if oldest_info is None:
oldest_info = dateModified
elif oldest_info > dateModified:
oldest_info = dateModified
return most_recent_info, oldest_info
PHABCACHESINFO = ((reviews_cache, ("differential", "revision", "search"),
"updated", record_reviews, 5, 7),
(users_cache, ("user", "search"), "newest", record_users,
100, 1000))
def load_cache():
for cache, phab_query, order, record_results, _, _ in PHABCACHESINFO:
cache.populate_cache_from_disk()
print("Loaded {0} nr entries: {1}".format(
cache.get_name(), len(cache.get_ids_in_cache())))
print("Loaded {0} has most recent info: {1}".format(
cache.get_name(),
datetime.fromtimestamp(cache.most_recent_info)
if cache.most_recent_info is not None else None))
def update_cache(phab):
load_cache()
for cache, phab_query, order, record_results, max_nr_entries_per_fetch, \
max_nr_days_to_cache in PHABCACHESINFO:
update_cached_info(phab, cache, phab_query, order, record_results,
max_nr_entries_per_fetch, max_nr_days_to_cache)
ids_in_cache = cache.get_ids_in_cache()
print("{0} objects in {1}".format(len(ids_in_cache), cache.get_name()))
cache.write_cache_to_disk()
def get_most_recent_reviews(days):
newest_reviews = sorted(
reviews_cache.get_objects(), key=lambda r: -r.dateModified)
if len(newest_reviews) == 0:
return newest_reviews
most_recent_review_time = \
datetime.fromtimestamp(newest_reviews[0].dateModified)
cut_off_date = most_recent_review_time - timedelta(days=days)
result = []
for review in newest_reviews:
if datetime.fromtimestamp(review.dateModified) < cut_off_date:
return result
result.append(review)
return result
# All of the above code is about fetching data from Phabricator and caching it
# on local disk. The below code contains the actual "business logic" for this
# script.
_userphid2realname = None
def get_real_name_from_author(user_phid):
global _userphid2realname
if _userphid2realname is None:
_userphid2realname = {}
for user in users_cache.get_objects():
_userphid2realname[user.phid] = user.realName
return _userphid2realname.get(user_phid, "unknown")
def print_most_recent_reviews(phab, days, filter_reviewers):
msgs = []
def add_msg(msg):
msgs.append(msg)
print(msg.encode('utf-8'))
newest_reviews = get_most_recent_reviews(days)
add_msg(u"These are the reviews that look interesting to be reviewed. " +
u"The report below has 2 sections. The first " +
u"section is organized per review; the second section is organized "
+ u"per potential reviewer.\n")
oldest_review = newest_reviews[-1] if len(newest_reviews) > 0 else None
oldest_datetime = \
datetime.fromtimestamp(oldest_review.dateModified) \
if oldest_review else None
add_msg((u"The report below is based on analyzing the reviews that got " +
u"touched in the past {0} days (since {1}). " +
u"The script found {2} such reviews.\n").format(
days, oldest_datetime, len(newest_reviews)))
reviewer2reviews_and_scores = {}
for i, review in enumerate(newest_reviews):
matched_reviewers = find_reviewers_for_review(review)
matched_reviewers = filter_reviewers(matched_reviewers)
if len(matched_reviewers) == 0:
continue
add_msg((u"{0:>3}. https://reviews.llvm.org/D{1} by {2}\n {3}\n" +
u" Last updated on {4}").format(
i, review.id,
get_real_name_from_author(review.author), review.title,
datetime.fromtimestamp(review.dateModified)))
for reviewer, scores in matched_reviewers:
add_msg(u" potential reviewer {0}, score {1}".format(
reviewer,
"(" + "/".join(["{0:.1f}%".format(s) for s in scores]) + ")"))
if reviewer not in reviewer2reviews_and_scores:
reviewer2reviews_and_scores[reviewer] = []
reviewer2reviews_and_scores[reviewer].append((review, scores))
# Print out a summary per reviewer.
for reviewer in sorted(reviewer2reviews_and_scores.keys()):
reviews_and_scores = reviewer2reviews_and_scores[reviewer]
reviews_and_scores.sort(key=lambda rs: rs[1], reverse=True)
add_msg(u"\n\nSUMMARY FOR {0} (found {1} reviews):".format(
reviewer, len(reviews_and_scores)))
for review, scores in reviews_and_scores:
add_msg(u"[{0}] https://reviews.llvm.org/D{1} '{2}' by {3}".format(
"/".join(["{0:.1f}%".format(s) for s in scores]), review.id,
review.title, get_real_name_from_author(review.author)))
return "\n".join(msgs)
def get_git_cmd_output(cmd):
output = None
try:
logging.debug(cmd)
output = subprocess.check_output(
cmd, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
logging.debug(str(e))
if output is None:
return None
return output.decode("utf-8", errors='ignore')
reAuthorMail = re.compile("^author-mail <([^>]*)>.*$")
def parse_blame_output_line_porcelain(blame_output_lines):
email2nr_occurences = {}
if blame_output_lines is None:
return email2nr_occurences
for line in blame_output_lines:
m = reAuthorMail.match(line)
if m:
author_email_address = m.group(1)
if author_email_address not in email2nr_occurences:
email2nr_occurences[author_email_address] = 1
else:
email2nr_occurences[author_email_address] += 1
return email2nr_occurences
class BlameOutputCache:
def __init__(self):
self.cache = {}
def _populate_cache_for(self, cache_key):
assert cache_key not in self.cache
git_repo, base_revision, path = cache_key
cmd = ("git -C {0} blame --encoding=utf-8 --date iso -f -e -w " +
"--line-porcelain {1} -- {2}").format(git_repo, base_revision,
path)
blame_output = get_git_cmd_output(cmd)
self.cache[cache_key] = \
blame_output.split('\n') if blame_output is not None else None
# FIXME: the blame cache could probably be made more effective still if
# instead of storing the requested base_revision in the cache, the last
# revision before the base revision this file/path got changed in gets
# stored. That way multiple project revisions for which this specific
# file/patch hasn't changed would get cache hits (instead of misses in
# the current implementation).
def get_blame_output_for(self, git_repo, base_revision, path, start_line=-1,
end_line=-1):
cache_key = (git_repo, base_revision, path)
if cache_key not in self.cache:
self._populate_cache_for(cache_key)
assert cache_key in self.cache
all_blame_lines = self.cache[cache_key]
if all_blame_lines is None:
return None
if start_line == -1 and end_line == -1:
return all_blame_lines
assert start_line >= 0
assert end_line >= 0
assert end_line <= len(all_blame_lines)
assert start_line <= len(all_blame_lines)
assert start_line <= end_line
return all_blame_lines[start_line:end_line]
def get_parsed_git_blame_for(self, git_repo, base_revision, path,
start_line=-1, end_line=-1):
return parse_blame_output_line_porcelain(
self.get_blame_output_for(git_repo, base_revision, path, start_line,
end_line))
blameOutputCache = BlameOutputCache()
def find_reviewers_for_diff_heuristic(diff):
# Heuristic 1: assume good reviewers are the ones that touched the same
# lines before as this patch is touching.
# Heuristic 2: assume good reviewers are the ones that touched the same
# files before as this patch is touching.
reviewers2nr_lines_touched = {}
reviewers2nr_files_touched = {}
# Assume last revision before diff was modified is the revision the diff
# applies to.
assert len(GIT_REPO_METADATA) == 1
git_repo = os.path.join("git_repos", GIT_REPO_METADATA[0][0])
cmd = 'git -C {0} rev-list -n 1 --before="{1}" master'.format(
git_repo,
datetime.fromtimestamp(
diff.dateModified).strftime("%Y-%m-%d %H:%M:%s"))
base_revision = get_git_cmd_output(cmd).strip()
logging.debug("Base revision={0}".format(base_revision))
for change in diff.changes:
path = change.oldPath
# Compute heuristic 1: look at context of patch lines.
for hunk in change.hunks:
for start_line, end_line in hunk.actual_lines_changed_offset:
# Collect git blame results for authors in those ranges.
for reviewer, nr_occurences in \
blameOutputCache.get_parsed_git_blame_for(
git_repo, base_revision, path, start_line, end_line
).items():
if reviewer not in reviewers2nr_lines_touched:
reviewers2nr_lines_touched[reviewer] = 0
reviewers2nr_lines_touched[reviewer] += nr_occurences
# Compute heuristic 2: don't look at context, just at files touched.
# Collect git blame results for authors in those ranges.
for reviewer, nr_occurences in \
blameOutputCache.get_parsed_git_blame_for(
git_repo, base_revision, path).items():
if reviewer not in reviewers2nr_files_touched:
reviewers2nr_files_touched[reviewer] = 0
reviewers2nr_files_touched[reviewer] += 1
# Compute "match scores"
total_nr_lines = sum(reviewers2nr_lines_touched.values())
total_nr_files = len(diff.changes)
reviewers_matchscores = \
[(reviewer,
(reviewers2nr_lines_touched.get(reviewer, 0)*100.0/total_nr_lines
if total_nr_lines != 0 else 0,
reviewers2nr_files_touched[reviewer]*100.0/total_nr_files
if total_nr_files != 0 else 0))
for reviewer, nr_lines
in reviewers2nr_files_touched.items()]
reviewers_matchscores.sort(key=lambda i: i[1], reverse=True)
return reviewers_matchscores
def find_reviewers_for_review(review):
# Process the newest diff first.
diffs = sorted(
review.phabDiffs, key=lambda d: d.dateModified, reverse=True)
if len(diffs) == 0:
return
diff = diffs[0]
matched_reviewers = find_reviewers_for_diff_heuristic(diff)
# Show progress, as this is a slow operation:
sys.stdout.write('.')
sys.stdout.flush()
logging.debug(u"matched_reviewers: {0}".format(matched_reviewers))
return matched_reviewers
def update_git_repos():
git_repos_directory = "git_repos"
for name, url in GIT_REPO_METADATA:
dirname = os.path.join(git_repos_directory, name)
if not os.path.exists(dirname):
cmd = "git clone {0} {1}".format(url, dirname)
output = get_git_cmd_output(cmd)
cmd = "git -C {0} pull --rebase".format(dirname)
output = get_git_cmd_output(cmd)
def send_emails(email_addresses, sender, msg):
s = smtplib.SMTP()
s.connect()
for email_address in email_addresses:
email_msg = email.mime.multipart.MIMEMultipart()
email_msg['From'] = sender
email_msg['To'] = email_address
email_msg['Subject'] = 'LLVM patches you may be able to review.'
email_msg.attach(email.mime.text.MIMEText(msg.encode('utf-8'), 'plain'))
# python 3.x: s.send_message(email_msg)
s.sendmail(email_msg['From'], email_msg['To'], email_msg.as_string())
s.quit()
def filter_reviewers_to_report_for(people_to_look_for):
# The below is just an example filter, to only report potential reviews
# to do for the people that will receive the report email.
return lambda potential_reviewers: [r for r in potential_reviewers
if r[0] in people_to_look_for]
def main():
parser = argparse.ArgumentParser(
description='Match open reviews to potential reviewers.')
parser.add_argument(
'--no-update-cache',
dest='update_cache',
action='store_false',
default=True,
help='Do not update cached Phabricator objects')
parser.add_argument(
'--email-report',
dest='email_report',
nargs='*',
default="",
help="A email addresses to send the report to.")
parser.add_argument(
'--sender',
dest='sender',
default="",
help="The email address to use in 'From' on messages emailed out.")
parser.add_argument(
'--email-addresses',
dest='email_addresses',
nargs='*',
help="The email addresses (as known by LLVM git) of " +
"the people to look for reviews for.")
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
if args.verbose >= 1:
logging.basicConfig(level=logging.DEBUG)
people_to_look_for = [e.decode('utf-8') for e in args.email_addresses]
logging.debug("Will look for reviews that following contributors could " +
"review: {}".format(people_to_look_for))
logging.debug("Will email a report to: {}".format(args.email_report))
phab = init_phab_connection()
if args.update_cache:
update_cache(phab)
load_cache()
update_git_repos()
msg = print_most_recent_reviews(
phab,
days=1,
filter_reviewers=filter_reviewers_to_report_for(people_to_look_for))
if args.email_report != []:
send_emails(args.email_report, args.sender, msg)
if __name__ == "__main__":
main()
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/Reviewing/find_interesting_reviews.py |
#!/usr/bin/env python3
#
# ======- pre-push - LLVM Git Help Integration ---------*- python -*--========#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ==------------------------------------------------------------------------==#
"""
pre-push git hook integration
=============================
This script is intended to be setup as a pre-push hook, from the root of the
repo run:
ln -sf ../../llvm/utils/git/pre-push.py .git/hooks/pre-push
From the git doc:
The pre-push hook runs during git push, after the remote refs have been
updated but before any objects have been transferred. It receives the name
and location of the remote as parameters, and a list of to-be-updated refs
through stdin. You can use it to validate a set of ref updates before a push
occurs (a non-zero exit code will abort the push).
"""
import argparse
import collections
import os
import re
import shutil
import subprocess
import sys
import time
import getpass
from shlex import quote
VERBOSE = False
QUIET = False
dev_null_fd = None
z40 = '0000000000000000000000000000000000000000'
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def log(*args, **kwargs):
if QUIET:
return
print(*args, **kwargs)
def log_verbose(*args, **kwargs):
if not VERBOSE:
return
print(*args, **kwargs)
def die(msg):
eprint(msg)
sys.exit(1)
def ask_confirm(prompt):
while True:
query = input('%s (y/N): ' % (prompt))
if query.lower() not in ['y', 'n', '']:
print('Expect y or n!')
continue
return query.lower() == 'y'
def get_dev_null():
"""Lazily create a /dev/null fd for use in shell()"""
global dev_null_fd
if dev_null_fd is None:
dev_null_fd = open(os.devnull, 'w')
return dev_null_fd
def shell(cmd, strip=True, cwd=None, stdin=None, die_on_failure=True,
ignore_errors=False, text=True, print_raw_stderr=False):
# Escape args when logging for easy repro.
quoted_cmd = [quote(arg) for arg in cmd]
cwd_msg = ''
if cwd:
cwd_msg = ' in %s' % cwd
log_verbose('Running%s: %s' % (cwd_msg, ' '.join(quoted_cmd)))
err_pipe = subprocess.PIPE
if ignore_errors:
# Silence errors if requested.
err_pipe = get_dev_null()
start = time.time()
p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=err_pipe,
stdin=subprocess.PIPE,
universal_newlines=text)
stdout, stderr = p.communicate(input=stdin)
elapsed = time.time() - start
log_verbose('Command took %0.1fs' % elapsed)
if p.returncode == 0 or ignore_errors:
if stderr and not ignore_errors:
if not print_raw_stderr:
eprint('`%s` printed to stderr:' % ' '.join(quoted_cmd))
eprint(stderr.rstrip())
if strip:
if text:
stdout = stdout.rstrip('\r\n')
else:
stdout = stdout.rstrip(b'\r\n')
if VERBOSE:
for l in stdout.splitlines():
log_verbose('STDOUT: %s' % l)
return stdout
err_msg = '`%s` returned %s' % (' '.join(quoted_cmd), p.returncode)
eprint(err_msg)
if stderr:
eprint(stderr.rstrip())
if die_on_failure:
sys.exit(2)
raise RuntimeError(err_msg)
def git(*cmd, **kwargs):
return shell(['git'] + list(cmd), **kwargs)
def get_revs_to_push(range):
commits = git('rev-list', range).splitlines()
# Reverse the order so we print the oldest commit first
commits.reverse()
return commits
def handle_push(args, local_ref, local_sha, remote_ref, remote_sha):
'''Check a single push request (which can include multiple revisions)'''
log_verbose('Handle push, reproduce with '
'`echo %s %s %s %s | pre-push.py %s %s'
% (local_ref, local_sha, remote_ref, remote_sha, args.remote,
args.url))
# Handle request to delete
if local_sha == z40:
if not ask_confirm('Are you sure you want to delete "%s" on remote "%s"?' % (remote_ref, args.url)):
die("Aborting")
return
# Push a new branch
if remote_sha == z40:
if not ask_confirm('Are you sure you want to push a new branch/tag "%s" on remote "%s"?' % (remote_ref, args.url)):
die("Aborting")
range=local_sha
return
else:
# Update to existing branch, examine new commits
range='%s..%s' % (remote_sha, local_sha)
# Check that the remote commit exists, otherwise let git proceed
if "commit" not in git('cat-file','-t', remote_sha, ignore_errors=True):
return
revs = get_revs_to_push(range)
if not revs:
# This can happen if someone is force pushing an older revision to a branch
return
# Print the revision about to be pushed commits
print('Pushing to "%s" on remote "%s"' % (remote_ref, args.url))
for sha in revs:
print(' - ' + git('show', '--oneline', '--quiet', sha))
if len(revs) > 1:
if not ask_confirm('Are you sure you want to push %d commits?' % len(revs)):
die('Aborting')
for sha in revs:
msg = git('log', '--format=%B', '-n1', sha)
if 'Differential Revision' not in msg:
continue
for line in msg.splitlines():
for tag in ['Summary', 'Reviewers', 'Subscribers', 'Tags']:
if line.startswith(tag + ':'):
eprint('Please remove arcanist tags from the commit message (found "%s" tag in %s)' % (tag, sha[:12]))
if len(revs) == 1:
eprint('Try running: llvm/utils/git/arcfilter.sh')
die('Aborting (force push by adding "--no-verify")')
return
if __name__ == '__main__':
if not shutil.which('git'):
die('error: cannot find git command')
argv = sys.argv[1:]
p = argparse.ArgumentParser(
prog='pre-push', formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
verbosity_group = p.add_mutually_exclusive_group()
verbosity_group.add_argument('-q', '--quiet', action='store_true',
help='print less information')
verbosity_group.add_argument('-v', '--verbose', action='store_true',
help='print more information')
p.add_argument('remote', type=str, help='Name of the remote')
p.add_argument('url', type=str, help='URL for the remote')
args = p.parse_args(argv)
VERBOSE = args.verbose
QUIET = args.quiet
lines = sys.stdin.readlines()
sys.stdin = open('/dev/tty', 'r')
for line in lines:
local_ref, local_sha, remote_ref, remote_sha = line.split()
handle_push(args, local_ref, local_sha, remote_ref, remote_sha)
| MDL-SDK-master | src/mdl/jit/llvm/dist/utils/git/pre-push.py |
# -*- coding: utf-8 -*-
#
# LLVM documentation build configuration file.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from __future__ import print_function
import sys, os, re
from datetime import date
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.intersphinx', 'sphinx.ext.todo']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = {
'.rst': 'restructuredtext',
}
try:
import recommonmark
except ImportError:
# manpages do not use any .md sources
if not tags.has('builder-man'):
raise
else:
import sphinx
if sphinx.version_info >= (3, 0):
# This requires 0.5 or later.
extensions.append('recommonmark')
else:
source_parsers = {'.md': 'recommonmark.parser.CommonMarkParser'}
source_suffix['.md'] = 'markdown'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'LLVM'
copyright = u'2003-%d, LLVM Project' % date.today().year
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short version.
version = '12'
# The full version, including alpha/beta/rc tags.
release = '12'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%Y-%m-%d'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'friendly'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'llvm-theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = { "nosidebar": False }
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["_themes"]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%Y-%m-%d'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': [
'indexsidebar.html',
'sourcelink.html',
'searchbox.html',
]
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'LLVMdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'LLVM.tex', u'LLVM Documentation',
u'LLVM project', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = []
# Automatically derive the list of man pages from the contents of the command
# guide subdirectory.
basedir = os.path.dirname(__file__)
man_page_authors = "Maintained by the LLVM Team (https://llvm.org/)."
command_guide_subpath = 'CommandGuide'
command_guide_path = os.path.join(basedir, command_guide_subpath)
def process_md(name):
file_subpath = os.path.join(command_guide_subpath, name)
with open(os.path.join(command_guide_path, name)) as f:
title = f.readline().rstrip('\n')
m = re.match(r'^# (\S+) - (.+)$', title)
if m is None:
print("error: invalid title in %r "
"(expected '# <name> - <description>')" % file_subpath,
file=sys.stderr)
else:
man_pages.append((file_subpath.replace('.md',''), m.group(1),
m.group(2), man_page_authors, 1))
def process_rst(name):
file_subpath = os.path.join(command_guide_subpath, name)
with open(os.path.join(command_guide_path, name)) as f:
title = f.readline().rstrip('\n')
header = f.readline().rstrip('\n')
if len(header) != len(title):
print('error: invalid header in %r (does not match title)' %
file_subpath, file=sys.stderr)
if ' - ' not in title:
print("error: invalid title in %r "
"(expected '<name> - <description>')" % file_subpath,
file=sys.stderr)
# Split the name out of the title.
name,description = title.split(' - ', 1)
man_pages.append((file_subpath.replace('.rst',''), name,
description, man_page_authors, 1))
for name in os.listdir(command_guide_path):
# Process Markdown files
if name.endswith('.md'):
process_md(name)
# Process ReST files apart from the index page.
elif name.endswith('.rst') and name != 'index.rst':
process_rst(name)
# If true, show URL addresses after external links.
#man_show_urls = False
# FIXME: Define intersphinx configuration.
intersphinx_mapping = {}
# Pygment lexer are sometimes out of date (when parsing LLVM for example) or
# wrong. Suppress the warning so the build doesn't abort.
suppress_warnings = [ 'misc.highlighting_failure' ]
# Direct html-ified man pages to llvm.org
manpages_url = 'https://llvm.org/docs/CommandGuide/{page}.html'
| MDL-SDK-master | src/mdl/jit/llvm/dist/docs/conf.py |
#!/usr/bin/env python
from __future__ import print_function
class TimingScriptGenerator:
"""Used to generate a bash script which will invoke the toy and time it"""
def __init__(self, scriptname, outputname):
self.shfile = open(scriptname, 'w')
self.timeFile = outputname
self.shfile.write("echo \"\" > %s\n" % self.timeFile)
def writeTimingCall(self, irname, callname):
"""Echo some comments and invoke both versions of toy"""
rootname = irname
if '.' in irname:
rootname = irname[:irname.rfind('.')]
self.shfile.write("echo \"%s: Calls %s\" >> %s\n" % (callname, irname, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT again\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy -suppress-prompts -use-mcjit=false -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
class LibScriptGenerator:
"""Used to generate a bash script which will invoke the toy and time it"""
def __init__(self, filename):
self.shfile = open(filename, 'w')
def writeLibGenCall(self, libname, irname):
self.shfile.write("./toy -suppress-prompts -use-mcjit=false -dump-modules < %s 2> %s\n" % (libname, irname))
def splitScript(inputname, libGenScript, timingScript):
rootname = inputname[:-2]
libname = rootname + "-lib.k"
irname = rootname + "-lib.ir"
callname = rootname + "-call.k"
infile = open(inputname, "r")
libfile = open(libname, "w")
callfile = open(callname, "w")
print("Splitting %s into %s and %s" % (inputname, callname, libname))
for line in infile:
if not line.startswith("#"):
if line.startswith("print"):
callfile.write(line)
else:
libfile.write(line)
libGenScript.writeLibGenCall(libname, irname)
timingScript.writeTimingCall(irname, callname)
# Execution begins here
libGenScript = LibScriptGenerator("make-libs.sh")
timingScript = TimingScriptGenerator("time-lib.sh", "lib-timing.txt")
script_list = ["test-5000-3-50-50.k", "test-5000-10-100-10.k", "test-5000-10-5-10.k", "test-5000-10-1-0.k",
"test-1000-3-10-50.k", "test-1000-10-100-10.k", "test-1000-10-5-10.k", "test-1000-10-1-0.k",
"test-200-3-2-50.k", "test-200-10-40-10.k", "test-200-10-2-10.k", "test-200-10-1-0.k"]
for script in script_list:
splitScript(script, libGenScript, timingScript)
print("All done!")
| MDL-SDK-master | src/mdl/jit/llvm/dist/examples/Kaleidoscope/MCJIT/complete/split-lib.py |
#!/usr/bin/env python
from __future__ import print_function
import sys
import random
class TimingScriptGenerator:
"""Used to generate a bash script which will invoke the toy and time it"""
def __init__(self, scriptname, outputname):
self.timeFile = outputname
self.shfile = open(scriptname, 'w')
self.shfile.write("echo \"\" > %s\n" % self.timeFile)
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls):
"""Echo some comments and invoke both versions of toy"""
rootname = filename
if '.' in filename:
rootname = filename[:filename.rfind('.')]
self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT (original)\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=false < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT (lazy)\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy -suppress-prompts -use-mcjit=true -enable-lazy-compilation=true < %s > %s-mcjit-lazy.out 2> %s-mcjit-lazy.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy -suppress-prompts -use-mcjit=false < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
class KScriptGenerator:
"""Used to generate random Kaleidoscope code"""
def __init__(self, filename):
self.kfile = open(filename, 'w')
self.nextFuncNum = 1
self.lastFuncNum = None
self.callWeighting = 0.1
# A mapping of calls within functions with no duplicates
self.calledFunctionTable = {}
# A list of function calls which will actually be executed
self.calledFunctions = []
# A comprehensive mapping of calls within functions
# used for computing the total number of calls
self.comprehensiveCalledFunctionTable = {}
self.totalCallsExecuted = 0
def updateTotalCallCount(self, callee):
# Count this call
self.totalCallsExecuted += 1
# Then count all the functions it calls
if callee in self.comprehensiveCalledFunctionTable:
for child in self.comprehensiveCalledFunctionTable[callee]:
self.updateTotalCallCount(child)
def updateFunctionCallMap(self, caller, callee):
"""Maintains a map of functions that are called from other functions"""
if not caller in self.calledFunctionTable:
self.calledFunctionTable[caller] = []
if not callee in self.calledFunctionTable[caller]:
self.calledFunctionTable[caller].append(callee)
if not caller in self.comprehensiveCalledFunctionTable:
self.comprehensiveCalledFunctionTable[caller] = []
self.comprehensiveCalledFunctionTable[caller].append(callee)
def updateCalledFunctionList(self, callee):
"""Maintains a list of functions that will actually be called"""
# Update the total call count
self.updateTotalCallCount(callee)
# If this function is already in the list, don't do anything else
if callee in self.calledFunctions:
return
# Add this function to the list of those that will be called.
self.calledFunctions.append(callee)
# If this function calls other functions, add them too
if callee in self.calledFunctionTable:
for subCallee in self.calledFunctionTable[callee]:
self.updateCalledFunctionList(subCallee)
def setCallWeighting(self, weight):
""" Sets the probably of generating a function call"""
self.callWeighting = weight
def writeln(self, line):
self.kfile.write(line + '\n')
def writeComment(self, comment):
self.writeln('# ' + comment)
def writeEmptyLine(self):
self.writeln("")
def writePredefinedFunctions(self):
self.writeComment("Define ':' for sequencing: as a low-precedence operator that ignores operands")
self.writeComment("and just returns the RHS.")
self.writeln("def binary : 1 (x y) y;")
self.writeEmptyLine()
self.writeComment("Helper functions defined within toy")
self.writeln("extern putchard(x);")
self.writeln("extern printd(d);")
self.writeln("extern printlf();")
self.writeEmptyLine()
self.writeComment("Print the result of a function call")
self.writeln("def printresult(N Result)")
self.writeln(" # 'result('")
self.writeln(" putchard(114) : putchard(101) : putchard(115) : putchard(117) : putchard(108) : putchard(116) : putchard(40) :")
self.writeln(" printd(N) :");
self.writeln(" # ') = '")
self.writeln(" putchard(41) : putchard(32) : putchard(61) : putchard(32) :")
self.writeln(" printd(Result) :");
self.writeln(" printlf();")
self.writeEmptyLine()
def writeRandomOperation(self, LValue, LHS, RHS):
shouldCallFunc = (self.lastFuncNum > 2 and random.random() < self.callWeighting)
if shouldCallFunc:
funcToCall = random.randrange(1, self.lastFuncNum - 1)
self.updateFunctionCallMap(self.lastFuncNum, funcToCall)
self.writeln(" %s = func%d(%s, %s) :" % (LValue, funcToCall, LHS, RHS))
else:
possibleOperations = ["+", "-", "*", "/"]
operation = random.choice(possibleOperations)
if operation == "-":
# Don't let our intermediate value become zero
# This is complicated by the fact that '<' is our only comparison operator
self.writeln(" if %s < %s then" % (LHS, RHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else if %s < %s then" % (RHS, LHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else")
self.writeln(" %s = %s %s %f :" % (LValue, LHS, operation, random.uniform(1, 100)))
else:
self.writeln(" %s = %s %s %s :" % (LValue, LHS, operation, RHS))
def getNextFuncNum(self):
result = self.nextFuncNum
self.nextFuncNum += 1
self.lastFuncNum = result
return result
def writeFunction(self, elements):
funcNum = self.getNextFuncNum()
self.writeComment("Auto-generated function number %d" % funcNum)
self.writeln("def func%d(X Y)" % funcNum)
self.writeln(" var temp1 = X,")
self.writeln(" temp2 = Y,")
self.writeln(" temp3 in")
# Initialize the variable names to be rotated
first = "temp3"
second = "temp1"
third = "temp2"
# Write some random operations
for i in range(elements):
self.writeRandomOperation(first, second, third)
# Rotate the variables
temp = first
first = second
second = third
third = temp
self.writeln(" " + third + ";")
self.writeEmptyLine()
def writeFunctionCall(self):
self.writeComment("Call the last function")
arg1 = random.uniform(1, 100)
arg2 = random.uniform(1, 100)
self.writeln("printresult(%d, func%d(%f, %f) )" % (self.lastFuncNum, self.lastFuncNum, arg1, arg2))
self.writeEmptyLine()
self.updateCalledFunctionList(self.lastFuncNum)
def writeFinalFunctionCounts(self):
self.writeComment("Called %d of %d functions" % (len(self.calledFunctions), self.lastFuncNum))
def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript):
""" Generate a random Kaleidoscope script based on the given parameters """
print("Generating " + filename)
print(" %d functions, %d elements per function, %d functions between execution" %
(numFuncs, elementsPerFunc, funcsBetweenExec))
print(" Call weighting = %f" % callWeighting)
script = KScriptGenerator(filename)
script.setCallWeighting(callWeighting)
script.writeComment("===========================================================================")
script.writeComment("Auto-generated script")
script.writeComment(" %d functions, %d elements per function, %d functions between execution"
% (numFuncs, elementsPerFunc, funcsBetweenExec))
script.writeComment(" call weighting = %f" % callWeighting)
script.writeComment("===========================================================================")
script.writeEmptyLine()
script.writePredefinedFunctions()
funcsSinceLastExec = 0
for i in range(numFuncs):
script.writeFunction(elementsPerFunc)
funcsSinceLastExec += 1
if funcsSinceLastExec == funcsBetweenExec:
script.writeFunctionCall()
funcsSinceLastExec = 0
# Always end with a function call
if funcsSinceLastExec > 0:
script.writeFunctionCall()
script.writeEmptyLine()
script.writeFinalFunctionCounts()
funcsCalled = len(script.calledFunctions)
print(" Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted))
timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted)
# Execution begins here
random.seed()
timingScript = TimingScriptGenerator("time-toy.sh", "timing-data.txt")
dataSets = [(5000, 3, 50, 0.50), (5000, 10, 100, 0.10), (5000, 10, 5, 0.10), (5000, 10, 1, 0.0),
(1000, 3, 10, 0.50), (1000, 10, 100, 0.10), (1000, 10, 5, 0.10), (1000, 10, 1, 0.0),
( 200, 3, 2, 0.50), ( 200, 10, 40, 0.10), ( 200, 10, 2, 0.10), ( 200, 10, 1, 0.0)]
# Generate the code
for (numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting) in dataSets:
filename = "test-%d-%d-%d-%d.k" % (numFuncs, elementsPerFunc, funcsBetweenExec, int(callWeighting * 100))
generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript)
print("All done!")
| MDL-SDK-master | src/mdl/jit/llvm/dist/examples/Kaleidoscope/MCJIT/complete/genk-timing.py |
#!/usr/bin/env python
from __future__ import print_function
class TimingScriptGenerator:
"""Used to generate a bash script which will invoke the toy and time it"""
def __init__(self, scriptname, outputname):
self.shfile = open(scriptname, 'w')
self.timeFile = outputname
self.shfile.write("echo \"\" > %s\n" % self.timeFile)
def writeTimingCall(self, irname, callname):
"""Echo some comments and invoke both versions of toy"""
rootname = irname
if '.' in irname:
rootname = irname[:irname.rfind('.')]
self.shfile.write("echo \"%s: Calls %s\" >> %s\n" % (callname, irname, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT again\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-jit -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
class LibScriptGenerator:
"""Used to generate a bash script which will convert Kaleidoscope files to IR"""
def __init__(self, filename):
self.shfile = open(filename, 'w')
def writeLibGenCall(self, libname, irname):
self.shfile.write("./toy-ir-gen < %s 2> %s\n" % (libname, irname))
def splitScript(inputname, libGenScript, timingScript):
rootname = inputname[:-2]
libname = rootname + "-lib.k"
irname = rootname + "-lib.ir"
callname = rootname + "-call.k"
infile = open(inputname, "r")
libfile = open(libname, "w")
callfile = open(callname, "w")
print("Splitting %s into %s and %s" % (inputname, callname, libname))
for line in infile:
if not line.startswith("#"):
if line.startswith("print"):
callfile.write(line)
else:
libfile.write(line)
libGenScript.writeLibGenCall(libname, irname)
timingScript.writeTimingCall(irname, callname)
# Execution begins here
libGenScript = LibScriptGenerator("make-libs.sh")
timingScript = TimingScriptGenerator("time-lib.sh", "lib-timing.txt")
script_list = ["test-5000-3-50-50.k", "test-5000-10-100-10.k", "test-5000-10-5-10.k", "test-5000-10-1-0.k",
"test-1000-3-10-50.k", "test-1000-10-100-10.k", "test-1000-10-5-10.k", "test-1000-10-1-0.k",
"test-200-3-2-50.k", "test-200-10-40-10.k", "test-200-10-2-10.k", "test-200-10-1-0.k"]
for script in script_list:
splitScript(script, libGenScript, timingScript)
print("All done!")
| MDL-SDK-master | src/mdl/jit/llvm/dist/examples/Kaleidoscope/MCJIT/cached/split-lib.py |
#!/usr/bin/env python
from __future__ import print_function
import sys
import random
class TimingScriptGenerator:
"""Used to generate a bash script which will invoke the toy and time it"""
def __init__(self, scriptname, outputname):
self.timeFile = outputname
self.shfile = open(scriptname, 'w')
self.shfile.write("echo \"\" > %s\n" % self.timeFile)
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls):
"""Echo some comments and invoke both versions of toy"""
rootname = filename
if '.' in filename:
rootname = filename[:filename.rfind('.')]
self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-jit < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
class KScriptGenerator:
"""Used to generate random Kaleidoscope code"""
def __init__(self, filename):
self.kfile = open(filename, 'w')
self.nextFuncNum = 1
self.lastFuncNum = None
self.callWeighting = 0.1
# A mapping of calls within functions with no duplicates
self.calledFunctionTable = {}
# A list of function calls which will actually be executed
self.calledFunctions = []
# A comprehensive mapping of calls within functions
# used for computing the total number of calls
self.comprehensiveCalledFunctionTable = {}
self.totalCallsExecuted = 0
def updateTotalCallCount(self, callee):
# Count this call
self.totalCallsExecuted += 1
# Then count all the functions it calls
if callee in self.comprehensiveCalledFunctionTable:
for child in self.comprehensiveCalledFunctionTable[callee]:
self.updateTotalCallCount(child)
def updateFunctionCallMap(self, caller, callee):
"""Maintains a map of functions that are called from other functions"""
if not caller in self.calledFunctionTable:
self.calledFunctionTable[caller] = []
if not callee in self.calledFunctionTable[caller]:
self.calledFunctionTable[caller].append(callee)
if not caller in self.comprehensiveCalledFunctionTable:
self.comprehensiveCalledFunctionTable[caller] = []
self.comprehensiveCalledFunctionTable[caller].append(callee)
def updateCalledFunctionList(self, callee):
"""Maintains a list of functions that will actually be called"""
# Update the total call count
self.updateTotalCallCount(callee)
# If this function is already in the list, don't do anything else
if callee in self.calledFunctions:
return
# Add this function to the list of those that will be called.
self.calledFunctions.append(callee)
# If this function calls other functions, add them too
if callee in self.calledFunctionTable:
for subCallee in self.calledFunctionTable[callee]:
self.updateCalledFunctionList(subCallee)
def setCallWeighting(self, weight):
""" Sets the probably of generating a function call"""
self.callWeighting = weight
def writeln(self, line):
self.kfile.write(line + '\n')
def writeComment(self, comment):
self.writeln('# ' + comment)
def writeEmptyLine(self):
self.writeln("")
def writePredefinedFunctions(self):
self.writeComment("Define ':' for sequencing: as a low-precedence operator that ignores operands")
self.writeComment("and just returns the RHS.")
self.writeln("def binary : 1 (x y) y;")
self.writeEmptyLine()
self.writeComment("Helper functions defined within toy")
self.writeln("extern putchard(x);")
self.writeln("extern printd(d);")
self.writeln("extern printlf();")
self.writeEmptyLine()
self.writeComment("Print the result of a function call")
self.writeln("def printresult(N Result)")
self.writeln(" # 'result('")
self.writeln(" putchard(114) : putchard(101) : putchard(115) : putchard(117) : putchard(108) : putchard(116) : putchard(40) :")
self.writeln(" printd(N) :");
self.writeln(" # ') = '")
self.writeln(" putchard(41) : putchard(32) : putchard(61) : putchard(32) :")
self.writeln(" printd(Result) :");
self.writeln(" printlf();")
self.writeEmptyLine()
def writeRandomOperation(self, LValue, LHS, RHS):
shouldCallFunc = (self.lastFuncNum > 2 and random.random() < self.callWeighting)
if shouldCallFunc:
funcToCall = random.randrange(1, self.lastFuncNum - 1)
self.updateFunctionCallMap(self.lastFuncNum, funcToCall)
self.writeln(" %s = func%d(%s, %s) :" % (LValue, funcToCall, LHS, RHS))
else:
possibleOperations = ["+", "-", "*", "/"]
operation = random.choice(possibleOperations)
if operation == "-":
# Don't let our intermediate value become zero
# This is complicated by the fact that '<' is our only comparison operator
self.writeln(" if %s < %s then" % (LHS, RHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else if %s < %s then" % (RHS, LHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else")
self.writeln(" %s = %s %s %f :" % (LValue, LHS, operation, random.uniform(1, 100)))
else:
self.writeln(" %s = %s %s %s :" % (LValue, LHS, operation, RHS))
def getNextFuncNum(self):
result = self.nextFuncNum
self.nextFuncNum += 1
self.lastFuncNum = result
return result
def writeFunction(self, elements):
funcNum = self.getNextFuncNum()
self.writeComment("Auto-generated function number %d" % funcNum)
self.writeln("def func%d(X Y)" % funcNum)
self.writeln(" var temp1 = X,")
self.writeln(" temp2 = Y,")
self.writeln(" temp3 in")
# Initialize the variable names to be rotated
first = "temp3"
second = "temp1"
third = "temp2"
# Write some random operations
for i in range(elements):
self.writeRandomOperation(first, second, third)
# Rotate the variables
temp = first
first = second
second = third
third = temp
self.writeln(" " + third + ";")
self.writeEmptyLine()
def writeFunctionCall(self):
self.writeComment("Call the last function")
arg1 = random.uniform(1, 100)
arg2 = random.uniform(1, 100)
self.writeln("printresult(%d, func%d(%f, %f) )" % (self.lastFuncNum, self.lastFuncNum, arg1, arg2))
self.writeEmptyLine()
self.updateCalledFunctionList(self.lastFuncNum)
def writeFinalFunctionCounts(self):
self.writeComment("Called %d of %d functions" % (len(self.calledFunctions), self.lastFuncNum))
def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript):
""" Generate a random Kaleidoscope script based on the given parameters """
print("Generating " + filename)
print(" %d functions, %d elements per function, %d functions between execution" %
(numFuncs, elementsPerFunc, funcsBetweenExec))
print(" Call weighting = %f" % callWeighting)
script = KScriptGenerator(filename)
script.setCallWeighting(callWeighting)
script.writeComment("===========================================================================")
script.writeComment("Auto-generated script")
script.writeComment(" %d functions, %d elements per function, %d functions between execution"
% (numFuncs, elementsPerFunc, funcsBetweenExec))
script.writeComment(" call weighting = %f" % callWeighting)
script.writeComment("===========================================================================")
script.writeEmptyLine()
script.writePredefinedFunctions()
funcsSinceLastExec = 0
for i in range(numFuncs):
script.writeFunction(elementsPerFunc)
funcsSinceLastExec += 1
if funcsSinceLastExec == funcsBetweenExec:
script.writeFunctionCall()
funcsSinceLastExec = 0
# Always end with a function call
if funcsSinceLastExec > 0:
script.writeFunctionCall()
script.writeEmptyLine()
script.writeFinalFunctionCounts()
funcsCalled = len(script.calledFunctions)
print(" Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted))
timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted)
# Execution begins here
random.seed()
timingScript = TimingScriptGenerator("time-toy.sh", "timing-data.txt")
dataSets = [(5000, 3, 50, 0.50), (5000, 10, 100, 0.10), (5000, 10, 5, 0.10), (5000, 10, 1, 0.0),
(1000, 3, 10, 0.50), (1000, 10, 100, 0.10), (1000, 10, 5, 0.10), (1000, 10, 1, 0.0),
( 200, 3, 2, 0.50), ( 200, 10, 40, 0.10), ( 200, 10, 2, 0.10), ( 200, 10, 1, 0.0)]
# Generate the code
for (numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting) in dataSets:
filename = "test-%d-%d-%d-%d.k" % (numFuncs, elementsPerFunc, funcsBetweenExec, int(callWeighting * 100))
generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript)
print("All done!")
| MDL-SDK-master | src/mdl/jit/llvm/dist/examples/Kaleidoscope/MCJIT/cached/genk-timing.py |
#!/usr/bin/env python
from __future__ import print_function
import sys
import random
class TimingScriptGenerator:
"""Used to generate a bash script which will invoke the toy and time it"""
def __init__(self, scriptname, outputname):
self.timeFile = outputname
self.shfile = open(scriptname, 'w')
self.shfile.write("echo \"\" > %s\n" % self.timeFile)
def writeTimingCall(self, filename, numFuncs, funcsCalled, totalCalls):
"""Echo some comments and invoke both versions of toy"""
rootname = filename
if '.' in filename:
rootname = filename[:filename.rfind('.')]
self.shfile.write("echo \"%s: Calls %d of %d functions, %d total\" >> %s\n" % (filename, funcsCalled, numFuncs, totalCalls, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-jit < %s > %s-jit.out 2> %s-jit.err\n" % (filename, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
class KScriptGenerator:
"""Used to generate random Kaleidoscope code"""
def __init__(self, filename):
self.kfile = open(filename, 'w')
self.nextFuncNum = 1
self.lastFuncNum = None
self.callWeighting = 0.1
# A mapping of calls within functions with no duplicates
self.calledFunctionTable = {}
# A list of function calls which will actually be executed
self.calledFunctions = []
# A comprehensive mapping of calls within functions
# used for computing the total number of calls
self.comprehensiveCalledFunctionTable = {}
self.totalCallsExecuted = 0
def updateTotalCallCount(self, callee):
# Count this call
self.totalCallsExecuted += 1
# Then count all the functions it calls
if callee in self.comprehensiveCalledFunctionTable:
for child in self.comprehensiveCalledFunctionTable[callee]:
self.updateTotalCallCount(child)
def updateFunctionCallMap(self, caller, callee):
"""Maintains a map of functions that are called from other functions"""
if not caller in self.calledFunctionTable:
self.calledFunctionTable[caller] = []
if not callee in self.calledFunctionTable[caller]:
self.calledFunctionTable[caller].append(callee)
if not caller in self.comprehensiveCalledFunctionTable:
self.comprehensiveCalledFunctionTable[caller] = []
self.comprehensiveCalledFunctionTable[caller].append(callee)
def updateCalledFunctionList(self, callee):
"""Maintains a list of functions that will actually be called"""
# Update the total call count
self.updateTotalCallCount(callee)
# If this function is already in the list, don't do anything else
if callee in self.calledFunctions:
return
# Add this function to the list of those that will be called.
self.calledFunctions.append(callee)
# If this function calls other functions, add them too
if callee in self.calledFunctionTable:
for subCallee in self.calledFunctionTable[callee]:
self.updateCalledFunctionList(subCallee)
def setCallWeighting(self, weight):
""" Sets the probably of generating a function call"""
self.callWeighting = weight
def writeln(self, line):
self.kfile.write(line + '\n')
def writeComment(self, comment):
self.writeln('# ' + comment)
def writeEmptyLine(self):
self.writeln("")
def writePredefinedFunctions(self):
self.writeComment("Define ':' for sequencing: as a low-precedence operator that ignores operands")
self.writeComment("and just returns the RHS.")
self.writeln("def binary : 1 (x y) y;")
self.writeEmptyLine()
self.writeComment("Helper functions defined within toy")
self.writeln("extern putchard(x);")
self.writeln("extern printd(d);")
self.writeln("extern printlf();")
self.writeEmptyLine()
self.writeComment("Print the result of a function call")
self.writeln("def printresult(N Result)")
self.writeln(" # 'result('")
self.writeln(" putchard(114) : putchard(101) : putchard(115) : putchard(117) : putchard(108) : putchard(116) : putchard(40) :")
self.writeln(" printd(N) :");
self.writeln(" # ') = '")
self.writeln(" putchard(41) : putchard(32) : putchard(61) : putchard(32) :")
self.writeln(" printd(Result) :");
self.writeln(" printlf();")
self.writeEmptyLine()
def writeRandomOperation(self, LValue, LHS, RHS):
shouldCallFunc = (self.lastFuncNum > 2 and random.random() < self.callWeighting)
if shouldCallFunc:
funcToCall = random.randrange(1, self.lastFuncNum - 1)
self.updateFunctionCallMap(self.lastFuncNum, funcToCall)
self.writeln(" %s = func%d(%s, %s) :" % (LValue, funcToCall, LHS, RHS))
else:
possibleOperations = ["+", "-", "*", "/"]
operation = random.choice(possibleOperations)
if operation == "-":
# Don't let our intermediate value become zero
# This is complicated by the fact that '<' is our only comparison operator
self.writeln(" if %s < %s then" % (LHS, RHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else if %s < %s then" % (RHS, LHS))
self.writeln(" %s = %s %s %s" % (LValue, LHS, operation, RHS))
self.writeln(" else")
self.writeln(" %s = %s %s %f :" % (LValue, LHS, operation, random.uniform(1, 100)))
else:
self.writeln(" %s = %s %s %s :" % (LValue, LHS, operation, RHS))
def getNextFuncNum(self):
result = self.nextFuncNum
self.nextFuncNum += 1
self.lastFuncNum = result
return result
def writeFunction(self, elements):
funcNum = self.getNextFuncNum()
self.writeComment("Auto-generated function number %d" % funcNum)
self.writeln("def func%d(X Y)" % funcNum)
self.writeln(" var temp1 = X,")
self.writeln(" temp2 = Y,")
self.writeln(" temp3 in")
# Initialize the variable names to be rotated
first = "temp3"
second = "temp1"
third = "temp2"
# Write some random operations
for i in range(elements):
self.writeRandomOperation(first, second, third)
# Rotate the variables
temp = first
first = second
second = third
third = temp
self.writeln(" " + third + ";")
self.writeEmptyLine()
def writeFunctionCall(self):
self.writeComment("Call the last function")
arg1 = random.uniform(1, 100)
arg2 = random.uniform(1, 100)
self.writeln("printresult(%d, func%d(%f, %f) )" % (self.lastFuncNum, self.lastFuncNum, arg1, arg2))
self.writeEmptyLine()
self.updateCalledFunctionList(self.lastFuncNum)
def writeFinalFunctionCounts(self):
self.writeComment("Called %d of %d functions" % (len(self.calledFunctions), self.lastFuncNum))
def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript):
""" Generate a random Kaleidoscope script based on the given parameters """
print("Generating " + filename)
print(" %d functions, %d elements per function, %d functions between execution" %
(numFuncs, elementsPerFunc, funcsBetweenExec))
print(" Call weighting = %f" % callWeighting)
script = KScriptGenerator(filename)
script.setCallWeighting(callWeighting)
script.writeComment("===========================================================================")
script.writeComment("Auto-generated script")
script.writeComment(" %d functions, %d elements per function, %d functions between execution"
% (numFuncs, elementsPerFunc, funcsBetweenExec))
script.writeComment(" call weighting = %f" % callWeighting)
script.writeComment("===========================================================================")
script.writeEmptyLine()
script.writePredefinedFunctions()
funcsSinceLastExec = 0
for i in range(numFuncs):
script.writeFunction(elementsPerFunc)
funcsSinceLastExec += 1
if funcsSinceLastExec == funcsBetweenExec:
script.writeFunctionCall()
funcsSinceLastExec = 0
# Always end with a function call
if funcsSinceLastExec > 0:
script.writeFunctionCall()
script.writeEmptyLine()
script.writeFinalFunctionCounts()
funcsCalled = len(script.calledFunctions)
print(" Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted))
timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted)
# Execution begins here
random.seed()
timingScript = TimingScriptGenerator("time-toy.sh", "timing-data.txt")
dataSets = [(5000, 3, 50, 0.50), (5000, 10, 100, 0.10), (5000, 10, 5, 0.10), (5000, 10, 1, 0.0),
(1000, 3, 10, 0.50), (1000, 10, 100, 0.10), (1000, 10, 5, 0.10), (1000, 10, 1, 0.0),
( 200, 3, 2, 0.50), ( 200, 10, 40, 0.10), ( 200, 10, 2, 0.10), ( 200, 10, 1, 0.0)]
# Generate the code
for (numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting) in dataSets:
filename = "test-%d-%d-%d-%d.k" % (numFuncs, elementsPerFunc, funcsBetweenExec, int(callWeighting * 100))
generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript)
print("All done!")
| MDL-SDK-master | src/mdl/jit/llvm/dist/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py |
#===- object.py - Python Object Bindings --------------------*- python -*--===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===------------------------------------------------------------------------===#
r"""
Object File Interface
=====================
This module provides an interface for reading information from object files
(e.g. binary executables and libraries).
Using this module, you can obtain information about an object file's sections,
symbols, and relocations. These are represented by the classes ObjectFile,
Section, Symbol, and Relocation, respectively.
Usage
-----
The only way to use this module is to start by creating an ObjectFile. You can
create an ObjectFile by loading a file (specified by its path) or by creating a
llvm.core.MemoryBuffer and loading that.
Once you have an object file, you can inspect its sections and symbols directly
by calling get_sections() and get_symbols() respectively. To inspect
relocations, call get_relocations() on a Section instance.
Iterator Interface
------------------
The LLVM bindings expose iteration over sections, symbols, and relocations in a
way that only allows one instance to be operated on at a single time. This is
slightly annoying from a Python perspective, as it isn't very Pythonic to have
objects that "expire" but are still active from a dynamic language.
To aid working around this limitation, each Section, Symbol, and Relocation
instance caches its properties after first access. So, if the underlying
iterator is advanced, the properties can still be obtained provided they have
already been retrieved.
In addition, we also provide a "cache" method on each class to cache all
available data. You can call this on each obtained instance. Or, you can pass
cache=True to the appropriate get_XXX() method to have this done for you.
Here are some examples on how to perform iteration:
obj = ObjectFile(filename='/bin/ls')
# This is OK. Each Section is only accessed inside its own iteration slot.
section_names = []
for section in obj.get_sections():
section_names.append(section.name)
# This is NOT OK. You perform a lookup after the object has expired.
symbols = list(obj.get_symbols())
for symbol in symbols:
print symbol.name # This raises because the object has expired.
# In this example, we mix a working and failing scenario.
symbols = []
for symbol in obj.get_symbols():
symbols.append(symbol)
print symbol.name
for symbol in symbols:
print symbol.name # OK
print symbol.address # NOT OK. We didn't look up this property before.
# Cache everything up front.
symbols = list(obj.get_symbols(cache=True))
for symbol in symbols:
print symbol.name # OK
"""
from ctypes import c_char_p
from ctypes import c_char
from ctypes import POINTER
from ctypes import c_uint64
from ctypes import string_at
from .common import CachedProperty
from .common import LLVMObject
from .common import c_object_p
from .common import get_library
from .core import MemoryBuffer
__all__ = [
"lib",
"ObjectFile",
"Relocation",
"Section",
"Symbol",
]
class ObjectFile(LLVMObject):
"""Represents an object/binary file."""
def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data.
filename must be a path to a file that can be opened with open().
contents can be either a native Python buffer type (like str) or a
llvm.core.MemoryBuffer instance.
"""
if contents:
assert isinstance(contents, MemoryBuffer)
if filename is not None:
contents = MemoryBuffer(filename=filename)
if contents is None:
raise Exception('No input found.')
ptr = lib.LLVMCreateObjectFile(contents)
LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisposeObjectFile)
self.take_ownership(contents)
def get_sections(self, cache=False):
"""Obtain the sections in this object file.
This is a generator for llvm.object.Section instances.
Sections are exposed as limited-use objects. See the module's
documentation on iterators for more.
"""
sections = lib.LLVMGetSections(self)
last = None
while True:
if lib.LLVMIsSectionIteratorAtEnd(self, sections):
break
last = Section(sections)
if cache:
last.cache()
yield last
lib.LLVMMoveToNextSection(sections)
last.expire()
if last is not None:
last.expire()
lib.LLVMDisposeSectionIterator(sections)
def get_symbols(self, cache=False):
"""Obtain the symbols in this object file.
This is a generator for llvm.object.Symbol instances.
Each Symbol instance is a limited-use object. See this module's
documentation on iterators for more.
"""
symbols = lib.LLVMGetSymbols(self)
last = None
while True:
if lib.LLVMIsSymbolIteratorAtEnd(self, symbols):
break
last = Symbol(symbols, self)
if cache:
last.cache()
yield last
lib.LLVMMoveToNextSymbol(symbols)
last.expire()
if last is not None:
last.expire()
lib.LLVMDisposeSymbolIterator(symbols)
class Section(LLVMObject):
"""Represents a section in an object file."""
def __init__(self, ptr):
"""Construct a new section instance.
Section instances can currently only be created from an ObjectFile
instance. Therefore, this constructor should not be used outside of
this module.
"""
LLVMObject.__init__(self, ptr)
self.expired = False
@CachedProperty
def name(self):
"""Obtain the string name of the section.
This is typically something like '.dynsym' or '.rodata'.
"""
if self.expired:
raise Exception('Section instance has expired.')
return lib.LLVMGetSectionName(self)
@CachedProperty
def size(self):
"""The size of the section, in long bytes."""
if self.expired:
raise Exception('Section instance has expired.')
return lib.LLVMGetSectionSize(self)
@CachedProperty
def contents(self):
if self.expired:
raise Exception('Section instance has expired.')
siz = self.size
r = lib.LLVMGetSectionContents(self)
if r:
return string_at(r, siz)
return None
@CachedProperty
def address(self):
"""The address of this section, in long bytes."""
if self.expired:
raise Exception('Section instance has expired.')
return lib.LLVMGetSectionAddress(self)
def has_symbol(self, symbol):
"""Returns whether a Symbol instance is present in this Section."""
if self.expired:
raise Exception('Section instance has expired.')
assert isinstance(symbol, Symbol)
return lib.LLVMGetSectionContainsSymbol(self, symbol)
def get_relocations(self, cache=False):
"""Obtain the relocations in this Section.
This is a generator for llvm.object.Relocation instances.
Each instance is a limited used object. See this module's documentation
on iterators for more.
"""
if self.expired:
raise Exception('Section instance has expired.')
relocations = lib.LLVMGetRelocations(self)
last = None
while True:
if lib.LLVMIsRelocationIteratorAtEnd(self, relocations):
break
last = Relocation(relocations)
if cache:
last.cache()
yield last
lib.LLVMMoveToNextRelocation(relocations)
last.expire()
if last is not None:
last.expire()
lib.LLVMDisposeRelocationIterator(relocations)
def cache(self):
"""Cache properties of this Section.
This can be called as a workaround to the single active Section
limitation. When called, the properties of the Section are fetched so
they are still available after the Section has been marked inactive.
"""
getattr(self, 'name')
getattr(self, 'size')
getattr(self, 'contents')
getattr(self, 'address')
def expire(self):
"""Expire the section.
This is called internally by the section iterator.
"""
self.expired = True
class Symbol(LLVMObject):
"""Represents a symbol in an object file."""
def __init__(self, ptr, object_file):
assert isinstance(ptr, c_object_p)
assert isinstance(object_file, ObjectFile)
LLVMObject.__init__(self, ptr)
self.expired = False
self._object_file = object_file
@CachedProperty
def name(self):
"""The str name of the symbol.
This is often a function or variable name. Keep in mind that name
mangling could be in effect.
"""
if self.expired:
raise Exception('Symbol instance has expired.')
return lib.LLVMGetSymbolName(self)
@CachedProperty
def address(self):
"""The address of this symbol, in long bytes."""
if self.expired:
raise Exception('Symbol instance has expired.')
return lib.LLVMGetSymbolAddress(self)
@CachedProperty
def size(self):
"""The size of the symbol, in long bytes."""
if self.expired:
raise Exception('Symbol instance has expired.')
return lib.LLVMGetSymbolSize(self)
@CachedProperty
def section(self):
"""The Section to which this Symbol belongs.
The returned Section instance does not expire, unlike Sections that are
commonly obtained through iteration.
Because this obtains a new section iterator each time it is accessed,
calling this on a number of Symbol instances could be expensive.
"""
sections = lib.LLVMGetSections(self._object_file)
lib.LLVMMoveToContainingSection(sections, self)
return Section(sections)
def cache(self):
"""Cache all cacheable properties."""
getattr(self, 'name')
getattr(self, 'address')
getattr(self, 'size')
def expire(self):
"""Mark the object as expired to prevent future API accesses.
This is called internally by this module and it is unlikely that
external callers have a legitimate reason for using it.
"""
self.expired = True
class Relocation(LLVMObject):
"""Represents a relocation definition."""
def __init__(self, ptr):
"""Create a new relocation instance.
Relocations are created from objects derived from Section instances.
Therefore, this constructor should not be called outside of this
module. See Section.get_relocations() for the proper method to obtain
a Relocation instance.
"""
assert isinstance(ptr, c_object_p)
LLVMObject.__init__(self, ptr)
self.expired = False
@CachedProperty
def offset(self):
"""The offset of this relocation, in long bytes."""
if self.expired:
raise Exception('Relocation instance has expired.')
return lib.LLVMGetRelocationOffset(self)
@CachedProperty
def symbol(self):
"""The Symbol corresponding to this Relocation."""
if self.expired:
raise Exception('Relocation instance has expired.')
ptr = lib.LLVMGetRelocationSymbol(self)
return Symbol(ptr)
@CachedProperty
def type_number(self):
"""The relocation type, as a long."""
if self.expired:
raise Exception('Relocation instance has expired.')
return lib.LLVMGetRelocationType(self)
@CachedProperty
def type_name(self):
"""The relocation type's name, as a str."""
if self.expired:
raise Exception('Relocation instance has expired.')
return lib.LLVMGetRelocationTypeName(self)
@CachedProperty
def value_string(self):
if self.expired:
raise Exception('Relocation instance has expired.')
return lib.LLVMGetRelocationValueString(self)
def expire(self):
"""Expire this instance, making future API accesses fail."""
self.expired = True
def cache(self):
"""Cache all cacheable properties on this instance."""
getattr(self, 'address')
getattr(self, 'offset')
getattr(self, 'symbol')
getattr(self, 'type')
getattr(self, 'type_name')
getattr(self, 'value_string')
def register_library(library):
"""Register function prototypes with LLVM library instance."""
# Object.h functions
library.LLVMCreateObjectFile.argtypes = [MemoryBuffer]
library.LLVMCreateObjectFile.restype = c_object_p
library.LLVMDisposeObjectFile.argtypes = [ObjectFile]
library.LLVMGetSections.argtypes = [ObjectFile]
library.LLVMGetSections.restype = c_object_p
library.LLVMDisposeSectionIterator.argtypes = [c_object_p]
library.LLVMIsSectionIteratorAtEnd.argtypes = [ObjectFile, c_object_p]
library.LLVMIsSectionIteratorAtEnd.restype = bool
library.LLVMMoveToNextSection.argtypes = [c_object_p]
library.LLVMMoveToContainingSection.argtypes = [c_object_p, c_object_p]
library.LLVMGetSymbols.argtypes = [ObjectFile]
library.LLVMGetSymbols.restype = c_object_p
library.LLVMDisposeSymbolIterator.argtypes = [c_object_p]
library.LLVMIsSymbolIteratorAtEnd.argtypes = [ObjectFile, c_object_p]
library.LLVMIsSymbolIteratorAtEnd.restype = bool
library.LLVMMoveToNextSymbol.argtypes = [c_object_p]
library.LLVMGetSectionName.argtypes = [c_object_p]
library.LLVMGetSectionName.restype = c_char_p
library.LLVMGetSectionSize.argtypes = [c_object_p]
library.LLVMGetSectionSize.restype = c_uint64
library.LLVMGetSectionContents.argtypes = [c_object_p]
# Can't use c_char_p here as it isn't a NUL-terminated string.
library.LLVMGetSectionContents.restype = POINTER(c_char)
library.LLVMGetSectionAddress.argtypes = [c_object_p]
library.LLVMGetSectionAddress.restype = c_uint64
library.LLVMGetSectionContainsSymbol.argtypes = [c_object_p, c_object_p]
library.LLVMGetSectionContainsSymbol.restype = bool
library.LLVMGetRelocations.argtypes = [c_object_p]
library.LLVMGetRelocations.restype = c_object_p
library.LLVMDisposeRelocationIterator.argtypes = [c_object_p]
library.LLVMIsRelocationIteratorAtEnd.argtypes = [c_object_p, c_object_p]
library.LLVMIsRelocationIteratorAtEnd.restype = bool
library.LLVMMoveToNextRelocation.argtypes = [c_object_p]
library.LLVMGetSymbolName.argtypes = [Symbol]
library.LLVMGetSymbolName.restype = c_char_p
library.LLVMGetSymbolAddress.argtypes = [Symbol]
library.LLVMGetSymbolAddress.restype = c_uint64
library.LLVMGetSymbolSize.argtypes = [Symbol]
library.LLVMGetSymbolSize.restype = c_uint64
library.LLVMGetRelocationOffset.argtypes = [c_object_p]
library.LLVMGetRelocationOffset.restype = c_uint64
library.LLVMGetRelocationSymbol.argtypes = [c_object_p]
library.LLVMGetRelocationSymbol.restype = c_object_p
library.LLVMGetRelocationType.argtypes = [c_object_p]
library.LLVMGetRelocationType.restype = c_uint64
library.LLVMGetRelocationTypeName.argtypes = [c_object_p]
library.LLVMGetRelocationTypeName.restype = c_char_p
library.LLVMGetRelocationValueString.argtypes = [c_object_p]
library.LLVMGetRelocationValueString.restype = c_char_p
lib = get_library()
register_library(lib)
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/object.py |
#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===------------------------------------------------------------------------===#
from ctypes import CFUNCTYPE
from ctypes import POINTER
from ctypes import addressof
from ctypes import c_byte
from ctypes import c_char_p
from ctypes import c_int
from ctypes import c_size_t
from ctypes import c_ubyte
from ctypes import c_uint64
from ctypes import c_void_p
from ctypes import cast
from .common import LLVMObject
from .common import c_object_p
from .common import get_library
__all__ = [
'Disassembler',
]
lib = get_library()
callbacks = {}
# Constants for set_options
Option_UseMarkup = 1
_initialized = False
_targets = ['AArch64', 'ARM', 'Hexagon', 'MSP430', 'Mips', 'NVPTX', 'PowerPC', 'R600', 'Sparc', 'SystemZ', 'X86', 'XCore']
def _ensure_initialized():
global _initialized
if not _initialized:
# Here one would want to call the functions
# LLVMInitializeAll{TargetInfo,TargetMC,Disassembler}s, but
# unfortunately they are only defined as static inline
# functions in the header files of llvm-c, so they don't exist
# as symbols in the shared library.
# So until that is fixed use this hack to initialize them all
for tgt in _targets:
for initializer in ("TargetInfo", "TargetMC", "Disassembler"):
try:
f = getattr(lib, "LLVMInitialize" + tgt + initializer)
except AttributeError:
continue
f()
_initialized = True
class Disassembler(LLVMObject):
"""Represents a disassembler instance.
Disassembler instances are tied to specific "triple," which must be defined
at creation time.
Disassembler instances can disassemble instructions from multiple sources.
"""
def __init__(self, triple):
"""Create a new disassembler instance.
The triple argument is the triple to create the disassembler for. This
is something like 'i386-apple-darwin9'.
"""
_ensure_initialized()
ptr = lib.LLVMCreateDisasm(c_char_p(triple), c_void_p(None), c_int(0),
callbacks['op_info'](0), callbacks['symbol_lookup'](0))
if not ptr:
raise Exception('Could not obtain disassembler for triple: %s' %
triple)
LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisasmDispose)
def get_instruction(self, source, pc=0):
"""Obtain the next instruction from an input source.
The input source should be a str or bytearray or something that
represents a sequence of bytes.
This function will start reading bytes from the beginning of the
source.
The pc argument specifies the address that the first byte is at.
This returns a 2-tuple of:
long number of bytes read. 0 if no instruction was read.
str representation of instruction. This will be the assembly that
represents the instruction.
"""
buf = cast(c_char_p(source), POINTER(c_ubyte))
out_str = cast((c_byte * 255)(), c_char_p)
result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)),
c_uint64(pc), out_str, 255)
return (result, out_str.value)
def get_instructions(self, source, pc=0):
"""Obtain multiple instructions from an input source.
This is like get_instruction() except it is a generator for all
instructions within the source. It starts at the beginning of the
source and reads instructions until no more can be read.
This generator returns 3-tuple of:
long address of instruction.
long size of instruction, in bytes.
str representation of instruction.
"""
source_bytes = c_char_p(source)
out_str = cast((c_byte * 255)(), c_char_p)
# This could probably be written cleaner. But, it does work.
buf = cast(source_bytes, POINTER(c_ubyte * len(source))).contents
offset = 0
address = pc
end_address = pc + len(source)
while address < end_address:
b = cast(addressof(buf) + offset, POINTER(c_ubyte))
result = lib.LLVMDisasmInstruction(self, b,
c_uint64(len(source) - offset), c_uint64(address),
out_str, 255)
if result == 0:
break
yield (address, result, out_str.value)
address += result
offset += result
def set_options(self, options):
if not lib.LLVMSetDisasmOptions(self, options):
raise Exception('Unable to set all disassembler options in %i' % options)
def register_library(library):
library.LLVMCreateDisasm.argtypes = [c_char_p, c_void_p, c_int,
callbacks['op_info'], callbacks['symbol_lookup']]
library.LLVMCreateDisasm.restype = c_object_p
library.LLVMDisasmDispose.argtypes = [Disassembler]
library.LLVMDisasmInstruction.argtypes = [Disassembler, POINTER(c_ubyte),
c_uint64, c_uint64, c_char_p, c_size_t]
library.LLVMDisasmInstruction.restype = c_size_t
library.LLVMSetDisasmOptions.argtypes = [Disassembler, c_uint64]
library.LLVMSetDisasmOptions.restype = c_int
callbacks['op_info'] = CFUNCTYPE(c_int, c_void_p, c_uint64, c_uint64, c_uint64,
c_int, c_void_p)
callbacks['symbol_lookup'] = CFUNCTYPE(c_char_p, c_void_p, c_uint64,
POINTER(c_uint64), c_uint64,
POINTER(c_char_p))
register_library(lib)
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/disassembler.py |
#===- enumerations.py - Python LLVM Enumerations -------------*- python -*--===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===------------------------------------------------------------------------===#
r"""
LLVM Enumerations
=================
This file defines enumerations from LLVM.
Each enumeration is exposed as a list of 2-tuples. These lists are consumed by
dedicated types elsewhere in the package. The enumerations are centrally
defined in this file so they are easier to locate and maintain.
"""
__all__ = [
'Attributes',
'OpCodes',
'TypeKinds',
'Linkages',
'Visibility',
'CallConv',
'IntPredicate',
'RealPredicate',
'LandingPadClauseTy',
]
Attributes = [
('ZExt', 1 << 0),
('MSExt', 1 << 1),
('NoReturn', 1 << 2),
('InReg', 1 << 3),
('StructRet', 1 << 4),
('NoUnwind', 1 << 5),
('NoAlias', 1 << 6),
('ByVal', 1 << 7),
('Nest', 1 << 8),
('ReadNone', 1 << 9),
('ReadOnly', 1 << 10),
('NoInline', 1 << 11),
('AlwaysInline', 1 << 12),
('OptimizeForSize', 1 << 13),
('StackProtect', 1 << 14),
('StackProtectReq', 1 << 15),
('Alignment', 31 << 16),
('NoCapture', 1 << 21),
('NoRedZone', 1 << 22),
('ImplicitFloat', 1 << 23),
('Naked', 1 << 24),
('InlineHint', 1 << 25),
('StackAlignment', 7 << 26),
('ReturnsTwice', 1 << 29),
('UWTable', 1 << 30),
('NonLazyBind', 1 << 31),
]
OpCodes = [
('Ret', 1),
('Br', 2),
('Switch', 3),
('IndirectBr', 4),
('Invoke', 5),
('Unreachable', 7),
('Add', 8),
('FAdd', 9),
('Sub', 10),
('FSub', 11),
('Mul', 12),
('FMul', 13),
('UDiv', 14),
('SDiv', 15),
('FDiv', 16),
('URem', 17),
('SRem', 18),
('FRem', 19),
('Shl', 20),
('LShr', 21),
('AShr', 22),
('And', 23),
('Or', 24),
('Xor', 25),
('Alloca', 26),
('Load', 27),
('Store', 28),
('GetElementPtr', 29),
('Trunc', 30),
('ZExt', 31),
('SExt', 32),
('FPToUI', 33),
('FPToSI', 34),
('UIToFP', 35),
('SIToFP', 36),
('FPTrunc', 37),
('FPExt', 38),
('PtrToInt', 39),
('IntToPtr', 40),
('BitCast', 41),
('ICmp', 42),
('FCmpl', 43),
('PHI', 44),
('Call', 45),
('Select', 46),
('UserOp1', 47),
('UserOp2', 48),
('AArg', 49),
('ExtractElement', 50),
('InsertElement', 51),
('ShuffleVector', 52),
('ExtractValue', 53),
('InsertValue', 54),
('Fence', 55),
('AtomicCmpXchg', 56),
('AtomicRMW', 57),
('Resume', 58),
('LandingPad', 59),
]
TypeKinds = [
('Void', 0),
('Half', 1),
('Float', 2),
('Double', 3),
('X86_FP80', 4),
('FP128', 5),
('PPC_FP128', 6),
('Label', 7),
('Integer', 8),
('Function', 9),
('Struct', 10),
('Array', 11),
('Pointer', 12),
('Vector', 13),
('Metadata', 14),
('X86_MMX', 15),
]
Linkages = [
('External', 0),
('AvailableExternally', 1),
('LinkOnceAny', 2),
('LinkOnceODR', 3),
('WeakAny', 4),
('WeakODR', 5),
('Appending', 6),
('Internal', 7),
('Private', 8),
('DLLImport', 9),
('DLLExport', 10),
('ExternalWeak', 11),
('Ghost', 12),
('Common', 13),
('LinkerPrivate', 14),
('LinkerPrivateWeak', 15),
('LinkerPrivateWeakDefAuto', 16),
]
Visibility = [
('Default', 0),
('Hidden', 1),
('Protected', 2),
]
CallConv = [
('CCall', 0),
('FastCall', 8),
('ColdCall', 9),
('X86StdcallCall', 64),
('X86FastcallCall', 65),
]
IntPredicate = [
('EQ', 32),
('NE', 33),
('UGT', 34),
('UGE', 35),
('ULT', 36),
('ULE', 37),
('SGT', 38),
('SGE', 39),
('SLT', 40),
('SLE', 41),
]
RealPredicate = [
('PredicateFalse', 0),
('OEQ', 1),
('OGT', 2),
('OGE', 3),
('OLT', 4),
('OLE', 5),
('ONE', 6),
('ORD', 7),
('UNO', 8),
('UEQ', 9),
('UGT', 10),
('UGE', 11),
('ULT', 12),
('ULE', 13),
('UNE', 14),
('PredicateTrue', 15),
]
LandingPadClauseTy = [
('Catch', 0),
('Filter', 1),
]
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/enumerations.py |
MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/__init__.py |
|
#===- core.py - Python LLVM Bindings -------------------------*- python -*--===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===------------------------------------------------------------------------===#
from __future__ import print_function
from .common import LLVMObject
from .common import c_object_p
from .common import get_library
from . import enumerations
from ctypes import POINTER
from ctypes import byref
from ctypes import c_char_p
from ctypes import c_uint
import sys
__all__ = [
"lib",
"Enums",
"OpCode",
"MemoryBuffer",
"Module",
"Value",
"Function",
"BasicBlock",
"Instruction",
"Context",
"PassRegistry"
]
lib = get_library()
Enums = []
class LLVMEnumeration(object):
"""Represents an individual LLVM enumeration."""
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return '%s.%s' % (self.__class__.__name__,
self.name)
@classmethod
def from_value(cls, value):
"""Obtain an enumeration instance from a numeric value."""
result = cls._value_map.get(value, None)
if result is None:
raise ValueError('Unknown %s: %d' % (cls.__name__,
value))
return result
@classmethod
def register(cls, name, value):
"""Registers a new enumeration.
This is called by this module for each enumeration defined in
enumerations. You should not need to call this outside this module.
"""
if value in cls._value_map:
raise ValueError('%s value already registered: %d' % (cls.__name__,
value))
enum = cls(name, value)
cls._value_map[value] = enum
setattr(cls, name, enum)
class Attribute(LLVMEnumeration):
"""Represents an individual Attribute enumeration."""
_value_map = {}
def __init__(self, name, value):
super(Attribute, self).__init__(name, value)
class OpCode(LLVMEnumeration):
"""Represents an individual OpCode enumeration."""
_value_map = {}
def __init__(self, name, value):
super(OpCode, self).__init__(name, value)
class TypeKind(LLVMEnumeration):
"""Represents an individual TypeKind enumeration."""
_value_map = {}
def __init__(self, name, value):
super(TypeKind, self).__init__(name, value)
class Linkage(LLVMEnumeration):
"""Represents an individual Linkage enumeration."""
_value_map = {}
def __init__(self, name, value):
super(Linkage, self).__init__(name, value)
class Visibility(LLVMEnumeration):
"""Represents an individual visibility enumeration."""
_value_map = {}
def __init__(self, name, value):
super(Visibility, self).__init__(name, value)
class CallConv(LLVMEnumeration):
"""Represents an individual calling convention enumeration."""
_value_map = {}
def __init__(self, name, value):
super(CallConv, self).__init__(name, value)
class IntPredicate(LLVMEnumeration):
"""Represents an individual IntPredicate enumeration."""
_value_map = {}
def __init__(self, name, value):
super(IntPredicate, self).__init__(name, value)
class RealPredicate(LLVMEnumeration):
"""Represents an individual RealPredicate enumeration."""
_value_map = {}
def __init__(self, name, value):
super(RealPredicate, self).__init__(name, value)
class LandingPadClauseTy(LLVMEnumeration):
"""Represents an individual LandingPadClauseTy enumeration."""
_value_map = {}
def __init__(self, name, value):
super(LandingPadClauseTy, self).__init__(name, value)
class MemoryBuffer(LLVMObject):
"""Represents an opaque memory buffer."""
def __init__(self, filename=None):
"""Create a new memory buffer.
Currently, we support creating from the contents of a file at the
specified filename.
"""
if filename is None:
raise Exception("filename argument must be defined")
memory = c_object_p()
out = c_char_p(None)
result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
byref(memory), byref(out))
if result:
raise Exception("Could not create memory buffer: %s" % out.value)
LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
def __len__(self):
return lib.LLVMGetBufferSize(self)
class Value(LLVMObject):
def __init__(self, value):
LLVMObject.__init__(self, value)
@property
def name(self):
return lib.LLVMGetValueName(self)
def dump(self):
lib.LLVMDumpValue(self)
def get_operand(self, i):
return Value(lib.LLVMGetOperand(self, i))
def set_operand(self, i, v):
return lib.LLVMSetOperand(self, i, v)
def __len__(self):
return lib.LLVMGetNumOperands(self)
class Module(LLVMObject):
"""Represents the top-level structure of an llvm program in an opaque object."""
def __init__(self, module, name=None, context=None):
LLVMObject.__init__(self, module, disposer=lib.LLVMDisposeModule)
@classmethod
def CreateWithName(cls, module_id):
m = Module(lib.LLVMModuleCreateWithName(module_id))
Context.GetGlobalContext().take_ownership(m)
return m
@property
def datalayout(self):
return lib.LLVMGetDataLayout(self)
@datalayout.setter
def datalayout(self, new_data_layout):
"""new_data_layout is a string."""
lib.LLVMSetDataLayout(self, new_data_layout)
@property
def target(self):
return lib.LLVMGetTarget(self)
@target.setter
def target(self, new_target):
"""new_target is a string."""
lib.LLVMSetTarget(self, new_target)
def dump(self):
lib.LLVMDumpModule(self)
class __function_iterator(object):
def __init__(self, module, reverse=False):
self.module = module
self.reverse = reverse
if self.reverse:
self.function = self.module.last
else:
self.function = self.module.first
def __iter__(self):
return self
def __next__(self):
if not isinstance(self.function, Function):
raise StopIteration("")
result = self.function
if self.reverse:
self.function = self.function.prev
else:
self.function = self.function.next
return result
if sys.version_info.major == 2:
next = __next__
def __iter__(self):
return Module.__function_iterator(self)
def __reversed__(self):
return Module.__function_iterator(self, reverse=True)
@property
def first(self):
return Function(lib.LLVMGetFirstFunction(self))
@property
def last(self):
return Function(lib.LLVMGetLastFunction(self))
def print_module_to_file(self, filename):
out = c_char_p(None)
# Result is inverted so 0 means everything was ok.
result = lib.LLVMPrintModuleToFile(self, filename, byref(out))
if result:
raise RuntimeError("LLVM Error: %s" % out.value)
class Function(Value):
def __init__(self, value):
Value.__init__(self, value)
@property
def next(self):
f = lib.LLVMGetNextFunction(self)
return f and Function(f)
@property
def prev(self):
f = lib.LLVMGetPreviousFunction(self)
return f and Function(f)
@property
def first(self):
b = lib.LLVMGetFirstBasicBlock(self)
return b and BasicBlock(b)
@property
def last(self):
b = lib.LLVMGetLastBasicBlock(self)
return b and BasicBlock(b)
class __bb_iterator(object):
def __init__(self, function, reverse=False):
self.function = function
self.reverse = reverse
if self.reverse:
self.bb = function.last
else:
self.bb = function.first
def __iter__(self):
return self
def __next__(self):
if not isinstance(self.bb, BasicBlock):
raise StopIteration("")
result = self.bb
if self.reverse:
self.bb = self.bb.prev
else:
self.bb = self.bb.next
return result
if sys.version_info.major == 2:
next = __next__
def __iter__(self):
return Function.__bb_iterator(self)
def __reversed__(self):
return Function.__bb_iterator(self, reverse=True)
def __len__(self):
return lib.LLVMCountBasicBlocks(self)
class BasicBlock(LLVMObject):
def __init__(self, value):
LLVMObject.__init__(self, value)
@property
def next(self):
b = lib.LLVMGetNextBasicBlock(self)
return b and BasicBlock(b)
@property
def prev(self):
b = lib.LLVMGetPreviousBasicBlock(self)
return b and BasicBlock(b)
@property
def first(self):
i = lib.LLVMGetFirstInstruction(self)
return i and Instruction(i)
@property
def last(self):
i = lib.LLVMGetLastInstruction(self)
return i and Instruction(i)
def __as_value(self):
return Value(lib.LLVMBasicBlockAsValue(self))
@property
def name(self):
return lib.LLVMGetValueName(self.__as_value())
def dump(self):
lib.LLVMDumpValue(self.__as_value())
def get_operand(self, i):
return Value(lib.LLVMGetOperand(self.__as_value(),
i))
def set_operand(self, i, v):
return lib.LLVMSetOperand(self.__as_value(),
i, v)
def __len__(self):
return lib.LLVMGetNumOperands(self.__as_value())
class __inst_iterator(object):
def __init__(self, bb, reverse=False):
self.bb = bb
self.reverse = reverse
if self.reverse:
self.inst = self.bb.last
else:
self.inst = self.bb.first
def __iter__(self):
return self
def __next__(self):
if not isinstance(self.inst, Instruction):
raise StopIteration("")
result = self.inst
if self.reverse:
self.inst = self.inst.prev
else:
self.inst = self.inst.next
return result
if sys.version_info.major == 2:
next = __next__
def __iter__(self):
return BasicBlock.__inst_iterator(self)
def __reversed__(self):
return BasicBlock.__inst_iterator(self, reverse=True)
class Instruction(Value):
def __init__(self, value):
Value.__init__(self, value)
@property
def next(self):
i = lib.LLVMGetNextInstruction(self)
return i and Instruction(i)
@property
def prev(self):
i = lib.LLVMGetPreviousInstruction(self)
return i and Instruction(i)
@property
def opcode(self):
return OpCode.from_value(lib.LLVMGetInstructionOpcode(self))
class Context(LLVMObject):
def __init__(self, context=None):
if context is None:
context = lib.LLVMContextCreate()
LLVMObject.__init__(self, context, disposer=lib.LLVMContextDispose)
else:
LLVMObject.__init__(self, context)
@classmethod
def GetGlobalContext(cls):
return Context(lib.LLVMGetGlobalContext())
class PassRegistry(LLVMObject):
"""Represents an opaque pass registry object."""
def __init__(self):
LLVMObject.__init__(self,
lib.LLVMGetGlobalPassRegistry())
def register_library(library):
# Initialization/Shutdown declarations.
library.LLVMInitializeCore.argtypes = [PassRegistry]
library.LLVMInitializeCore.restype = None
library.LLVMInitializeTransformUtils.argtypes = [PassRegistry]
library.LLVMInitializeTransformUtils.restype = None
library.LLVMInitializeScalarOpts.argtypes = [PassRegistry]
library.LLVMInitializeScalarOpts.restype = None
library.LLVMInitializeObjCARCOpts.argtypes = [PassRegistry]
library.LLVMInitializeObjCARCOpts.restype = None
library.LLVMInitializeVectorization.argtypes = [PassRegistry]
library.LLVMInitializeVectorization.restype = None
library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
library.LLVMInitializeInstCombine.restype = None
library.LLVMInitializeAggressiveInstCombiner.argtypes = [PassRegistry]
library.LLVMInitializeAggressiveInstCombiner.restype = None
library.LLVMInitializeIPO.argtypes = [PassRegistry]
library.LLVMInitializeIPO.restype = None
library.LLVMInitializeInstrumentation.argtypes = [PassRegistry]
library.LLVMInitializeInstrumentation.restype = None
library.LLVMInitializeAnalysis.argtypes = [PassRegistry]
library.LLVMInitializeAnalysis.restype = None
library.LLVMInitializeCodeGen.argtypes = [PassRegistry]
library.LLVMInitializeCodeGen.restype = None
library.LLVMInitializeTarget.argtypes = [PassRegistry]
library.LLVMInitializeTarget.restype = None
library.LLVMShutdown.argtypes = []
library.LLVMShutdown.restype = None
# Pass Registry declarations.
library.LLVMGetGlobalPassRegistry.argtypes = []
library.LLVMGetGlobalPassRegistry.restype = c_object_p
# Context declarations.
library.LLVMContextCreate.argtypes = []
library.LLVMContextCreate.restype = c_object_p
library.LLVMContextDispose.argtypes = [Context]
library.LLVMContextDispose.restype = None
library.LLVMGetGlobalContext.argtypes = []
library.LLVMGetGlobalContext.restype = c_object_p
# Memory buffer declarations
library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
POINTER(c_object_p), POINTER(c_char_p)]
library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
library.LLVMGetBufferSize.argtypes = [MemoryBuffer]
library.LLVMDisposeMemoryBuffer.argtypes = [MemoryBuffer]
# Module declarations
library.LLVMModuleCreateWithName.argtypes = [c_char_p]
library.LLVMModuleCreateWithName.restype = c_object_p
library.LLVMDisposeModule.argtypes = [Module]
library.LLVMDisposeModule.restype = None
library.LLVMGetDataLayout.argtypes = [Module]
library.LLVMGetDataLayout.restype = c_char_p
library.LLVMSetDataLayout.argtypes = [Module, c_char_p]
library.LLVMSetDataLayout.restype = None
library.LLVMGetTarget.argtypes = [Module]
library.LLVMGetTarget.restype = c_char_p
library.LLVMSetTarget.argtypes = [Module, c_char_p]
library.LLVMSetTarget.restype = None
library.LLVMDumpModule.argtypes = [Module]
library.LLVMDumpModule.restype = None
library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p,
POINTER(c_char_p)]
library.LLVMPrintModuleToFile.restype = bool
library.LLVMGetFirstFunction.argtypes = [Module]
library.LLVMGetFirstFunction.restype = c_object_p
library.LLVMGetLastFunction.argtypes = [Module]
library.LLVMGetLastFunction.restype = c_object_p
library.LLVMGetNextFunction.argtypes = [Function]
library.LLVMGetNextFunction.restype = c_object_p
library.LLVMGetPreviousFunction.argtypes = [Function]
library.LLVMGetPreviousFunction.restype = c_object_p
# Value declarations.
library.LLVMGetValueName.argtypes = [Value]
library.LLVMGetValueName.restype = c_char_p
library.LLVMDumpValue.argtypes = [Value]
library.LLVMDumpValue.restype = None
library.LLVMGetOperand.argtypes = [Value, c_uint]
library.LLVMGetOperand.restype = c_object_p
library.LLVMSetOperand.argtypes = [Value, Value, c_uint]
library.LLVMSetOperand.restype = None
library.LLVMGetNumOperands.argtypes = [Value]
library.LLVMGetNumOperands.restype = c_uint
# Basic Block Declarations.
library.LLVMGetFirstBasicBlock.argtypes = [Function]
library.LLVMGetFirstBasicBlock.restype = c_object_p
library.LLVMGetLastBasicBlock.argtypes = [Function]
library.LLVMGetLastBasicBlock.restype = c_object_p
library.LLVMGetNextBasicBlock.argtypes = [BasicBlock]
library.LLVMGetNextBasicBlock.restype = c_object_p
library.LLVMGetPreviousBasicBlock.argtypes = [BasicBlock]
library.LLVMGetPreviousBasicBlock.restype = c_object_p
library.LLVMGetFirstInstruction.argtypes = [BasicBlock]
library.LLVMGetFirstInstruction.restype = c_object_p
library.LLVMGetLastInstruction.argtypes = [BasicBlock]
library.LLVMGetLastInstruction.restype = c_object_p
library.LLVMBasicBlockAsValue.argtypes = [BasicBlock]
library.LLVMBasicBlockAsValue.restype = c_object_p
library.LLVMCountBasicBlocks.argtypes = [Function]
library.LLVMCountBasicBlocks.restype = c_uint
# Instruction Declarations.
library.LLVMGetNextInstruction.argtypes = [Instruction]
library.LLVMGetNextInstruction.restype = c_object_p
library.LLVMGetPreviousInstruction.argtypes = [Instruction]
library.LLVMGetPreviousInstruction.restype = c_object_p
library.LLVMGetInstructionOpcode.argtypes = [Instruction]
library.LLVMGetInstructionOpcode.restype = c_uint
def register_enumerations():
if Enums:
return None
enums = [
(Attribute, enumerations.Attributes),
(OpCode, enumerations.OpCodes),
(TypeKind, enumerations.TypeKinds),
(Linkage, enumerations.Linkages),
(Visibility, enumerations.Visibility),
(CallConv, enumerations.CallConv),
(IntPredicate, enumerations.IntPredicate),
(RealPredicate, enumerations.RealPredicate),
(LandingPadClauseTy, enumerations.LandingPadClauseTy),
]
for enum_class, enum_spec in enums:
for name, value in enum_spec:
print(name, value)
enum_class.register(name, value)
return enums
def initialize_llvm():
Context.GetGlobalContext()
p = PassRegistry()
lib.LLVMInitializeCore(p)
lib.LLVMInitializeTransformUtils(p)
lib.LLVMInitializeScalarOpts(p)
lib.LLVMInitializeObjCARCOpts(p)
lib.LLVMInitializeVectorization(p)
lib.LLVMInitializeInstCombine(p)
lib.LLVMInitializeIPO(p)
lib.LLVMInitializeInstrumentation(p)
lib.LLVMInitializeAnalysis(p)
lib.LLVMInitializeCodeGen(p)
lib.LLVMInitializeTarget(p)
register_library(lib)
Enums = register_enumerations()
initialize_llvm()
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/core.py |
#===- common.py - Python LLVM Bindings -----------------------*- python -*--===#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#===------------------------------------------------------------------------===#
from ctypes import POINTER
from ctypes import c_void_p
from ctypes import cdll
import ctypes.util
import platform
# LLVM_VERSION: sync with PACKAGE_VERSION in CMakeLists.txt
# but leave out the 'svn' suffix.
LLVM_VERSION = '10.0.0'
__all__ = [
'c_object_p',
'get_library',
]
c_object_p = POINTER(c_void_p)
class LLVMObject(object):
"""Base class for objects that are backed by an LLVM data structure.
This class should never be instantiated outside of this package.
"""
def __init__(self, ptr, ownable=True, disposer=None):
assert isinstance(ptr, c_object_p)
self._ptr = self._as_parameter_ = ptr
self._self_owned = True
self._ownable = ownable
self._disposer = disposer
self._owned_objects = []
def take_ownership(self, obj):
"""Take ownership of another object.
When you take ownership of another object, you are responsible for
destroying that object. In addition, a reference to that object is
placed inside this object so the Python garbage collector will not
collect the object while it is still alive in libLLVM.
This method should likely only be called from within modules inside
this package.
"""
assert isinstance(obj, LLVMObject)
self._owned_objects.append(obj)
obj._self_owned = False
def from_param(self):
"""ctypes function that converts this object to a function parameter."""
return self._as_parameter_
def __del__(self):
if not hasattr(self, '_self_owned') or not hasattr(self, '_disposer'):
return
if self._self_owned and self._disposer:
self._disposer(self)
class CachedProperty(object):
"""Decorator that caches the result of a property lookup.
This is a useful replacement for @property. It is recommended to use this
decorator on properties that invoke C API calls for which the result of the
call will be idempotent.
"""
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__doc__ = wrapped.__doc__
except: # pragma: no cover
pass
def __get__(self, instance, instance_type=None):
if instance is None:
return self
value = self.wrapped(instance)
setattr(instance, self.wrapped.__name__, value)
return value
def get_library():
"""Obtain a reference to the llvm library."""
# On Linux, ctypes.cdll.LoadLibrary() respects LD_LIBRARY_PATH
# while ctypes.util.find_library() doesn't.
# See http://docs.python.org/2/library/ctypes.html#finding-shared-libraries
#
# To make it possible to run the unit tests without installing the LLVM shared
# library into a default linker search path. Always Try ctypes.cdll.LoadLibrary()
# with all possible library names first, then try ctypes.util.find_library().
names = ['LLVM-' + LLVM_VERSION, 'LLVM-' + LLVM_VERSION + 'svn']
t = platform.system()
if t == 'Darwin':
pfx, ext = 'lib', '.dylib'
elif t == 'Windows':
pfx, ext = '', '.dll'
else:
pfx, ext = 'lib', '.so'
for i in names:
try:
lib = cdll.LoadLibrary(pfx + i + ext)
except OSError:
pass
else:
return lib
for i in names:
t = ctypes.util.find_library(i)
if t:
return cdll.LoadLibrary(t)
raise Exception('LLVM shared library not found!')
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/common.py |
from .common import LLVMObject
from .common import c_object_p
from .common import get_library
from . import enumerations
from .core import MemoryBuffer
from .core import Module
from .core import OpCode
from ctypes import POINTER
from ctypes import byref
from ctypes import c_char_p
from ctypes import cast
__all__ = ['parse_bitcode']
lib = get_library()
def parse_bitcode(mem_buffer):
"""Input is .core.MemoryBuffer"""
module = c_object_p()
result = lib.LLVMParseBitcode2(mem_buffer, byref(module))
if result:
raise RuntimeError('LLVM Error')
m = Module(module)
m.take_ownership(mem_buffer)
return m
def register_library(library):
library.LLVMParseBitcode2.argtypes = [MemoryBuffer, POINTER(c_object_p)]
library.LLVMParseBitcode2.restype = bool
register_library(lib)
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/bit_reader.py |
from __future__ import print_function
from .base import TestBase
from ..core import OpCode
from ..core import MemoryBuffer
from ..core import PassRegistry
from ..core import Context
from ..core import Module
from ..bit_reader import parse_bitcode
class TestBitReader(TestBase):
def test_parse_bitcode(self):
source = self.get_test_bc()
m = parse_bitcode(MemoryBuffer(filename=source))
print(m.target)
print(m.datalayout)
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/tests/test_bitreader.py |
from __future__ import print_function
from .base import TestBase
from ..core import MemoryBuffer
from ..core import PassRegistry
from ..core import Context
from ..core import Module
from ..core import Enums
from ..core import OpCode
from ..bit_reader import parse_bitcode
class TestCore(TestBase):
def test_enumerations(self):
for enum_cls, enum_spec in Enums:
for enum_name, enum_value in enum_spec:
# First make sure that enum_cls has the name of the enum as an
# attribute. People will access these values as
# EnumCls.EnumName.
self.assertTrue(hasattr(enum_cls, enum_name))
v_attr = getattr(enum_cls, enum_name)
self.assertTrue(isinstance(v_attr, enum_cls))
# Then make sure that the value returned for this attribute is
# correct in both ways.
self.assertEqual(v_attr.value, enum_value)
e = enum_cls.from_value(enum_value)
self.assertTrue(isinstance(e, enum_cls))
self.assertEqual(e, v_attr)
def test_memory_buffer_create_from_file(self):
source = self.get_test_file()
MemoryBuffer(filename=source)
def test_memory_buffer_failing(self):
with self.assertRaises(Exception):
MemoryBuffer(filename="/hopefully/this/path/doesnt/exist")
def test_memory_buffer_len(self):
source = self.get_test_file()
m = MemoryBuffer(filename=source)
self.assertEqual(len(m), 50)
def test_create_passregistry(self):
PassRegistry()
def test_create_context(self):
Context.GetGlobalContext()
def test_create_module_with_name(self):
# Make sure we can not create a module without a LLVMModuleRef.
with self.assertRaises(TypeError):
m = Module()
m = Module.CreateWithName("test-module")
def test_module_getset_datalayout(self):
m = Module.CreateWithName("test-module")
dl = "e-p:32:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:32:64-v128:32:128-a0:0:32-n32-S32"
m.datalayout = dl
self.assertEqual(m.datalayout, dl)
def test_module_getset_target(self):
m = Module.CreateWithName("test-module")
target = "thumbv7-apple-ios5.0.0"
m.target = target
self.assertEqual(m.target, target)
def test_module_print_module_to_file(self):
m = Module.CreateWithName("test")
dl = "e-p:32:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:32:64-v128:32:128-a0:0:32-n32-S32"
m.datalayout = dl
target = "thumbv7-apple-ios5.0.0"
m.target = target
m.print_module_to_file("test2.ll")
def test_module_function_iteration(self):
m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc()))
i = 0
functions = ["f", "f2", "f3", "f4", "f5", "f6", "g1", "g2", "h1", "h2",
"h3"]
# Forward
for f in m:
self.assertEqual(f.name, functions[i])
f.dump()
i += 1
# Backwards
for f in reversed(m):
i -= 1
self.assertEqual(f.name, functions[i])
f.dump()
def test_function_basicblock_iteration(self):
m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc()))
i = 0
bb_list = ['b1', 'b2', 'end']
f = m.first
while f.name != "f6":
f = f.next
# Forward
for bb in f:
self.assertEqual(bb.name, bb_list[i])
bb.dump()
i += 1
# Backwards
for bb in reversed(f):
i -= 1
self.assertEqual(bb.name, bb_list[i])
bb.dump()
def test_basicblock_instruction_iteration(self):
m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc()))
i = 0
inst_list = [('arg1', OpCode.ExtractValue),
('arg2', OpCode.ExtractValue),
('', OpCode.Call),
('', OpCode.Ret)]
bb = m.first.first
# Forward
for inst in bb:
self.assertEqual(inst.name, inst_list[i][0])
self.assertEqual(inst.opcode, inst_list[i][1])
for op in range(len(inst)):
o = inst.get_operand(op)
print(o.name)
o.dump()
inst.dump()
i += 1
# Backwards
for inst in reversed(bb):
i -= 1
self.assertEqual(inst.name, inst_list[i][0])
self.assertEqual(inst.opcode, inst_list[i][1])
inst.dump()
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/tests/test_core.py |
MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/tests/__init__.py |
|
from __future__ import print_function
from .base import TestBase
from ..disassembler import Disassembler, Option_UseMarkup
class TestDisassembler(TestBase):
def test_instantiate(self):
Disassembler('i686-apple-darwin9')
def test_basic(self):
sequence = '\x67\xe3\x81' # jcxz -127
triple = 'i686-apple-darwin9'
disassembler = Disassembler(triple)
count, s = disassembler.get_instruction(sequence)
self.assertEqual(count, 3)
self.assertEqual(s, '\tjcxz\t-127')
def test_nonexistent_triple(self):
with self.assertRaisesRegex(Exception, "Could not obtain disassembler for triple"):
Disassembler("nonexistent-triple-raises")
def test_get_instructions(self):
sequence = '\x67\xe3\x81\x01\xc7' # jcxz -127; addl %eax, %edi
disassembler = Disassembler('i686-apple-darwin9')
instructions = list(disassembler.get_instructions(sequence))
self.assertEqual(len(instructions), 2)
self.assertEqual(instructions[0], (0, 3, '\tjcxz\t-127'))
self.assertEqual(instructions[1], (3, 2, '\taddl\t%eax, %edi'))
def test_set_options(self):
sequence = '\x10\x40\x2d\xe9'
triple = 'arm-linux-android'
disassembler = Disassembler(triple)
disassembler.set_options(Option_UseMarkup)
count, s = disassembler.get_instruction(sequence)
print(s)
self.assertEqual(count, 4)
self.assertEqual(s, '\tpush\t{<reg:r4>, <reg:lr>}')
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/tests/test_disassembler.py |
from numbers import Integral
from .base import TestBase
from ..object import ObjectFile
from ..object import Relocation
from ..object import Section
from ..object import Symbol
class TestObjectFile(TestBase):
def get_object_file(self):
source = self.get_test_binary()
return ObjectFile(filename=source)
def test_create_from_file(self):
self.get_object_file()
def test_get_sections(self):
o = self.get_object_file()
count = 0
for section in o.get_sections():
count += 1
assert isinstance(section, Section)
assert isinstance(section.name, str)
assert isinstance(section.size, Integral)
assert isinstance(section.contents, str)
assert isinstance(section.address, Integral)
assert len(section.contents) == section.size
self.assertGreater(count, 0)
for section in o.get_sections():
section.cache()
def test_get_symbols(self):
o = self.get_object_file()
count = 0
for symbol in o.get_symbols():
count += 1
assert isinstance(symbol, Symbol)
assert isinstance(symbol.name, str)
assert isinstance(symbol.address, Integral)
assert isinstance(symbol.size, Integral)
self.assertGreater(count, 0)
for symbol in o.get_symbols():
symbol.cache()
def test_symbol_section_accessor(self):
o = self.get_object_file()
for symbol in o.get_symbols():
section = symbol.section
assert isinstance(section, Section)
break
def test_get_relocations(self):
o = self.get_object_file()
for section in o.get_sections():
for relocation in section.get_relocations():
assert isinstance(relocation, Relocation)
assert isinstance(relocation.address, Integral)
assert isinstance(relocation.offset, Integral)
assert isinstance(relocation.type_number, Integral)
assert isinstance(relocation.type_name, str)
assert isinstance(relocation.value_string, str)
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/tests/test_object.py |
import os.path
import sys
import unittest
POSSIBLE_TEST_BINARIES = [
'libreadline.so.5',
'libreadline.so.6',
]
POSSIBLE_TEST_BINARY_PATHS = [
'/usr/lib/debug',
'/lib',
'/usr/lib',
'/usr/local/lib',
'/lib/i386-linux-gnu',
]
class TestBase(unittest.TestCase):
if sys.version_info.major == 2:
assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
def get_test_binary(self):
"""Helper to obtain a test binary for object file testing.
FIXME Support additional, highly-likely targets or create one
ourselves.
"""
for d in POSSIBLE_TEST_BINARY_PATHS:
for lib in POSSIBLE_TEST_BINARIES:
path = os.path.join(d, lib)
if os.path.exists(path):
return path
raise Exception('No suitable test binaries available!')
get_test_binary.__test__ = False
def get_test_file(self):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_file")
def get_test_bc(self):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "test.bc")
| MDL-SDK-master | src/mdl/jit/llvm/dist/bindings/python/llvm/tests/base.py |
#!/usr/bin/env python
#*****************************************************************************
# Copyright (c) 2017-2023, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#*****************************************************************************
# This script generates libbsdf_bitcode.h from libbsdf.bc
import sys
import os
copyright_str = """
/******************************************************************************
* Copyright (c) 2017-2023, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
"""
def xxd(filename, fout):
f = open(filename, "rb")
bytes = f.read()
i = 0
fout.write("\t")
for byte in bytes:
if isinstance(byte, str):
byte = ord(byte)
fout.write("0x%02x, " % byte)
if i == 7:
fout.write("\n\t")
i = 0
else:
i += 1
def usage():
print("Usage: %s <inputfile> <output directory>" % sys.argv[0])
return 1
def main(args):
if len(args) != 3:
return usage()
bc_name = args[1]
IntDir = args[2]
suffix = bc_name[bc_name.rfind('_'):-3];
out_name = "libbsdf_bitcode" + suffix + ".h"
with open(os.path.join(IntDir, out_name), "w") as f:
f.write(copyright_str)
f.write("\n// Automatically generated from libbsdf%s.bc\n\n"
"static unsigned char const libbsdf_bitcode%s[] = {\n" % (suffix, suffix))
xxd(bc_name, f)
f.write("};\n")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
| MDL-SDK-master | src/mdl/jit/generator_jit/gen_libbsdf.py |
#!/usr/bin/env python
#*****************************************************************************
# Copyright (c) 2014-2023, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#*****************************************************************************
import sys
import os
def xxd(filename, fout):
f = open(filename, "rb")
bytes = f.read()
i = 0
fout.write("\t")
for byte in bytes:
if isinstance(byte, str):
byte = ord(byte)
fout.write("0x%02x, " % byte)
if i == 7:
fout.write("\n\t")
i = 0
else:
i += 1
def main(args):
filter = args[1]
#CUDA_DIR = args[2].replace("\\","/") #re-enable in case we update to newer LLVM
MISRC_DIR = args[2].replace("\\","/")
IntDir = args[3]
#LIBDEVICE_DIR = CUDA_DIR + "/nvvm/libdevice" #re-enable in case we update to newer LLVM
LIBDEVICE_DIR = MISRC_DIR + "/libdevice"
# to support old python versions having problems executing
# relative path with forward slashes under windows
if filter[0] == '.':
filter = os.getcwd() + "/" + filter
version = 10
bc_name = "libdevice.%u.bc" % (version)
out_name = "glue_libdevice.h"
print("Stripping %s ..." % bc_name)
cmd_line = (filter +
" \"" + LIBDEVICE_DIR + "/" + bc_name + "\" \"" +
IntDir + "/" + bc_name + "\"")
exit_code = os.system(cmd_line)
if exit_code != 0:
sys.stderr.write ("ERROR: command %s exited unexpectedly, exitcode %d\n" % (cmd_line, exit_code))
sys.exit (1)
print("Generating %s ..." % out_name)
f = open(IntDir + "/" + out_name, "w")
f.write("static unsigned char const glue_bitcode[] = {\n")
xxd(IntDir + "/" + bc_name, f)
f.write("};\n")
f.close()
if __name__ == "__main__":
main(sys.argv)
| MDL-SDK-master | src/mdl/jit/generator_jit/gen_libdevice.py |
#!/bin/env python
#*****************************************************************************
# Copyright (c) 2013-2023, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#*****************************************************************************
# This script generated signatures for compiler known functions.
#
# python 2.3 or higher is needed
#
import sys
import os
import re
def error(msg):
"""Write a message to stderr"""
sys.stderr.write("gen_intrinsic_func: Error: " + msg + "\n")
def warning(msg):
"""Write a message to stderr"""
sys.stderr.write("gen_intrinsic_func: Warning: " + msg + "\n")
def make_temp_file():
"""Return a temporary file name"""
fd, name = tempfile.mkstemp()
os.close(fd)
return name
class SignatureParser:
"""main signature parser"""
def __init__(self, script_name, indir, out_name, strict):
"""constructor"""
self.debug = False
self.indir = indir
self.out_name = out_name
self.r_intrinsic = re.compile(r"\[\[\s+intrinsic\(\)[^]]*\]\];")
self.curr_module = ""
self.m_intrinsics = {}
self.m_intrinsic_mods = {}
self.m_signatures = {}
self.indent = 0
self.strict = strict
self.m_func_index = {}
self.m_next_func_index = 0
self.unsupported_intrinsics = {}
self.intrinsic_modes = {}
self.cnst_mul = {}
# members of the generator class, a (type, name, comment) tupel
self.m_class_members = {}
self.m_class_member_names = []
#
# ADD NEW TYPES HERE!
#
self.m_types = {
"bool" : "BB",
"bool2" : "B2",
"bool3" : "B3",
"bool4" : "B4",
"int" : "II",
"int2" : "I2",
"int3" : "I3",
"int4" : "I4",
"float" : "FF",
"float2" : "F2",
"float3" : "F3",
"float4" : "F4",
"double" : "DD",
"double2" : "D2",
"double3" : "D3",
"double4" : "D4",
"color" : "CC",
"float2x2" : "F22",
"float2x3" : "F23",
"float2x4" : "F24",
"float3x2" : "F32",
"float3x3" : "F33",
"float3x4" : "F34",
"float4x2" : "F42",
"float4x3" : "F43",
"float4x4" : "F44",
"double2x2" : "D22",
"double2x3" : "D23",
"double2x4" : "D24",
"double3x2" : "D32",
"double3x3" : "D33",
"double3x4" : "D34",
"double4x2" : "D42",
"double4x3" : "D43",
"double4x4" : "D44",
"float[2]" : "FA2",
"float[3]" : "FA3",
"float[4]" : "FA4",
"float2[2]" : "F2A2",
"float3[2]" : "F3A2",
"float4[2]" : "F4A2",
"double[2]" : "DA2",
"double2[2]" : "D2A2",
"double3[2]" : "D3A2",
"double4[2]" : "D4A2",
"int[3]" : "IA3",
"float[<N>]" : "FAN",
"float[N]" : "FAn",
"texture_2d" : "T2",
"texture_3d" : "T3",
"texture_cube" : "TC",
"texture_ptex" : "TP",
"string" : "SS",
"light_profile" : "LP",
"size_t" : "ZZ",
"double *" : "dd",
"float *" : "ff",
"void *" : "vv",
"Exception_state *" : "xs",
"State_core *" : "sc",
"Line_buffer *" : "lb",
"char const *" : "CS",
"float[WAVELENGTH_BASE_MAX]" : "FAW",
"coordinate_space" : "ECS",
"wrap_mode" : "EWM",
"mbsdf_part" : "EMP",
"Res_data_pair *" : "PT",
# unsupported types
"bsdf" : "UB",
"hair_bsdf" : "UH",
"edf" : "UE",
"vdf" : "UV",
"bsdf_measurement" : "UM",
"scatter_mode" : "ESM",
"bsdf_component[<N>]" : "UAB",
"edf_component[<N>]" : "UAE",
"vdf_component[<N>]" : "UAV",
"color_bsdf_component[<N>]" : "UABB",
"color_edf_component[<N>]" : "UAEE",
"color_vdf_component[<N>]" : "UAVV",
"color[<N>]" : "UACC",
# derived types
"struct { float[2], float[2], float[2] }" : "FD2",
}
# map type codes to suffixes for C runtime functions
self.m_type_suffixes = {
"BB" : "b", # not a runtime function
"II" : "i", # not a runtime function
"FF" : "f", # used by the C-runtime
"DD" : "" # no suffix used by the C-runtime
}
# create inverse mapping
self.m_inv_types = {}
# C runtime functions
self.m_c_runtime_functions = {}
# MDL atomic runtime functions
self.m_mdl_runtime_functions = {}
for type, code in self.m_types.items():
old_type = self.m_inv_types.setdefault(code, type)
if type != old_type:
error("type code %s is not unique, used by '%s' and '%s'" % (code, old_type, type))
def split_signature(self, signature):
"""Split a signature into return type and parameter types."""
params = signature.split('_')
ret_type = params[0]
params = params[1:]
if params == ['']:
# fix for no parameters
params = []
return ret_type, params
def get_atomic_type_kind(self, type_code):
"""If type_code is an atomic value, return its value kind, else None."""
cases = {
"bool": "mi::mdl::IType::TK_BOOL",
"int": "mi::mdl::IType::TK_INT",
"float": "mi::mdl::IType::TK_FLOAT",
"double": "mi::mdl::IType::TK_DOUBLE",
"color": "mi::mdl::IType::TK_COLOR",
"string": "mi::mdl::IType::TK_STRING",
"light_profile": "mi::mdl::IType::TK_LIGHT_PROFILE",
"bsdf_measurement": "mi::mdl::IType::TK_BSDF_MEASUREMENT",
}
return cases.get(self.m_inv_types[type_code], None)
def get_vector_type_kind(self, type_code):
"""If type_code is an vector value, return its type kind, else None."""
cases = {
"bool2": "mi::mdl::IType::TK_BOOL",
"bool3": "mi::mdl::IType::TK_BOOL",
"bool4": "mi::mdl::IType::TK_BOOL",
"int2": "mi::mdl::IType::TK_INT",
"int3": "mi::mdl::IType::TK_INT",
"int4": "mi::mdl::IType::TK_INT",
"float2": "mi::mdl::IType::TK_FLOAT",
"float3": "mi::mdl::IType::TK_FLOAT",
"float4": "mi::mdl::IType::TK_FLOAT",
"double2": "mi::mdl::IType::TK_DOUBLE",
"double3": "mi::mdl::IType::TK_DOUBLE",
"double4": "mi::mdl::IType::TK_DOUBLE",
}
return cases.get(self.m_inv_types[type_code], None)
def get_vector_type_and_size(self, type_code):
"""If type_code is an vector value, return its (element type, size) pair else None."""
cases = {
"bool2": ("bool", 2),
"bool3": ("bool", 3),
"bool4": ("bool", 4),
"int2": ("int", 2),
"int3": ("int", 3),
"int4": ("int", 4),
"float2": ("float", 2),
"float3": ("float", 3),
"float4": ("float", 4),
"double2": ("double", 2),
"double3": ("double", 3),
"double4": ("double", 4),
"color": ("float", 3)
}
return cases.get(self.m_inv_types[type_code], None)
def get_matrix_type_kind(self, type_code):
"""If type_code is an matrix value, return its type kind, else None."""
cases = {
"float2x2" : "mi::mdl::IType::TK_FLOAT",
"float2x3" : "mi::mdl::IType::TK_FLOAT",
"float2x4" : "mi::mdl::IType::TK_FLOAT",
"float3x2" : "mi::mdl::IType::TK_FLOAT",
"float3x3" : "mi::mdl::IType::TK_FLOAT",
"float3x4" : "mi::mdl::IType::TK_FLOAT",
"float4x2" : "mi::mdl::IType::TK_FLOAT",
"float4x3" : "mi::mdl::IType::TK_FLOAT",
"float4x4" : "mi::mdl::IType::TK_FLOAT",
"double2x2" : "mi::mdl::IType::TK_DOUBLE",
"double2x3" : "mi::mdl::IType::TK_DOUBLE",
"double2x4" : "mi::mdl::IType::TK_DOUBLE",
"double3x2" : "mi::mdl::IType::TK_DOUBLE",
"double3x3" : "mi::mdl::IType::TK_DOUBLE",
"double3x4" : "mi::mdl::IType::TK_DOUBLE",
"double4x2" : "mi::mdl::IType::TK_DOUBLE",
"double4x3" : "mi::mdl::IType::TK_DOUBLE",
"double4x4" : "mi::mdl::IType::TK_DOUBLE",
}
return cases.get(self.m_inv_types[type_code], None)
def get_texture_shape(self, type_code):
"""If type_code is a texture type, return its shape, else None."""
cases = {
"texture_2d" : "mi::mdl::IType_texture::TS_2D",
"texture_3d" : "mi::mdl::IType_texture::TS_3D",
"texture_cube" : "mi::mdl::IType_texture::TS_CUBE",
"texture_ptex" : "mi::mdl::IType_texture::TS_PTEX",
"texture_bsdf_data" : "mi::mdl::IType_texture::TS_BSDF_DATA",
}
return cases.get(self.m_inv_types[type_code], None)
def get_array_element_type(self, type_code):
"""If type_code is an array type, returns its element type (code), else None."""
cases = {
"FA2" : "FF",
"FA3" : "FF",
"FA4" : "FF",
"F2A2" : "F2",
"F3A2" : "F3",
"F4A2" : "F4",
"DA2" : "DD",
"D2A2" : "D2",
"D3A2" : "D3",
"D4A2" : "D4",
"IA3" : "II",
}
return cases.get(type_code, None)
def do_indentation(self, f):
"""Print current indentation."""
for i in range(self.indent):
f.write(" ")
def write(self, f, s):
"""write string s to file f after doing indent."""
i = 0
for c in s:
if c != '\n':
break
f.write(c)
i += 1
s = s[i:]
if s == "":
return
self.do_indentation(f)
f.write(s)
def format_code(self, f, code):
"""The (not so) smart code formater."""
skip_spaces = True
for c in code:
if skip_spaces:
# skip spaces
if c == '\n':
f.write(c)
if c.isspace():
continue
if c == '}' or c == ')':
self.indent -= 1
self.do_indentation(f)
skip_spaces = False
if c == '}' or c == ')':
f.write(c)
continue
if not skip_spaces:
# copy mode
f.write(c)
if c == '\n':
skip_spaces = True
elif c == '{' or c == '(':
self.indent += 1
elif c == '}' or c == ')':
self.indent -= 1
def parse(self, mdl_name):
"""Parse a mdl module."""
self.curr_module = mdl_name
fname = self.indir + "/" + mdl_name + ".mdl"
f = open(fname, "r")
o = self.parse_file(f)
f.close()
def parse_builtins(self, buffer):
"""Parse a mdl module given as buffer."""
self.curr_module = ""
o = self.parse_buffer(buffer)
def as_intrinsic_function(self, decl):
"""Check if the given declaration is an intrinsic function declaration."""
if decl[:5] == "const":
return None
if decl[:4] == "enum":
return None
if decl[:5] == "struct":
return None
if decl[:8] == "material":
return None
m = self.r_intrinsic.search(decl)
if m:
decl = decl[:m.start()]
# kill all other annotations
return re.sub(r'\[\[[^]]*\]\]', "", decl).strip()
return None
def get_type(self, tokens):
"""decode a type"""
start = 0
end = 1
if tokens[0] == "uniform" or tokens[0] == "varying":
# skip uniform and varying modifier
end += 1
start += 1
ret_type = " ".join(tokens[start:end])
return tokens[end:], ret_type
def do_get_type_code(self, s):
"""get the type code"""
try:
return self.m_types[s]
except KeyError:
error("Unsupported type '" + s + "' found")
sys.exit(1)
def get_type_suffix(self, s):
"""get the type suffix"""
try:
return self.m_type_suffixes[s]
except KeyError:
error("Unsupported type '" + s + "' found")
sys.exit(1)
def get_type_code(self, s):
"""get the type code"""
c = self.do_get_type_code(s)
return c
def create_signature(self, ret_type, args):
"""create the signature"""
ret_tp = self.get_type_code(ret_type)
sig = "_"
comma = ''
for arg in args:
sig += comma + self.get_type_code(arg)
comma = '_'
return ret_tp + sig
def is_float_type(self, type_code):
"""If type_code is an float type, return True, else False."""
cases = {
"float": True,
"double": True,
}
return cases.get(self.m_inv_types[type_code], False)
def is_int_type(self, type_code):
"""If type_code is an int type, return True, else False."""
return self.m_inv_types[type_code] == "int"
def is_bool_type(self, type_code):
"""If type_code is a bool type, return True, else False."""
return self.m_inv_types[type_code] == "bool"
def is_atomic_type(self, type_code):
"""If type_code is a bool, int, or float type, return True, else False."""
return self.is_bool_type(type_code) or self.is_int_type(type_code) or self.is_float_type(type_code)
def register_runtime_func(self, fname, signature):
"""Register a C runtime function by name and signature."""
if self.m_c_runtime_functions.get(fname) != None:
error("C runtime function '%s' already registered\n" % fname)
self.m_c_runtime_functions[fname] = signature
def register_mdl_runtime_func(self, fname, signature):
"""Register a mdl runtime function by name and signature."""
if self.m_mdl_runtime_functions.get(fname) != None:
error("MDL runtime function '%s' already registered\n" % fname)
self.m_mdl_runtime_functions[fname] = signature
def is_state_supported(self, name, signature):
"""Checks if the given state intrinsic is supported."""
if (name == "normal" or name == "geometry_normal" or name == "position" or
name == "animation_time"):
self.intrinsic_modes[name + signature] = "state::core_set"
return True
elif name == "rounded_corner_normal":
self.intrinsic_modes[name + signature] = "state::rounded_corner_normal"
return True
elif name == "texture_coordinate":
self.intrinsic_modes[name + signature] = "state::texture_coordinate"
return True
elif name == "texture_space_max":
self.intrinsic_modes[name + signature] = "state::texture_space_max"
return True
elif name == "texture_tangent_u":
self.intrinsic_modes[name + signature] = "state::texture_tangent_u"
return True
elif name == "texture_tangent_v":
self.intrinsic_modes[name + signature] = "state::texture_tangent_v"
return True
elif name == "geometry_tangent_u":
self.intrinsic_modes[name + signature] = "state::geometry_tangent_u"
return True
elif name == "geometry_tangent_v":
self.intrinsic_modes[name + signature] = "state::geometry_tangent_v"
return True
elif name == "direction":
self.intrinsic_modes[name + signature] = "state::environment_set"
return True
elif name == "transform":
self.intrinsic_modes[name + signature] = "state::transform"
return True
elif name == "transform_point":
self.intrinsic_modes[name + signature] = "state::transform_point"
return True
elif name == "transform_vector":
self.intrinsic_modes[name + signature] = "state::transform_vector"
return True
elif name == "transform_normal":
self.intrinsic_modes[name + signature] = "state::transform_normal"
return True
elif name == "transform_scale":
self.intrinsic_modes[name + signature] = "state::transform_scale"
return True
elif name == "meters_per_scene_unit":
self.intrinsic_modes[name + signature] = "state::meters_per_scene_unit"
return True
elif name == "scene_units_per_meter":
self.intrinsic_modes[name + signature] = "state::scene_units_per_meter"
return True
elif name == "wavelength_min" or name == "wavelength_max":
self.intrinsic_modes[name + signature] = "state::wavelength_min_max"
return True
elif name == "object_id":
# these should be handled by the code generator directly and never be
# called here
self.intrinsic_modes[name + signature] = "state::zero_return"
return True
else:
#warning("state::%s() will be mapped to zero" % name)
self.intrinsic_modes[name + signature] = "state::zero_return"
return True
return False
def is_df_supported(self, name, signature):
"""Checks if the given df intrinsic is supported."""
ret_type, params = self.split_signature(signature)
if (name == "diffuse_reflection_bsdf" or
name == "dusty_diffuse_reflection_bsdf" or
name == "diffuse_transmission_bsdf" or
name == "specular_bsdf" or
name == "simple_glossy_bsdf" or
name == "backscattering_glossy_reflection_bsdf" or
name == "measured_bsdf" or
name == "microfacet_beckmann_smith_bsdf" or
name == "microfacet_ggx_smith_bsdf" or
name == "microfacet_beckmann_vcavities_bsdf" or
name == "microfacet_ggx_vcavities_bsdf" or
name == "ward_geisler_moroder_bsdf" or
name == "diffuse_edf" or
name == "spot_edf" or
name == "measured_edf" or
name == "anisotropic_vdf" or
name == "fog_vdf" or
name == "tint" or
name == "thin_film" or
name == "directional_factor" or
name == "normalized_mix" or
name == "clamped_mix" or
name == "weighted_layer" or
name == "fresnel_layer" or
name == "custom_curve_layer" or
name == "measured_curve_layer" or
name == "measured_curve_factor" or
name == "color_normalized_mix" or
name == "color_clamped_mix" or
name == "color_weighted_layer" or
name == "color_fresnel_layer" or
name == "color_custom_curve_layer" or
name == "color_measured_curve_layer" or
name == "fresnel_factor" or
name == "measured_factor" or
name == "chiang_hair_bsdf" or
name == "sheen_bsdf" or
name == "unbounded_mix" or
name == "color_unbounded_mix"):
self.unsupported_intrinsics[name] = "unsupported"
return True;
if (name == "light_profile_power" or name == "light_profile_maximum" or
name == "light_profile_isvalid"):
if len(params) == 1:
# support light_profile_power(), light_profile_maximum(), light_profile_isvalid()
self.intrinsic_modes[name + signature] = "df::attr_lookup"
return True
elif name == "bsdf_measurement_isvalid":
if len(params) == 1:
# support bsdf_measurement_isvalid()
self.intrinsic_modes[name + signature] = "df::attr_lookup"
return True
return False
def is_tex_supported(self, name, signature):
"""Checks if the given tex intrinsic is supported."""
ret_type, params = self.split_signature(signature)
if name == "width" or name == "height" or name == "depth":
if (len(params) == 1):
# support width(), height(), depth(), without extra parameters
self.intrinsic_modes[name + signature] = "tex::attr_lookup"
return True
if params[0] == "T2":
if len(params) == 2:
# support width(), height() with uv_tile parameter
self.intrinsic_modes[name + signature] = "tex::attr_lookup_uvtile"
return True
if len(params) == 3:
# support width(), height() with uv_tile, frame parameters
self.intrinsic_modes[name + signature] = "tex::attr_lookup_uvtile_frame"
return True
elif params[0] == "T3":
if len(params) == 2:
# support width(), height(), depth() with frame parameter
self.intrinsic_modes[name + signature] = "tex::attr_lookup_frame"
return True
elif name == "texture_isvalid":
if len(params) == 1:
# support texture_isvalid()
self.intrinsic_modes[name + signature] = "tex::attr_lookup"
return True
elif name == "first_frame" or name == "last_frame":
if len(params) == 1:
# support first_frame(), last_frame()
self.intrinsic_modes[name + signature] = "tex::frame"
return True
elif name == "lookup_float":
# support lookup_float()
self.intrinsic_modes[name + signature] = "tex::lookup_float"
return True
elif (name == "lookup_float2" or name == "lookup_float3" or
name == "lookup_float4" or name == "lookup_color"):
# support lookup_float2|3|4|color()
self.intrinsic_modes[name + signature] = "tex::lookup_floatX"
return True
elif name == "texel_float":
if len(params) == 2:
# support texel_float() without extra parameter
self.intrinsic_modes[name + signature] = "tex::texel_float"
return True
if params[0] == "T2":
if len(params) == 3:
# support texel_float(texture_2d) with uv_tile parameter
self.intrinsic_modes[name + signature] = "tex::texel_float_uvtile"
return True
if len(params) == 4:
# support texel_float(texture_2d) with uv_tile, frame parameter
self.intrinsic_modes[name + signature] = "tex::texel_float_uvtile_frame"
return True
elif params[0] == "T3":
if len(params) == 3:
# support texel_float(texture_3d) with frame parameter
self.intrinsic_modes[name + signature] = "tex::texel_float_frame"
return True
elif (name == "texel_float2" or name == "texel_float3" or
name == "texel_float4" or name == "texel_color"):
if (len(params) == 2):
# support texel_float2|3|4|color() without uv_tile parameter
self.intrinsic_modes[name + signature] = "tex::texel_floatX"
return True
if params[0] == "T2":
if len(params) == 3:
# support texel_float2|3|4|color(texture_2d) with uv_tile parameter
self.intrinsic_modes[name + signature] = "tex::texel_floatX_uvtile"
return True
if len(params) == 4:
# support texel_float2|3|4|color(texture_2d) with uv_tile, frame parameter
self.intrinsic_modes[name + signature] = "tex::texel_floatX_uvtile_frame"
return True
elif params[0] == "T3":
if len(params) == 3:
# support texel_float2|3|4|color(texture_3d) with frame parameter
self.intrinsic_modes[name + signature] = "tex::texel_floatX_frame"
return True
elif (name == "width_offset" or name == "height_offset" or
name == "depth_offset"):
# for now, these return 0
self.intrinsic_modes[name + signature] = "tex::zero_return"
return True
elif name == "grid_to_object_space":
# FIXME: for now, these return 0
self.intrinsic_modes[name + signature] = "tex::zero_return"
return True
return False
def is_scene_supported(self, name, signature):
"""Checks if the given scene intrinsic is supported."""
ret_type, params = self.split_signature(signature)
if re.match("data_lookup_(float|int)$", name):
self.intrinsic_modes[name + signature] = "scene::data_lookup_atomic"
return True
elif re.match("data_lookup_uniform_(float|int)$", name):
self.intrinsic_modes[name + signature] = "scene::data_lookup_uniform_atomic"
return True
elif re.match("data_lookup_(float2|float3|float4|float4x4|color|int2|int3|int4)$", name):
self.intrinsic_modes[name + signature] = "scene::data_lookup_vector"
return True
elif re.match("data_lookup_uniform_(float2|float3|float4|float4x4|color|int2|int3|int4)$", name):
self.intrinsic_modes[name + signature] = "scene::data_lookup_uniform_vector"
return True
elif name == "data_isvalid":
self.intrinsic_modes[name + signature] = "scene::data_isvalid"
return True
return False
def is_builtin_supported(self, name, signature):
"""Checks if the given builtin intrinsic is supported."""
ret_type, params = self.split_signature(signature)
if name == "color":
if len(params) == 2:
# support color(float[<N>], float[N])
self.intrinsic_modes[name + signature] = "spectrum_constructor"
return True
return False
def is_debug_supported(self, name, signature):
"""Checks if the given debug intrinsic is supported."""
ret_type, params = self.split_signature(signature)
if name == "breakpoint":
if len(params) == 0:
# support breakpoint()
self.intrinsic_modes[name + signature] = "debug::breakpoint"
return True
elif name == "assert":
if len(params) == 5:
# support assert(expr, reason)
self.intrinsic_modes[name + signature] = "debug::assert"
return True
elif name == "print":
if len(params) == 1 or len(params) == 3:
# support print()
self.intrinsic_modes[name + signature] = "debug::print"
return True
return False
def is_math_supported(self, name, signature):
"""Checks if the given math intrinsic is supported."""
ret_type, params = self.split_signature(signature)
base = None
dim = 0
vt = self.get_vector_type_and_size(ret_type)
if vt:
base = vt[0]
dim = vt[1]
all_atomic = self.is_atomic_type(ret_type)
all_base_same = base != None
for param in params:
if not self.is_atomic_type(param):
all_atomic = False
if self.m_inv_types[param] != base:
vt = self.get_vector_type_and_size(param)
if not vt or vt[0] != base or vt[1] != dim:
all_base_same = False
if len(params) == 3:
if name == "lerp":
# support lerp with 3 arguments
self.intrinsic_modes[name + signature] = "math::lerp"
return True
elif len(params) == 2:
if name == "dot":
# support dot with 2 arguments
self.intrinsic_modes[name + signature] = "math::dot"
return True
elif name == "step":
# support step with 2 arguments
self.intrinsic_modes[name + signature] = "math::step"
return True
elif name == "distance":
# support distance(floatX)
self.intrinsic_modes[name + signature] = "math::distance"
return True
elif name == "emission_color":
# support emission_color(float[<N>], float[N])
self.intrinsic_modes[name + signature] = "math::emission_color"
return True
elif name == "eval_at_wavelength":
# support eval_at_wavelength(color,float)
self.intrinsic_modes[name + signature] = "math::eval_at_wavelength"
return True
elif len(params) == 1:
if name == "any" or name == "all":
# support any and all with one argument
self.intrinsic_modes[name + signature] = "math::any|all"
return True
if name == "average":
# support average with one argument
self.intrinsic_modes[name + signature] = "math::average"
return True
elif name == "degrees":
# support degrees with 1 argument
self.intrinsic_modes[name + signature] = "math::const_mul"
self.cnst_mul[name] = "180.0 / M_PI"
return True
elif name == "radians":
# support radians with 1 argument
self.intrinsic_modes[name + signature] = "math::const_mul"
self.cnst_mul[name] = "M_PI / 180.0"
return True
elif name == "min_value" or name == "max_value":
# support min_value/max_value with 1 argument
self.intrinsic_modes[name + signature] = "math::min_value|max_value"
return True
elif name == "min_value_wavelength" or name == "max_value_wavelength":
# support min_value_wavelength/max_value_wavelength with 1 argument
self.intrinsic_modes[name + signature] = "math::min_value_wavelength|max_value_wavelength"
return True
elif name == "isnan" or name == "isfinite":
if self.get_vector_type_and_size(params[0]) or self.is_atomic_type(params[0]):
# support all isnan/isfinite with one argument
self.intrinsic_modes[name + signature] = "math::isnan|isfinite"
return True
elif name == "blackbody":
# support blackbody with 1 argument
self.intrinsic_modes[name + signature] = "math::blackbody"
return True
elif name == "emission_color":
# supported emission_color(color)
self.intrinsic_modes[name + signature] = "math::first_arg"
return True
elif name == "length":
# support length(floatX)
self.intrinsic_modes[name + signature] = "math::length"
return True
elif name == "normalize":
# support normalize(floatX)
self.intrinsic_modes[name + signature] = "math::normalize"
return True
elif name == "DX" or name == "DY":
# support DX(floatX), DY(floatX)
self.intrinsic_modes[name + signature] = "math::DX|DY"
return True
if all_atomic and self.is_atomic_type(ret_type):
if name == "log10":
self.intrinsic_modes[name + signature] = "math::log10_atomic"
return True
# simple all float/int/bool functions
self.intrinsic_modes[name + signature] = "math::all_atomic"
return True
if len(params) == 1:
if name == "luminance":
if params[0] == "F3" or params[0] == "CC":
# support luminance(float3) and luminance(color)
self.intrinsic_modes[name + signature] = "math::luminance"
return True
elif name == "transpose":
if self.get_matrix_type_kind(params[0]):
# support transpose(floatX)
self.intrinsic_modes[name + signature] = "math::transpose"
return True
if name == "cross":
if signature == "F3_F3_F3" or signature == "D3_D3_D3":
# the only supported cross variant
self.intrinsic_modes[name + signature] = "math::cross"
return True
else:
return False
if name == "sincos":
if len(params) == 1:
arg_tp = params[0]
if self.is_float_type(arg_tp):
# support sincos for float types
self.intrinsic_modes[name + signature] = "math::sincos"
return True
vt = self.get_vector_type_and_size(arg_tp)
if vt and (vt[0] == "float" or vt[0] == "double"):
# support sincos for float vector types
self.intrinsic_modes[name + signature] = "math::sincos"
return True
return False
if name == "modf":
if len(params) == 1:
arg_tp = params[0]
if self.is_float_type(arg_tp):
# support modf for float types
self.intrinsic_modes[name + signature] = "math::modf"
return True
vt = self.get_vector_type_and_size(arg_tp)
if vt and (vt[0] == "float" or vt[0] == "double"):
# support modf for float vector types
self.intrinsic_modes[name + signature] = "math::modf"
return True
return False
if all_base_same:
# assume component operation
self.intrinsic_modes[name + signature] = "math::component_wise"
return True
return False
def is_supported(self, modname, name, signature):
"""Checks if the given intrinsic is supported."""
if modname == "math":
return self.is_math_supported(name, signature)
elif modname == "state":
return self.is_state_supported(name, signature)
elif modname == "df":
return self.is_df_supported(name, signature)
elif modname == "tex":
return self.is_tex_supported(name, signature)
elif modname == "scene":
return self.is_scene_supported(name, signature)
elif modname == "debug":
return self.is_debug_supported(name, signature)
elif modname == "":
return self.is_builtin_supported(name, signature)
return False
def skip_until(self, token_set, tokens):
"""skip tokens until token_kind is found, handle parenthesis"""
r = 0
e = 0
g = 0
a = 0
l = len(tokens)
while l > 0:
tok = tokens[0]
if r == 0 and e == 0 and g == 0 and a == 0 and tok in token_set:
return tokens
if tok == '(':
r += 1
elif tok == ')':
r -= 1
elif tok == '[':
e += 1
elif tok == ']':
e -= 1
elif tok == '{':
g += 1
elif tok == '}':
g -= 1
elif tok == '[[':
a += 1
elif tok == ']]':
a -= 1
tokens = tokens[1:]
l -= 1
# do not return empty tokens, the parser do not like that
return [None]
def get_signature(self, decl):
"""Get the signature for a given function declaration."""
# poor man's scanner :-)
tokens = re.sub(r'[,()]', lambda m: ' ' + m.group(0) + ' ', decl).split()
tokens, ret_type = self.get_type(tokens)
name = tokens[0]
self.m_intrinsic_mods[name] = self.curr_module
if tokens[1] != '(':
error("unknown token '" + tokens[1] + "' while processing '" + decl + "': '(' expected")
sys.exit(1)
tokens = tokens[2:]
args = []
if tokens[0] != ')':
while True:
tokens, t = self.get_type(tokens)
args.append(t)
# throw away the name
tokens = tokens[1:]
if tokens[0] == '=':
# default argument
tokens = self.skip_until({',':None, ')':None}, tokens[1:])
if tokens[0] == ')':
break
if tokens[0] != ',':
error("unknown token '" + tokens[1] + "' while processing '"
+ decl + "': ',' expected")
sys.exit(1)
# skip the comma
tokens = tokens[1:]
signature = self.create_signature(ret_type, args)
if self.debug:
print("%s %s" % (decl, signature))
if self.is_supported(self.curr_module, name, signature):
# insert the new signature for the given name
sigs = self.m_intrinsics.setdefault(name, {})
sigs[signature] = True
# remember the signature (without return type)
_, params = self.split_signature(signature)
self.m_signatures["_".join(params)] = True
else:
warning("Cannot generate code for %s" % decl)
def parse_lines(self, lines):
"""Parse lines and retrieve intrinsic function definitions."""
start = False
curr_line = ""
for line in lines:
l = line.strip();
# strip line comments
idx = l.find('//')
if idx != -1:
l = l[:idx]
if not start:
if l[:6] == "export":
start = True
curr_line = l[7:].strip()
else:
curr_line += l
if start:
if l[-1] == ";":
start = False
decl = self.as_intrinsic_function(curr_line)
if not decl:
continue
if self.debug:
print(decl)
self.get_signature(decl)
def parse_file(self, f):
"""Parse a file and retrieve intrinsic function definitions."""
self.parse_lines(f.readlines())
def parse_buffer(self, buffer):
"""Parse a string and retrieve intrinsic function definitions."""
self.parse_lines(buffer.splitlines())
def gen_condition(self, f, params, as_assert, pre_if = ""):
"""Generate the condition for the parameter type check."""
if len(params) == 0:
# we don't need a check if no parameters exists
return False
if as_assert:
self.write(f, "MDL_ASSERT(check_sig_%s(f_type));\n" % "_".join(params))
return False
else:
self.write(f, "%sif (check_sig_%s(f_type)) {\n" % (pre_if, "_".join(params)))
return True
def get_mangled_state_func_name(self, intrinsic, first_ptr_param):
has_index = intrinsic in ["texture_coordinate", "texture_tangent_u", "texture_tangent_v",
"tangent_space", "geometry_tangent_u", "geometry_tangent_v"]
name = "_ZN5state%d%sE" % (len(intrinsic), intrinsic)
if first_ptr_param:
# one of the non-const functions?
if intrinsic in ["set_normal", "get_texture_results"]:
name += "P%d%s" % (len(first_ptr_param), first_ptr_param)
else:
name += "PK%d%s" % (len(first_ptr_param), first_ptr_param)
if has_index:
name += "PK15Exception_statei" # throws due to out-of-bounds check
if intrinsic.startswith("transform"):
name += "NS_16coordinate_spaceES3_"
if intrinsic in ["transform_point", "transform_vector", "transform_normal"]:
name += "Dv3_f"
elif intrinsic == "transform_scale":
name += "f"
# only version 1.3 variant
if intrinsic == "rounded_corner_normal":
name += "fcf"
if intrinsic == "set_normal":
name += "Dv3_f"
return name
def create_lazy_ir_construction(self, f, intrinsic, signature):
"""Create a lazy IR construction call for a given intrinsic, signature pair."""
ret_type, params = self.split_signature(signature)
mode = self.intrinsic_modes.get(intrinsic + signature)
func_index = self.get_function_index((intrinsic, signature))
self.write(f, "if (llvm::Function *func = m_intrinsics[%d * 2 + return_derivs])\n" %
func_index)
self.indent += 1
self.write(f, "return func;\n")
self.indent -= 1
mod_name = self.m_intrinsic_mods[intrinsic]
if mod_name == "state":
self.write(f, "if (m_use_user_state_module) {\n")
self.indent += 1;
self.write(f, "llvm::Function *func;\n")
self.write(f, "if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE)\n")
self.indent += 1
self.write(f, "func = m_code_gen.get_llvm_module()->getFunction(\"%s\");\n"
% self.get_mangled_state_func_name(intrinsic, "State_core"))
self.indent -= 1
self.write(f, "else\n")
self.indent += 1
self.write(f, "func = m_code_gen.get_llvm_module()->getFunction(\"%s\");\n"
% self.get_mangled_state_func_name(intrinsic, "State_environment"))
self.indent -= 1
self.write(f, "if (func != NULL) {\n")
self.indent += 1
self.write(f, "m_code_gen.create_context_data(func_def, return_derivs, func);\n")
self.write(f, "return m_intrinsics[%d * 2 + return_derivs] = func;\n" % func_index)
self.indent -= 1
self.write(f, "}\n")
self.indent -= 1
self.write(f, "}\n")
suffix = signature
if suffix[-1] == '_':
# no parameters
suffix = suffix[:-1]
self.write(f, "return m_intrinsics[%d * 2 + return_derivs] = create_%s_%s_%s(func_def, return_derivs);\n" %
(func_index, mod_name, intrinsic, suffix))
def create_ir_constructor(self, f, intrinsic, signature):
"""Create the evaluation call for a given intrinsic, signature pair."""
if self.unsupported_intrinsics.get(intrinsic):
# we cannot create code for unsupported functions, these should not occur
return
mod_name = self.m_intrinsic_mods[intrinsic]
suffix = signature
if suffix[-1] == '_':
# no parameters
suffix = suffix[:-1]
self.write(f, "/// Generate LLVM IR for %s::%s_%s()\n" % (mod_name, intrinsic, suffix))
self.write(f, "llvm::Function *create_%s_%s_%s(mi::mdl::IDefinition const *func_def, bool return_derivs)\n" % (mod_name, intrinsic, suffix))
self.write(f, "{\n")
self.indent += 1
self.create_ir_constructor_body(f, intrinsic, signature)
self.indent -= 1
self.write(f, "}\n\n")
def get_runtime_enum(self, runtime_func):
"""Return the name of the Runtime_function enum value for the given runtime function."""
# first check for MDL runtime functions, those are more specific
if self.m_mdl_runtime_functions.get("mdl_" + runtime_func):
return "RT_MDL_" + runtime_func.upper()
if self.m_c_runtime_functions.get(runtime_func):
return "RT_" + runtime_func.upper()
error("Unknown runtime function '%s'" % runtime_func)
return None
def create_ir_constructor_body(self, f, intrinsic, signature):
"""Create the constructor body for a given intrinsic, signature pair."""
mode = self.intrinsic_modes.get(intrinsic + signature)
if mode == None:
error("%s%s" % (intrinsic, signature))
params = { "mode" : "::" + self.m_intrinsic_mods[intrinsic] }
if params["mode"] == "::":
params["mode"] = "::<builtins>"
code = """
Function_instance inst(m_code_gen.get_allocator(), func_def, return_derivs);
LLVM_context_data *ctx_data = m_code_gen.get_or_create_context_data(NULL, inst, "%(mode)s");
llvm::Function *func = ctx_data->get_function();
unsigned flags = ctx_data->get_function_flags();
Function_context ctx(m_alloc, m_code_gen, inst, func, flags);
llvm::Value *res;
func->setLinkage(llvm::GlobalValue::InternalLinkage);
m_code_gen.add_generated_attributes(func);
"""
self.format_code(f, code % params)
ret_type, params = self.split_signature(signature)
need_res_data = mode[0:5] == "tex::" or mode == "df::attr_lookup" or mode[0:7] == "scene::"
if need_res_data or params != []:
self.write(f, "llvm::Function::arg_iterator arg_it = ctx.get_first_parameter();\n")
comma = '\n'
if need_res_data:
# first parameter is the texture_data pointer
self.write(f, "llvm::Value *res_data = ctx.get_resource_data_parameter();")
if params != []:
idx = 0
for param in params:
f.write(comma)
comma = '++);\n'
self.write(f, "llvm::Value *%s = load_by_value(ctx, arg_it" % chr(ord('a') + idx))
idx += 1
if need_res_data or params != []:
f.write(');\n\n')
if mode == "math::all_atomic":
suffix = self.get_type_suffix(params[0])
suffix_upper = suffix.upper()
enum_value = self.get_runtime_enum(intrinsic + suffix)
type = self.m_inv_types[params[0]]
self.format_code(f,
"""// atomic
llvm::Function *callee = get_runtime_func(%s);
llvm::Value *call_args[%d];
if (inst.get_return_derivs()) {
""" % (enum_value, len(params)))
for idx, param in enumerate(params):
self.write(f, "call_args[%d] = ctx.get_dual_val(%s);\n"
% (idx, chr(ord('a') + idx)))
self.write(f, "llvm::Value *val = ctx->CreateCall(callee, call_args);\n")
# Calculate derivatives for specific functions
if enum_value == "RT_ABS" + suffix_upper:
self.format_code(f, """
// abs'(a) = a < 0 ? -a' : a'
llvm::Value *is_neg = ctx->CreateFCmpOLT(ctx.get_dual_val(a), ctx.get_constant(%(type)s(0)));
llvm::Value *a_dx = ctx.get_dual_dx(a);
llvm::Value *a_dy = ctx.get_dual_dy(a);
llvm::Value *neg_a_dx = ctx->CreateFNeg(a_dx);
llvm::Value *neg_a_dy = ctx->CreateFNeg(a_dy);
llvm::Value *dx = ctx->CreateSelect(is_neg, neg_a_dx, a_dx);
llvm::Value *dy = ctx->CreateSelect(is_neg, neg_a_dy, a_dy);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_ACOS" + suffix_upper or enum_value == "RT_ASIN" + suffix_upper:
self.format_code(f, """
// acos'(a) = -a' / sqrt(1 - a^2) for x in (-1, 1), 0 otherwise
// asin'(a) = a' / sqrt(1 - a^2) for x in (-1, 1), 0 otherwise
llvm::Function *sqrt_func = get_runtime_func(%(sqrt_name)s);
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *a_square = ctx->CreateFMul(a_val, a_val);
llvm::Value *sqrt_args[1] = { ctx->CreateFSub(ctx.get_constant(%(type)s(1)), a_square) };
llvm::Value *sqrt_res = ctx->CreateCall(sqrt_func, sqrt_args);
llvm::Value *dx_res = ctx->CreateFDiv(ctx.get_dual_dx(a), sqrt_res);
llvm::Value *dy_res = ctx->CreateFDiv(ctx.get_dual_dy(a), sqrt_res);
""" % { "sqrt_name": "RT_SQRT" + suffix_upper, "type": type })
if enum_value == "RT_ACOS" + suffix_upper:
self.format_code(f, """
dx_res = ctx->CreateFNeg(dx_res);
dy_res = ctx->CreateFNeg(dy_res);
""")
self.format_code(f, """
llvm::Value *too_small = ctx->CreateFCmpOLE(a_val, ctx.get_constant(%(type)s(-1)));
llvm::Value *too_big = ctx->CreateFCmpOGE(a_val, ctx.get_constant(%(type)s(1)));
llvm::Value *is_undef = ctx->CreateOr(too_small, too_big);
llvm::Value *dx = ctx->CreateSelect(is_undef, ctx.get_constant(%(type)s(0)), dx_res);
llvm::Value *dy = ctx->CreateSelect(is_undef, ctx.get_constant(%(type)s(0)), dy_res);
res = ctx.get_dual(val, dx, dy);
""" % {"type": type })
elif enum_value == "RT_ATAN" + suffix_upper:
self.format_code(f, """
// atan'(a) = a' / (a^2 + 1)
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *a_square = ctx->CreateFMul(a_val, a_val);
llvm::Value *divisor = ctx->CreateFAdd(a_square, ctx.get_constant(%(type)s(1)));
llvm::Value *dx = ctx->CreateFDiv(ctx.get_dual_dx(a), divisor);
llvm::Value *dy = ctx->CreateFDiv(ctx.get_dual_dy(a), divisor);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_ATAN2" + suffix_upper:
self.format_code(f, """
// atan2'(a, b) = (b(x) * a'(x) - a(x) * b'(x)) / (a(x)^2 + b(x)^2)
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *b_val = ctx.get_dual_val(b);
llvm::Value *a_square = ctx->CreateFMul(a_val, a_val);
llvm::Value *b_square = ctx->CreateFMul(b_val, b_val);
llvm::Value *divisor = ctx->CreateFAdd(a_square, b_square);
llvm::Value *dividend_dx = ctx->CreateFSub(
ctx->CreateFMul(b_val, ctx.get_dual_dx(a)),
ctx->CreateFMul(a_val, ctx.get_dual_dx(b)));
llvm::Value *dividend_dy = ctx->CreateFSub(
ctx->CreateFMul(b_val, ctx.get_dual_dy(a)),
ctx->CreateFMul(a_val, ctx.get_dual_dy(b)));
llvm::Value *dx = ctx->CreateFDiv(dividend_dx, divisor);
llvm::Value *dy = ctx->CreateFDiv(dividend_dy, divisor);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_MDL_CLAMP" + suffix_upper:
self.format_code(f, """
// clamp'(a, b, c) = a' for x in (b, c), b' for x <= b, c' for x >= c
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *is_too_small = ctx->CreateFCmpOLE(a_val, ctx.get_dual_val(b));
llvm::Value *is_too_big = ctx->CreateFCmpOGE(a_val, ctx.get_dual_val(c));
llvm::Value *is_out_of_interval = ctx->CreateOr(is_too_small, is_too_big);
llvm::Value *out_of_interval_dx = ctx->CreateSelect(
is_too_small, ctx.get_dual_dx(b), ctx.get_dual_dx(c));
llvm::Value *out_of_interval_dy = ctx->CreateSelect(
is_too_small, ctx.get_dual_dy(b), ctx.get_dual_dy(c));
llvm::Value *dx = ctx->CreateSelect(is_out_of_interval, out_of_interval_dx, ctx.get_dual_dx(a));
llvm::Value *dy = ctx->CreateSelect(is_out_of_interval, out_of_interval_dy, ctx.get_dual_dy(a));
res = ctx.get_dual(val, dx, dy);
""" % {"type": type })
elif enum_value == "RT_COS" + suffix_upper:
self.format_code(f, """
// cos'(a) = a' * (-sin(a))
llvm::Function *sin_func = get_runtime_func(%(sin_name)s);
llvm::Value *sin_val = ctx->CreateCall(sin_func, call_args);
llvm::Value *neg_sin_val = ctx->CreateFNeg(sin_val);
llvm::Value *dx = ctx->CreateFMul(ctx.get_dual_dx(a), neg_sin_val);
llvm::Value *dy = ctx->CreateFMul(ctx.get_dual_dy(a), neg_sin_val);
res = ctx.get_dual(val, dx, dy);
""" % { "sin_name": "RT_SIN" + suffix_upper })
elif enum_value == "RT_EXP" + suffix_upper:
self.format_code(f, """
// exp'(a) = a' * exp(a)
llvm::Value *dx = ctx->CreateFMul(ctx.get_dual_dx(a), val);
llvm::Value *dy = ctx->CreateFMul(ctx.get_dual_dy(a), val);
res = ctx.get_dual(val, dx, dy);
""")
elif enum_value == "RT_MDL_EXP2" + suffix_upper:
self.format_code(f, """
// exp2'(a) = log(2) * a' * exp2(a)
llvm::Value *log_2 = ctx.get_constant(%(type)s(0.69314718055994530941723212145818));
llvm::Value *val_log_2 = ctx->CreateFMul(log_2, val);
llvm::Value *dx = ctx->CreateFMul(ctx.get_dual_dx(a), val_log_2);
llvm::Value *dy = ctx->CreateFMul(ctx.get_dual_dy(a), val_log_2);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type } )
elif enum_value == "RT_FMOD" + suffix_upper:
self.format_code(f, """
// fmod(a, b) = a - b * int(a / b)
// fmod'(a, b) = a' - (b * int'(a / b) + b' * int(a / b)) = a' - b' * int(a / b)
// Note: FPToSI rounds towards zero
llvm::Value *int_a_over_b = ctx->CreateFPToSI(
ctx->CreateFDiv(ctx.get_dual_val(a), ctx.get_dual_val(b)),
m_code_gen.m_type_mapper.get_int_type());
llvm::Value *trimmed_a_over_b = ctx->CreateSIToFP(
int_a_over_b, m_code_gen.m_type_mapper.get_float_type());
llvm::Value *dx = ctx->CreateFSub(
ctx.get_dual_dx(a),
ctx->CreateFMul(ctx.get_dual_dx(b), trimmed_a_over_b));
llvm::Value *dy = ctx->CreateFSub(
ctx.get_dual_dy(a),
ctx->CreateFMul(ctx.get_dual_dy(b), trimmed_a_over_b));
res = ctx.get_dual(val, dx, dy);
""")
elif enum_value == "RT_MDL_FRAC" + suffix_upper:
self.format_code(f, """
// frac'(a) = a'
llvm::Value *dx = ctx.get_dual_dx(a);
llvm::Value *dy = ctx.get_dual_dy(a);
res = ctx.get_dual(val, dx, dy);
""")
elif enum_value == "RT_LOG" + suffix_upper:
self.format_code(f, """
// log'(a) = a' * 1/a for a > 0, 0 otherwise
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *r_a_val = ctx->CreateFDiv(ctx.get_constant(%(type)s(1)), a_val);
llvm::Value *dx_res = ctx->CreateFMul(ctx.get_dual_dx(a), r_a_val);
llvm::Value *dy_res = ctx->CreateFMul(ctx.get_dual_dy(a), r_a_val);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *too_small = ctx->CreateFCmpOLE(a_val, zero);
llvm::Value *dx = ctx->CreateSelect(too_small, zero, dx_res);
llvm::Value *dy = ctx->CreateSelect(too_small, zero, dy_res);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_MDL_LOG2" + suffix_upper:
self.format_code(f, """
// log2'(a) = a' * 1/a * 1/log(2) for a > 0, 0 otherwise
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *r_a_log_2 = ctx->CreateFDiv(
ctx.get_constant(%(type)s(1.4426950408889634073599246810019)), a_val);
llvm::Value *dx_res = ctx->CreateFMul(ctx.get_dual_dx(a), r_a_log_2);
llvm::Value *dy_res = ctx->CreateFMul(ctx.get_dual_dy(a), r_a_log_2);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *too_small = ctx->CreateFCmpOLE(a_val, zero);
llvm::Value *dx = ctx->CreateSelect(too_small, zero, dx_res);
llvm::Value *dy = ctx->CreateSelect(too_small, zero, dy_res);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_LOG10" + suffix_upper:
self.format_code(f, """
// log10'(a) = a' * 1/a * 1/log(10) for a > 0, 0 otherwise
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *r_a_log_10 = ctx->CreateFDiv(
ctx.get_constant(%(type)s(0.43429448190325182765112891891661)), a_val);
llvm::Value *dx_res = ctx->CreateFMul(ctx.get_dual_dx(a), r_a_log_10);
llvm::Value *dy_res = ctx->CreateFMul(ctx.get_dual_dy(a), r_a_log_10);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *too_small = ctx->CreateFCmpOLE(a_val, zero);
llvm::Value *dx = ctx->CreateSelect(too_small, zero, dx_res);
llvm::Value *dy = ctx->CreateSelect(too_small, zero, dy_res);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_MDL_MAX" + suffix_upper:
self.format_code(f, """
// max'(a, b) = a > b ? a' : b'
llvm::Value *cmp = ctx->CreateFCmpOGT(ctx.get_dual_val(a), ctx.get_dual_val(b));
llvm::Value *dx = ctx->CreateSelect(cmp, ctx.get_dual_dx(a), ctx.get_dual_dx(b));
llvm::Value *dy = ctx->CreateSelect(cmp, ctx.get_dual_dy(a), ctx.get_dual_dy(b));
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_MDL_MIN" + suffix_upper:
self.format_code(f, """
// min'(a, b) = a < b ? a' : b'
llvm::Value *cmp = ctx->CreateFCmpOLT(ctx.get_dual_val(a), ctx.get_dual_val(b));
llvm::Value *dx = ctx->CreateSelect(cmp, ctx.get_dual_dx(a), ctx.get_dual_dx(b));
llvm::Value *dy = ctx->CreateSelect(cmp, ctx.get_dual_dy(a), ctx.get_dual_dy(b));
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_POW" + suffix_upper:
self.format_code(f, """
// pow'(a, b) = a ^ (b - 1) * (a' * b + a * log(a) * b')
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *b_val = ctx.get_dual_val(b);
llvm::Value *a_pow_b_minus_1 = ctx->CreateFDiv(val, a_val);
llvm::Function *log_func = get_runtime_func(%(log_name)s);
llvm::Value *log_a = ctx->CreateCall(log_func, a_val);
llvm::Value *a_log_a = ctx->CreateFMul(a_val, log_a);
llvm::Value *dx = ctx->CreateFMul(
a_pow_b_minus_1,
ctx->CreateFAdd(
ctx->CreateFMul(ctx.get_dual_dx(a), b_val),
ctx->CreateFMul(a_log_a, ctx.get_dual_dx(b))));
llvm::Value *dy = ctx->CreateFMul(
a_pow_b_minus_1,
ctx->CreateFAdd(
ctx->CreateFMul(ctx.get_dual_dy(a), b_val),
ctx->CreateFMul(a_log_a, ctx.get_dual_dy(b))));
res = ctx.get_dual(val, dx, dy);
""" % { "log_name": "RT_LOG" + suffix_upper })
elif enum_value == "RT_MDL_RSQRT" + suffix_upper:
self.format_code(f, """
// rsqrt'(a) = a' * -0.5 * rsqrt(a) / a for a > 0, 0 otherwise
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *one_half = ctx.get_constant(%(type)s(-0.5));
llvm::Value *factor = ctx->CreateFDiv(
ctx->CreateFMul(one_half, val),
a_val);
llvm::Value *dx_res = ctx->CreateFMul(ctx.get_dual_dx(a), factor);
llvm::Value *dy_res = ctx->CreateFMul(ctx.get_dual_dy(a), factor);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *too_small = ctx->CreateFCmpOLE(a_val, zero);
llvm::Value *dx = ctx->CreateSelect(too_small, zero, dx_res);
llvm::Value *dy = ctx->CreateSelect(too_small, zero, dy_res);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_MDL_SATURATE" + suffix_upper:
self.format_code(f, """
// saturate'(a) = a' for x in (0, 1), 0 otherwise
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *one = ctx.get_constant(%(type)s(1));
llvm::Value *too_small = ctx->CreateFCmpOLE(a_val, zero);
llvm::Value *too_big = ctx->CreateFCmpOGE(a_val, one);
llvm::Value *is_zero = ctx->CreateOr(too_small, too_big);
llvm::Value *dx = ctx->CreateSelect(is_zero, zero, ctx.get_dual_dx(a));
llvm::Value *dy = ctx->CreateSelect(is_zero, zero, ctx.get_dual_dy(a));
res = ctx.get_dual(val, dx, dy);
""" % {"type": type })
elif enum_value == "RT_SIN" + suffix_upper:
self.format_code(f, """
// sin'(a) = a' * cos(a)
llvm::Function *cos_func = get_runtime_func(%(cos_name)s);
llvm::Value *cos_val = ctx->CreateCall(cos_func, call_args);
llvm::Value *dx = ctx->CreateFMul(ctx.get_dual_dx(a), cos_val);
llvm::Value *dy = ctx->CreateFMul(ctx.get_dual_dy(a), cos_val);
res = ctx.get_dual(val, dx, dy);
""" % { "cos_name": "RT_COS" + suffix_upper })
elif enum_value == "RT_MDL_SMOOTHSTEP" + suffix_upper:
self.format_code(f, """
// smoothstep(a, b, c) ==>
// c = clamp(c, a, b)
// c = (c-a)/(b-a)
// return c*c * (3.0 - (c+c))
// smoothstep'(a, b, c) =
// -6 * (c - a) * (b - c) * (c * (b' - a') + b * (a' - c') + a * (c' - b')) / (a - b) ^ 4
// for c in [a, b], 0 otherwise
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *b_val = ctx.get_dual_val(b);
llvm::Value *c_val = ctx.get_dual_val(c);
llvm::Value *too_small = ctx->CreateFCmpOLE(c_val, a_val);
llvm::Value *too_big = ctx->CreateFCmpOGE(c_val, b_val);
llvm::Value *is_zero = ctx->CreateOr(too_small, too_big);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *c_minus_a = ctx->CreateFSub(c_val, a_val);
llvm::Value *b_minus_c = ctx->CreateFSub(b_val, c_val);
llvm::Value *a_minus_b = ctx->CreateFSub(a_val, b_val);
llvm::Value *a_minus_b_pow_2 = ctx->CreateFMul(a_minus_b, a_minus_b);
llvm::Value *a_minus_b_pow_4 = ctx->CreateFMul(a_minus_b_pow_2, a_minus_b_pow_2);
llvm::Value *factor = ctx->CreateFDiv(
ctx->CreateFMul(
ctx->CreateFMul(
ctx.get_constant(%(type)s(-6)),
c_minus_a),
b_minus_c),
a_minus_b_pow_4);
llvm::Value *dx_res = ctx->CreateFMul(
factor,
ctx->CreateFAdd(
ctx->CreateFAdd(
ctx->CreateFMul(
c_val,
ctx->CreateFSub(
ctx.get_dual_dx(b),
ctx.get_dual_dx(a))),
ctx->CreateFMul(
b_val,
ctx->CreateFSub(
ctx.get_dual_dx(a),
ctx.get_dual_dx(c)))),
ctx->CreateFMul(
a_val,
ctx->CreateFSub(
ctx.get_dual_dx(c),
ctx.get_dual_dx(b)))));
llvm::Value *dy_res = ctx->CreateFMul(
factor,
ctx->CreateFAdd(
ctx->CreateFAdd(
ctx->CreateFMul(
c_val,
ctx->CreateFSub(
ctx.get_dual_dy(b),
ctx.get_dual_dy(a))),
ctx->CreateFMul(
b_val,
ctx->CreateFSub(
ctx.get_dual_dy(a),
ctx.get_dual_dy(c)))),
ctx->CreateFMul(
a_val,
ctx->CreateFSub(
ctx.get_dual_dy(c),
ctx.get_dual_dy(b)))));
llvm::Value *dx = ctx->CreateSelect(is_zero, zero, dx_res);
llvm::Value *dy = ctx->CreateSelect(is_zero, zero, dy_res);
res = ctx.get_dual(val, dx, dy);
""" % {"type": type })
elif enum_value == "RT_SQRT" + suffix_upper:
self.format_code(f, """
// sqrt'(a) = a' * 0.5 / sqrt(a) for a > 0, 0 otherwise
llvm::Value *one_half = ctx.get_constant(%(type)s(0.5));
llvm::Value *one_half_over_sqrt = ctx->CreateFDiv(one_half, val);
llvm::Value *dx_res = ctx->CreateFMul(ctx.get_dual_dx(a), one_half_over_sqrt);
llvm::Value *dy_res = ctx->CreateFMul(ctx.get_dual_dy(a), one_half_over_sqrt);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *too_small = ctx->CreateFCmpOLE(ctx.get_dual_val(a), zero);
llvm::Value *dx = ctx->CreateSelect(too_small, zero, dx_res);
llvm::Value *dy = ctx->CreateSelect(too_small, zero, dy_res);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
elif enum_value == "RT_TAN" + suffix_upper:
self.format_code(f, """
// tan'(a) = a' / cos(a)^2
llvm::Function *cos_func = get_runtime_func(%(cos_name)s);
llvm::Value *cos_val = ctx->CreateCall(cos_func, call_args);
llvm::Value *cos_2_val = ctx->CreateFMul(cos_val, cos_val);
llvm::Value *r_cos_2_val = ctx->CreateFDiv(ctx.get_constant(%(type)s(1)), cos_2_val);
llvm::Value *dx = ctx->CreateFMul(ctx.get_dual_dx(a), r_cos_2_val);
llvm::Value *dy = ctx->CreateFMul(ctx.get_dual_dy(a), r_cos_2_val);
res = ctx.get_dual(val, dx, dy);
""" % { "cos_name": "RT_COS" + suffix_upper, "type": type })
else:
# Unsupported function, set derivatives to zero.
# Also for ceil, floor, round, sign, step
self.format_code(f, """
llvm::Value *zero = llvm::Constant::getNullValue(val->getType());
res = ctx.get_dual(val, zero, zero);
""")
self.format_code(f, "} else {\n")
for idx, param in enumerate(params):
self.write(f, "call_args[%d] = %s;\n" % (idx, chr(ord('a') + idx)))
self.format_code(f,
"""res = ctx->CreateCall(callee, call_args);
}
""")
elif mode == "math::log10_atomic":
suffix = self.get_type_suffix(params[0])
suffix_upper = suffix.upper()
enum_value = self.get_runtime_enum("log10" + suffix)
type = self.m_inv_types[params[0]]
self.format_code(f,
"""// atomic log10
llvm::Function *callee = get_runtime_func(%s);
llvm::Value *call_args[%d];
if (inst.get_return_derivs()) {
""" % (enum_value, len(params)))
for idx, param in enumerate(params):
self.write(f, "call_args[%d] = ctx.get_dual_val(%s);\n"
% (idx, chr(ord('a') + idx)))
self.format_code(f,
"""
llvm::Value *val;
if (callee != nullptr) {
// we have log10
val = ctx->CreateCall(callee, call_args);
} else {
// log10(a) = log2(a) * 1/log2(10)
llvm::Function *callee = get_runtime_func(%(log2)s);
val = ctx->CreateCall(callee, call_args);
llvm::Value *r_log2_10 = ctx.get_constant(%(type)s(0.301029996));
val = ctx->CreateFMul(val, r_log2_10);
}
""" % { "log2": self.get_runtime_enum("log2" + suffix), "type": type } )
# Calculate derivatives for specific functions
self.format_code(f, """
// log10'(a) = a' * 1/a * 1/log(10) for a > 0, 0 otherwise
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *r_a_log_10 = ctx->CreateFDiv(
ctx.get_constant(%(type)s(0.43429448190325182765112891891661)), a_val);
llvm::Value *dx_res = ctx->CreateFMul(ctx.get_dual_dx(a), r_a_log_10);
llvm::Value *dy_res = ctx->CreateFMul(ctx.get_dual_dy(a), r_a_log_10);
llvm::Value *zero = ctx.get_constant(%(type)s(0));
llvm::Value *too_small = ctx->CreateFCmpOLE(a_val, zero);
llvm::Value *dx = ctx->CreateSelect(too_small, zero, dx_res);
llvm::Value *dy = ctx->CreateSelect(too_small, zero, dy_res);
res = ctx.get_dual(val, dx, dy);
""" % { "type": type })
self.format_code(f, "} else {\n")
for idx, param in enumerate(params):
self.write(f, "call_args[%d] = %s;\n" % (idx, chr(ord('a') + idx)))
self.format_code(f,
"""
if (callee != nullptr) {
// we have log10
res = ctx->CreateCall(callee, call_args);
} else {
// log10(a) = log2(a) * 1/log2(10)
llvm::Function *callee = get_runtime_func(%(log2)s);
res = ctx->CreateCall(callee, call_args);
llvm::Value *r_log2_10 = ctx.get_constant(%(type)s(0.301029996));
res = ctx->CreateFMul(res, r_log2_10);
}
""" % { "log2": self.get_runtime_enum("log2" + suffix), "type": type } )
self.format_code(f, "}\n")
elif mode == "math::any|all":
vt = self.get_vector_type_and_size(params[0])
need_or = intrinsic == "any"
op_instr = "CreateAnd"
if need_or:
op_instr = "CreateOr"
code_params = { "op_instr" : op_instr }
a_is_vec = self.get_vector_type_and_size(params[0])
if a_is_vec:
code_params["size"] = a_is_vec[1]
code = """
llvm::Type *arg_tp = a->getType();
if (arg_tp->isArrayTy()) {
unsigned idxes[1];
idxes[0] = 0u;
res = ctx->CreateExtractValue(a, idxes);
for (int i = 1; i < %(size)d; ++i) {
idxes[0] = unsigned(i);
llvm::Value *a_elem = ctx->CreateExtractValue(a, idxes);
res = ctx->%(op_instr)s(res, a_elem);
}
} else {
llvm::Value *idx = ctx.get_constant(0);
res = ctx->CreateExtractElement(a, idx);
for (int i = 1; i < %(size)d; ++i) {
llvm::Value *idx = ctx.get_constant(i);
llvm::Value *a_elem = ctx->CreateExtractElement(a, idx);
res = ctx->%(op_instr)s(res, a_elem);
}
}
""" % code_params
else:
# any|all on atomics is a no-op
code = """
res = a;
"""
self.format_code(f, code)
elif mode == "math::average":
a_is_vec = self.get_vector_type_and_size(params[0])
if a_is_vec:
code_params = {
"type" : a_is_vec[0],
"size" : a_is_vec[1]
}
code = """
llvm::Value *c = ctx.get_constant(%(type)s(1)/%(type)s(%(size)d));
if (inst.get_return_derivs()) {
llvm::Value *res_comps[3];
for (unsigned comp = 0; comp < 3; ++comp) {
llvm::Value *comp_val = ctx.get_dual_comp(a, comp);
res_comps[comp] = ctx.create_extract(comp_val, 0);
for (unsigned i = 1; i < %(size)d; ++i) {
llvm::Value *a_elem = ctx.create_extract(comp_val, i);
res_comps[comp] = ctx->CreateFAdd(res_comps[comp], a_elem);
}
res_comps[comp] = ctx->CreateFMul(res_comps[comp], c);
}
res = ctx.get_dual(res_comps[0], res_comps[1], res_comps[2]);
} else {
res = ctx.create_extract(a, 0);
for (unsigned i = 1; i < %(size)d; ++i) {
llvm::Value *a_elem = ctx.create_extract(a, i);
res = ctx->CreateFAdd(res, a_elem);
}
res = ctx->CreateFMul(res, c);
}
""" % code_params
else:
# average on atomics is a no-op
code = """
res = a;
"""
self.format_code(f, code)
elif mode == "math::lerp":
# lerp(a, b, c) = a * (1-c) + b * c;
code = """
if (inst.get_return_derivs()) {
llvm::Type *base_type = ctx.get_deriv_base_type(a->getType());
llvm::Type *elem_type = base_type;
if (elem_type->isVectorTy() || elem_type->isArrayTy())
elem_type = ctx.get_element_type(base_type);
llvm::Value *one = ctx.get_dual(ctx.get_constant(elem_type, 1));
llvm::Value *one_minus_c = ctx.create_deriv_sub(base_type, one, c);
res = ctx.create_deriv_add(base_type,
ctx.create_deriv_mul(base_type, a, one_minus_c),
ctx.create_deriv_mul(base_type, b, c));
} else {
llvm::Type *arg_tp = a->getType();
if (arg_tp->isArrayTy()) {
llvm::ArrayType *a_tp = llvm::cast<llvm::ArrayType>(arg_tp);
llvm::Type *e_tp = a_tp->getElementType();
llvm::Value *one = ctx.get_constant(e_tp, 1);
res = llvm::ConstantAggregateZero::get(a_tp);
unsigned idxes[1];
bool c_is_arr = c->getType() == arg_tp;
for (size_t i = 0, n = a_tp->getNumElements(); i < n; ++i) {
idxes[0] = unsigned(i);
llvm::Value *a_elem = ctx->CreateExtractValue(a, idxes);
llvm::Value *b_elem = ctx->CreateExtractValue(b, idxes);
llvm::Value *c_elem = c_is_arr ? ctx->CreateExtractValue(c, idxes) : c;
llvm::Value *s = ctx->CreateFSub(one, c_elem);
llvm::Value *t1 = ctx->CreateFMul(a_elem, s);
llvm::Value *t2 = ctx->CreateFMul(b_elem, c_elem);
llvm::Value *e = ctx->CreateFAdd(t1, t2);
res = ctx->CreateInsertValue(res, e, idxes);
}
} else {
if (arg_tp->isVectorTy()) {
llvm::VectorType *v_tp = llvm::cast<llvm::VectorType>(arg_tp);
if (c->getType() != arg_tp)
c = ctx.create_vector_splat(v_tp, c);
}
llvm::Value *one = ctx.get_constant(arg_tp, 1);
llvm::Value *s = ctx->CreateFSub(one, c);
llvm::Value *t1 = ctx->CreateFMul(a, s);
llvm::Value *t2 = ctx->CreateFMul(b, c);
res = ctx->CreateFAdd(t1, t2);
}
}
"""
self.format_code(f, code)
elif mode == "math::const_mul":
# degrees(a) = a * 180.0/PI
# radians(a) = a * PI/180.0
code = """
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Type *arg_tp = a_val->getType();
llvm::Value *cnst;
if (arg_tp->isArrayTy()) {
llvm::ArrayType *a_tp = llvm::cast<llvm::ArrayType>(arg_tp);
llvm::Type *e_tp = a_tp->getElementType();
cnst = ctx.get_constant(e_tp, %(cnst_mul)s);
} else {
cnst = ctx.get_constant(arg_tp, %(cnst_mul)s);
}
res = ctx.create_mul(arg_tp, a_val, cnst);
if (inst.get_return_derivs()) {
llvm::Value *dx = ctx.create_mul(arg_tp, ctx.get_dual_dx(a), cnst);
llvm::Value *dy = ctx.create_mul(arg_tp, ctx.get_dual_dy(a), cnst);
res = ctx.get_dual(res, dx, dy);
}
""" % { "cnst_mul": self.cnst_mul[intrinsic] }
self.format_code(f, code)
elif mode == "math::dot":
# dot product
code = """
if (inst.get_return_derivs()) {
llvm::Type *base_type = ctx.get_deriv_base_type(a->getType());
llvm::Value *t = ctx.create_deriv_mul(base_type, a, b);
res = ctx.create_extract_allow_deriv(t, 0);
llvm::Type *elem_type = ctx.get_deriv_base_type(res->getType());
for (unsigned i = 1, n = ctx.get_num_elements(ctx.get_dual_val(t)); i < n; ++i) {
llvm::Value *e = ctx.create_extract_allow_deriv(t, i);
res = ctx.create_deriv_add(elem_type, res, e);
}
} else {
llvm::Type *arg_tp = a->getType();
if (arg_tp->isArrayTy()) {
llvm::ArrayType *a_tp = llvm::cast<llvm::ArrayType>(arg_tp);
llvm::Type *e_tp = a_tp->getElementType();
res = ctx.get_constant(e_tp, 0);
unsigned idxes[1];
for (size_t i = 0, n = a_tp->getNumElements(); i < n; ++i) {
idxes[0] = unsigned(i);
llvm::Value *a_elem = ctx->CreateExtractValue(a, idxes);
llvm::Value *b_elem = ctx->CreateExtractValue(b, idxes);
llvm::Value *t = ctx->CreateFMul(a_elem, b_elem);
res = ctx->CreateFAdd(res, t);
}
} else {
llvm::FixedVectorType *v_tp = llvm::cast<llvm::FixedVectorType>(arg_tp);
llvm::Type *e_tp = v_tp->getElementType();
llvm::Value *t = ctx->CreateFMul(a, b);
res = ctx.get_constant(e_tp, 0);
for (size_t i = 0, n = v_tp->getNumElements(); i < n; ++i) {
llvm::Value *idx = ctx.get_constant(int(i));
llvm::Value *e = ctx->CreateExtractElement(t, idx);
res = ctx->CreateFAdd(res, e);
}
}
}
"""
first_param = signature.split('_')[1]
atomic_chk = self.get_atomic_type_kind(first_param)
if atomic_chk:
code = """
if (inst.get_return_derivs()) {
llvm::Type *base_type = ctx.get_deriv_base_type(a->getType());
res = ctx.create_deriv_mul(base_type, a, b);
} else {
res = ctx->CreateFMul(a, b);
}
"""
self.format_code(f, code)
elif mode == "math::step":
ret_is_vec = self.get_vector_type_and_size(ret_type)
is_float = True
if ret_is_vec:
base_tp = ret_is_vec[0]
is_float = base_tp == "float"
else:
ret_is_atomic = self.get_atomic_type_kind(ret_type)
is_float = ret_is_atomic == "mi::mdl::IType::TK_FLOAT"
a_is_vec = self.get_vector_type_and_size(params[0])
get_a = "ctx->CreateExtractValue(a, idxes);"
if not a_is_vec:
get_a = "a;"
b_is_vec = self.get_vector_type_and_size(params[1])
get_b = "ctx->CreateExtractValue(b, idxes);"
if not b_is_vec:
get_b = "b;"
code_params = {
"get_a" : get_a,
"get_b" : get_b,
}
if is_float:
code_params["zero"] = "0.0f"
code_params["one"] = "1.0f"
code_params["intrinsic_base"] = "RT_STEPFF"
else:
code_params["zero"] = "0.0"
code_params["one"] = "1.0"
code_params["intrinsic_base"] = "RT_STEPDD"
code_params["intrinsic"] = "RT_STEP" + ret_type.upper()
if ret_is_vec:
code_params["size"] = ret_is_vec[1]
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
llvm::Constant *one = ctx.get_constant(%(one)s);
llvm::Constant *zero = ctx.get_constant(%(zero)s);
if (ret_tp->isArrayTy()) {
llvm::Function *callee = get_runtime_func(%(intrinsic_base)s);
unsigned idxes[1];
res = llvm::ConstantAggregateZero::get(ret_tp);
for (unsigned i = 0; i < %(size)d; ++i) {
idxes[0] = i;
llvm::Value *a_elem = %(get_a)s
llvm::Value *b_elem = %(get_b)s
llvm::Value *elem;
if (callee != nullptr) {
llvm::Value *call_args[] = { a, b };
elem = ctx->CreateCall(callee, call_args);
} else {
llvm::Value *cmp = ctx->CreateFCmp(
llvm::ICmpInst::FCMP_OLT, b_elem, a_elem);
elem = ctx->CreateSelect(cmp, zero, one);
}
res = ctx->CreateInsertValue(res, elem, idxes);
}
} else {
llvm::Function *callee = get_runtime_func(%(intrinsic)s);
if (callee != nullptr) {
llvm::Value *call_args[] = { a, b };
res = ctx->CreateCall(callee, call_args);
} else {
zero = llvm::ConstantVector::getSplat(llvm::ElementCount::getFixed(%(size)d), zero);
one = llvm::ConstantVector::getSplat(llvm::ElementCount::getFixed(%(size)d), one);
llvm::Value *cmp = ctx->CreateFCmp(llvm::ICmpInst::FCMP_OLT, b, a);
res = ctx->CreateSelect(cmp, zero, one);
}
}
""" % code_params
else:
code = """
llvm::Function *callee = get_runtime_func(%(intrinsic)s);
if (callee != nullptr) {
llvm::Value *call_args[] = { a, b };
res = ctx->CreateCall(callee, call_args);
} else {
llvm::Value *cmp = ctx->CreateFCmp(llvm::ICmpInst::FCMP_OLT, b, a);
llvm::Constant *one = ctx.get_constant(%(one)s);
llvm::Constant *zero = ctx.get_constant(%(zero)s);
res = ctx->CreateSelect(cmp, zero, one);
}
""" % code_params
self.format_code(f, code)
self.format_code(f, """
// expand to dual, derivative is zero unless undefined for which we also set zero
if (inst.get_return_derivs()) {
res = ctx.get_dual(res);
}
""")
elif mode == "math::min_value|max_value":
# min_value/max_value
cmp = "LT"
if intrinsic == "max_value":
cmp = "GT"
code_params = { "cmp" : cmp }
a_is_vec = self.get_vector_type_and_size(params[0])
if a_is_vec:
code_params["size"] = a_is_vec[1]
code = """
res = ctx.create_extract_allow_deriv(a, 0);
for (int i = 1; i < %(size)d; ++i) {
llvm::Value *a_elem = ctx.create_extract_allow_deriv(a, i);
llvm::Value *cmp = ctx->CreateFCmp(
llvm::ICmpInst::FCMP_O%(cmp)s,
ctx.get_dual_val(res),
ctx.get_dual_val(a_elem));
res = ctx->CreateSelect(cmp, res, a_elem);
}
""" % code_params
else:
# min_value|max_value on atomics is a no-op
code = """
res = a;
"""
self.format_code(f, code)
elif mode == "math::min_value_wavelength|max_value_wavelength":
# FIXME: NYI
idx = 0
for param in params:
self.write(f, "(void)%s;\n" % chr(ord('a') + idx))
idx += 1
self.write(f, "res = llvm::Constant::getNullValue(ctx_data->get_return_type());\n")
elif mode == "math::cross":
# cross product
code = """
llvm::Type *res_tp = ctx.get_non_deriv_return_type();
res = llvm::ConstantAggregateZero::get(res_tp);
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *b_val = ctx.get_dual_val(b);
if (res_tp->isArrayTy()) {
unsigned idxes[1];
idxes[0] = 0u;
llvm::Value *a_x = ctx->CreateExtractValue(a_val, idxes);
llvm::Value *b_x = ctx->CreateExtractValue(b_val, idxes);
idxes[0] = 1u;
llvm::Value *a_y = ctx->CreateExtractValue(a_val, idxes);
llvm::Value *b_y = ctx->CreateExtractValue(b_val, idxes);
idxes[0] = 2u;
llvm::Value *a_z = ctx->CreateExtractValue(a_val, idxes);
llvm::Value *b_z = ctx->CreateExtractValue(b_val, idxes);
llvm::Value *res_x = ctx->CreateFSub(
ctx->CreateFMul(a_y, b_z),
ctx->CreateFMul(a_z, b_y));
idxes[0] = 0u;
res = ctx->CreateInsertValue(res, res_x, idxes);
llvm::Value *res_y = ctx->CreateFSub(
ctx->CreateFMul(a_z, b_x),
ctx->CreateFMul(a_x, b_z));
idxes[0] = 1u;
res = ctx->CreateInsertValue(res, res_y, idxes);
llvm::Value *res_z = ctx->CreateFSub(
ctx->CreateFMul(a_x, b_y),
ctx->CreateFMul(a_y, b_x));
idxes[0] = 2u;
res = ctx->CreateInsertValue(res, res_z, idxes);
// TODO: Add derivative support
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
} else {
res = ctx.create_cross(a_val, b_val);
if (inst.get_return_derivs()) {
llvm::Value *a_dx = ctx.get_dual_dx(a);
llvm::Value *a_dy = ctx.get_dual_dy(a);
llvm::Value *b_dx = ctx.get_dual_dx(b);
llvm::Value *b_dy = ctx.get_dual_dy(b);
// (a cross b)' = a' cross b + a cross b'
llvm::Value *dx = ctx->CreateFAdd(
ctx.create_cross(a_dx, b_val),
ctx.create_cross(a_val, b_dx));
llvm::Value *dy = ctx->CreateFAdd(
ctx.create_cross(a_dy, b_val),
ctx.create_cross(a_val, b_dy));
res = ctx.get_dual(res, dx, dy);
}
}
"""
self.format_code(f, code)
elif mode == "math::isnan|isfinite":
# NanN or finite check
# Should not be called with inst.get_return_derivs(), as the results are boolean
cmp = "ORD"
if intrinsic == "isnan":
cmp = "UNO"
code_params = { "cmp" : cmp }
a_is_vec = self.get_vector_type_and_size(params[0])
if a_is_vec:
code_params["size"] = a_is_vec[1]
code = """
llvm::Type *res_tp = ctx_data->get_return_type();
res = llvm::ConstantAggregateZero::get(res_tp);
if (res_tp->isArrayTy()) {
unsigned idxes[1];
for (int i = 0; i < %(size)d; ++i) {
idxes[0] = unsigned(i);
llvm::Value *a_elem = ctx->CreateExtractValue(a, idxes);
llvm::Value *cmp = ctx->CreateFCmp(llvm::ICmpInst::FCMP_%(cmp)s, a_elem, a_elem);
// map the i1 result to the bool type representation
cmp = ctx->CreateZExt(cmp, m_code_gen.m_type_mapper.get_bool_type());
res = ctx->CreateInsertValue(res, cmp, idxes);
}
} else {
llvm::Value *tmp = ctx->CreateFCmp(llvm::ICmpInst::FCMP_%(cmp)s, a, a);
if (tmp->getType() != res_tp) {
// convert bool type
res = llvm::UndefValue::get(res_tp);
for (int i = 0; i < %(size)d; ++i) {
llvm::Value *idx = ctx.get_constant(i);
llvm::Value *elem = ctx->CreateExtractElement(tmp, idx);
// map the i1 vector result to the bool type representation
elem = ctx->CreateZExt(elem, m_code_gen.m_type_mapper.get_bool_type());
res = ctx->CreateInsertElement(res, elem, idx);
}
} else {
res = tmp;
}
}
""" % code_params
else:
code = """
res = ctx->CreateFCmp(llvm::ICmpInst::FCMP_%(cmp)s, a, a);
// map the i1 result to the bool type representation
res = ctx->CreateZExt(res, m_code_gen.m_type_mapper.get_bool_type());
""" % code_params
self.format_code(f, code)
elif mode == "math::transpose":
type_code = params[0]
src_rows = int(type_code[-1])
src_cols = int(type_code[-2])
tgt_rows = src_cols
tgt_cols = src_rows
# 0 3
# a = (1 4) = [0, 1, 2, 3, 4, 5]
# 2 5
#
# res = (0 1 2) = [0, 3, 1, 4, 2, 5]
# 3 4 5
params = { "rows" : src_rows, "cols" : src_cols }
# the shuffle indexes for big_vector mode
code = "";
for col in range(tgt_cols):
for row in range(tgt_rows):
src_idx = row * tgt_cols + col
code = code + (" %d," % src_idx)
params["shuffle_idxes"] = code[0:-1] # remove last ','
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
if (ret_tp->isArrayTy()) {
llvm::ArrayType *a_tp = llvm::cast<llvm::ArrayType>(ret_tp);
llvm::Type *e_tp = a_tp->getElementType();
if (e_tp->isVectorTy()) {
// small vector mode
res = llvm::UndefValue::get(ret_tp);
if (m_code_gen.m_type_mapper.is_deriv_type(a->getType())) {
llvm::Value *column_val[%(cols)d];
llvm::Value *column_dx[%(cols)d];
llvm::Value *column_dy[%(cols)d];
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *a_dx = ctx.get_dual_dx(a);
llvm::Value *a_dy = ctx.get_dual_dy(a);
llvm::Value *res_val = res, *res_dx = res, *res_dy = res;
for (unsigned col = 0; col < %(cols)d; ++col) {
column_val[col] = ctx->CreateExtractValue(a_val, { col });
column_dx [col] = ctx->CreateExtractValue(a_dx , { col });
column_dy [col] = ctx->CreateExtractValue(a_dy , { col });
}
for (unsigned row = 0; row < %(rows)d; ++row) {
llvm::Value *tmp_val = llvm::UndefValue::get(e_tp);
llvm::Value *tmp_dx = llvm::UndefValue::get(e_tp);
llvm::Value *tmp_dy = llvm::UndefValue::get(e_tp);
for (unsigned col = 0; col < %(cols)d; ++col) {
llvm::Value *elem_val = ctx->CreateExtractElement(column_val[col], ctx.get_constant(int(row)));
llvm::Value *elem_dx = ctx->CreateExtractElement(column_dx[col], ctx.get_constant(int(row)));
llvm::Value *elem_dy = ctx->CreateExtractElement(column_dy[col], ctx.get_constant(int(row)));
tmp_val = ctx->CreateInsertElement(tmp_val, elem_val, ctx.get_constant(int(col)));
tmp_dx = ctx->CreateInsertElement(tmp_dx , elem_dx , ctx.get_constant(int(col)));
tmp_dy = ctx->CreateInsertElement(tmp_dy , elem_dy , ctx.get_constant(int(col)));
}
res_val = ctx->CreateInsertValue(res_val, tmp_val, { row });
res_dx = ctx->CreateInsertValue(res_dx, tmp_dx, { row });
res_dy = ctx->CreateInsertValue(res_dy, tmp_dy, { row });
}
res = ctx.get_dual(res_val, res_dx, res_dy);
} else {
llvm::Value *column[%(cols)d];
for (unsigned col = 0; col < %(cols)d; ++col) {
column[col] = ctx->CreateExtractValue(a, { col });
}
for (unsigned row = 0; row < %(rows)d; ++row) {
llvm::Value *tmp = llvm::UndefValue::get(e_tp);
for (unsigned col = 0; col < %(cols)d; ++col) {
llvm::Value *elem = ctx->CreateExtractElement(column[col], ctx.get_constant(int(row)));
tmp = ctx->CreateInsertElement(tmp, elem, ctx.get_constant(int(col)));
}
res = ctx->CreateInsertValue(res, tmp, { row });
}
}
} else {
// all scalar mode
res = llvm::UndefValue::get(ret_tp);
llvm::Value *tmp;
if (m_code_gen.m_type_mapper.is_deriv_type(a->getType())) {
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *a_dx = ctx.get_dual_dx(a);
llvm::Value *a_dy = ctx.get_dual_dy(a);
llvm::Value *res_val = res, *res_dx = res, *res_dy = res;
for (unsigned col = 0; col < %(cols)d; ++col) {
for (unsigned row = 0; row < %(rows)d; ++row) {
unsigned tgt_idxes[1] = { col * %(rows)d + row };
unsigned src_idxes[1] = { row * %(cols)d + col };
tmp = ctx->CreateExtractValue(a_val, src_idxes);
res_val = ctx->CreateInsertValue(res_val, tmp, tgt_idxes);
tmp = ctx->CreateExtractValue(a_dx, src_idxes);
res_dx = ctx->CreateInsertValue(res_dx, tmp, tgt_idxes);
tmp = ctx->CreateExtractValue(a_dy, src_idxes);
res_dy = ctx->CreateInsertValue(res_dy, tmp, tgt_idxes);
}
}
res = ctx.get_dual(res_val, res_dx, res_dy);
} else {
for (unsigned col = 0; col < %(cols)d; ++col) {
for (unsigned row = 0; row < %(rows)d; ++row) {
unsigned tgt_idxes[1] = { col * %(rows)d + row };
unsigned src_idxes[1] = { row * %(cols)d + col };
tmp = ctx->CreateExtractValue(a, src_idxes);
res = ctx->CreateInsertValue(res, tmp, tgt_idxes);
}
}
}
}
} else {
// big vector mode
static const int idxes[] = { %(shuffle_idxes)s };
llvm::Value *shuffle = ctx.get_shuffle(idxes);
if (m_code_gen.m_type_mapper.is_deriv_type(a->getType())) {
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *a_dx = ctx.get_dual_dx(a);
llvm::Value *a_dy = ctx.get_dual_dy(a);
res = ctx.get_dual(
ctx->CreateShuffleVector(a_val, a_val, shuffle),
ctx->CreateShuffleVector(a_dx , a_dx , shuffle),
ctx->CreateShuffleVector(a_dy , a_dy , shuffle));
} else {
res = ctx->CreateShuffleVector(a, a, shuffle);
}
}
"""
self.format_code(f, code % params)
elif mode == "math::sincos":
# we know that the return type is an array, so get the element type here
code = """
llvm::Value *res_0, *res_1;
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::ArrayType *ret_tp = llvm::cast<llvm::ArrayType>(ctx.get_non_deriv_return_type());
res = llvm::ConstantAggregateZero::get(ret_tp);
"""
self.format_code(f, code)
elem_type = self.get_array_element_type(ret_type)
vt = self.get_vector_type_and_size(elem_type)
if vt:
atom_code = self.do_get_type_code(vt[0])
n_elems = vt[1]
code_params = {
"sin_name" : "RT_SIN" + self.get_type_suffix(atom_code).upper(),
"cos_name" : "RT_COS" + self.get_type_suffix(atom_code).upper()
}
code = """
llvm::Function *sin_func = get_runtime_func(%(sin_name)s);
llvm::Function *cos_func = get_runtime_func(%(cos_name)s);
""" % code_params
is_float = False
if atom_code == "FF":
is_float = True
code += """
llvm::Function *sincos_func = m_has_sincosf ? get_runtime_func(RT_SINCOSF) : NULL;
"""
code += """
llvm::Type *elm_tp = ret_tp->getElementType();
res_0 = llvm::ConstantAggregateZero::get(elm_tp);
res_1 = llvm::ConstantAggregateZero::get(elm_tp);
""" % code_params
if is_float:
code += """
llvm::Value *sc_tmp = nullptr;
llvm::Value *s_tmp = nullptr;
llvm::Value *c_tmp = nullptr;
if (m_has_sincosf) {
sc_tmp = ctx.create_local(elm_tp, "sc_tmp");
s_tmp = ctx.create_simple_gep_in_bounds(sc_tmp, 0u);
c_tmp = ctx.create_simple_gep_in_bounds(sc_tmp, 1u);
}
"""
code += """
for (unsigned i = 0; i < %d; ++i) {
llvm::Value *tmp = ctx.create_extract(a_val, i);
""" % n_elems
if is_float:
code += """
llvm::Value *s_val;
llvm::Value *c_val;
if (m_has_sincosf) {
ctx->CreateCall(sincos_func, { tmp, s_tmp, c_tmp });
s_val = ctx->CreateLoad(s_tmp);
c_val = ctx->CreateLoad(c_tmp);
} else {
s_val = ctx->CreateCall(sin_func, tmp);
c_val = ctx->CreateCall(cos_func, tmp);
}
"""
else:
code += """
llvm::Value *s_val = ctx->CreateCall(sin_func, tmp);
llvm::Value *c_val = ctx->CreateCall(cos_func, tmp);
"""
code += """
res_0 = ctx.create_insert(res_0, s_val, i);
res_1 = ctx.create_insert(res_1, c_val, i);
}
"""
code += """
res = ctx.create_insert(res, res_0, 0);
res = ctx.create_insert(res, res_1, 1);
"""
self.format_code(f, code)
else:
# scalar code
atom_code = elem_type
code_params = {
"sin_name" : "RT_SIN" + self.get_type_suffix(atom_code).upper(),
"cos_name" : "RT_COS" + self.get_type_suffix(atom_code).upper()
}
if atom_code == "FF":
code = """
if (m_has_sincosf) {
llvm::Function *sincos_func = get_runtime_func(RT_SINCOSF);
res = ctx.create_local(ret_tp, "res");
llvm::Value *sinp = ctx.create_simple_gep_in_bounds(res, 0u);
llvm::Value *cosp = ctx.create_simple_gep_in_bounds(res, 1u);
ctx->CreateCall(sincos_func, { a_val, sinp, cosp });
res = ctx->CreateLoad(res);
} else {
llvm::Function *sin_func = get_runtime_func(RT_SINF);
llvm::Function *cos_func = get_runtime_func(RT_COSF);
res_0 = ctx->CreateCall(sin_func, a_val);
res_1 = ctx->CreateCall(cos_func, a_val);
res = ctx.create_insert(res, res_0, 0);
res = ctx.create_insert(res, res_1, 1);
}
""" % code_params
self.format_code(f, code)
else:
# not float
code = """
llvm::Function *sin_func = get_runtime_func(%(sin_name)s);
llvm::Function *cos_func = get_runtime_func(%(cos_name)s);
res_0 = ctx->CreateCall(sin_func, a_val);
res_1 = ctx->CreateCall(cos_func, a_val);
res = ctx.create_insert(res, res_0, 0);
res = ctx.create_insert(res, res_1, 1);
""" % code_params
self.format_code(f, code)
self.format_code(f, """
if (inst.get_return_derivs()) {
// [sin_a, cos_a] = sincos(a)
// sincos'(a) = [a' * cos_a, -a' * sin_a]
llvm::Value *neg_sin_a = ctx->CreateFNeg(ctx.create_extract(res, 0));
llvm::Value *cos_a = ctx.create_extract(res, 1);
llvm::Type *base_type = a_val->getType();
llvm::Value *res_dx_0 = ctx.create_mul(base_type, ctx.get_dual_dx(a), cos_a);
llvm::Value *res_dx_1 = ctx.create_mul(base_type, ctx.get_dual_dx(a), neg_sin_a);
llvm::Value *res_dx = llvm::ConstantAggregateZero::get(ret_tp);
res_dx = ctx.create_insert(res_dx, res_dx_0, 0);
res_dx = ctx.create_insert(res_dx, res_dx_1, 1);
llvm::Value *res_dy_0 = ctx.create_mul(base_type, ctx.get_dual_dy(a), cos_a);
llvm::Value *res_dy_1 = ctx.create_mul(base_type, ctx.get_dual_dy(a), neg_sin_a);
llvm::Value *res_dy = llvm::ConstantAggregateZero::get(ret_tp);
res_dy = ctx.create_insert(res_dy, res_dy_0, 0);
res_dy = ctx.create_insert(res_dy, res_dy_1, 1);
res = ctx.get_dual(res, res_dx, res_dy);
}
""")
elif mode == "math::modf":
# modf(x) = (floor(x), x - floor(x))
# floor'(x) = 0 unless undefined
# modf'(x) = (0, x')
# we know that the return type is an array, so get the element type here
self.format_code(f, """
llvm::Value *a_val = ctx.get_dual_val(a);
llvm::Value *res_integral, *res_fractional;
llvm::ArrayType *ret_tp = llvm::cast<llvm::ArrayType>(ctx.get_non_deriv_return_type());
llvm::Type *elm_tp = ret_tp->getElementType();
res = llvm::ConstantAggregateZero::get(ret_tp);
""")
elem_type = self.get_array_element_type(ret_type)
vt = self.get_vector_type_and_size(elem_type)
if vt:
atom_code = self.do_get_type_code(vt[0])
n_elems = vt[1]
f_name = "RT_MODF" + self.get_type_suffix(atom_code).upper()
self.format_code(f, """
llvm::Function *modf = get_runtime_func(%s);
res_integral = llvm::ConstantAggregateZero::get(elm_tp);
res_fractional = llvm::ConstantAggregateZero::get(elm_tp);
llvm::Type *t_type = ctx.get_element_type(elm_tp);
llvm::Value *intptr = ctx.create_local(t_type, "tmp");
llvm::Value *tmp;
""" % f_name)
for i in range(n_elems):
self.format_code(f, """
tmp = ctx.create_extract(a_val, %(idx)u);
tmp = ctx->CreateCall(modf, { tmp, intptr });
res_fractional = ctx.create_insert(res_fractional, tmp, %(idx)u);
res_integral = ctx.create_insert(res_integral, ctx->CreateLoad(intptr), %(idx)u);
""" % { "idx": i })
else:
atom_code = elem_type
f_name = "RT_MODF" + self.get_type_suffix(atom_code).upper()
self.format_code(f, """
llvm::Function *modf = get_runtime_func(%s);
llvm::Value *intptr = ctx.create_local(elm_tp, \"tmp\");
res_fractional = ctx->CreateCall(modf, { a_val, intptr });
res_integral = ctx->CreateLoad(intptr);
""" % f_name)
self.format_code(f, """
res = ctx.create_insert(res, res_integral, 0);
res = ctx.create_insert(res, res_fractional, 1);
if (inst.get_return_derivs()) {
llvm::Value *res_dx = llvm::ConstantAggregateZero::get(ret_tp);
llvm::Value *res_dy = llvm::ConstantAggregateZero::get(ret_tp);
res_dx = ctx.create_insert(res_dx, ctx.get_dual_dx(a), 1);
res_dy = ctx.create_insert(res_dy, ctx.get_dual_dy(a), 1);
res = ctx.get_dual(res, res_dx, res_dy);
}
""")
elif mode == "math::luminance":
if params[0] == "F3" or params[0] == "CC":
# this is the code for F3, which is sRGB, the spec does not
# specify a color space for color, so we share the code
code = """
llvm::Constant *c_r = ctx.get_constant(0.212671f);
llvm::Constant *c_g = ctx.get_constant(0.715160f);
llvm::Constant *c_b = ctx.get_constant(0.072169f);
// res = c_r * a.x + c_g * a.y + c_b * a.z;
if (inst.get_return_derivs()) {
llvm::Value *r = ctx.create_extract_allow_deriv(a, 0);
llvm::Type *base_type = ctx.get_deriv_base_type(r->getType());
res = ctx.create_deriv_mul(base_type, r, c_r);
llvm::Value *g = ctx.create_extract_allow_deriv(a, 1);
res = ctx.create_deriv_add(base_type, res, ctx.create_deriv_mul(base_type, g, c_g));
llvm::Value *b = ctx.create_extract_allow_deriv(a, 2);
res = ctx.create_deriv_add(base_type, res, ctx.create_deriv_mul(base_type, b, c_b));
} else {
llvm::Value *r = ctx.create_extract(a, 0);
res = ctx->CreateFMul(r, c_r);
llvm::Value *g = ctx.create_extract(a, 1);
res = ctx->CreateFAdd(res, ctx->CreateFMul(g, c_g));
llvm::Value *b = ctx.create_extract(a, 2);
res = ctx->CreateFAdd(res, ctx->CreateFMul(b, c_b));
}
"""
self.format_code(f, code)
elif mode == "math::length":
vt = self.get_vector_type_and_size(params[0])
if vt:
atom_code = self.do_get_type_code(vt[0])
n_elems = vt[1]
f_name = "RT_SQRT" + self.get_type_suffix(atom_code).upper()
code_params = {
"sqrt_name" : f_name,
"n_elems" : n_elems,
"type" : vt[0]
}
code = """
if (inst.get_return_derivs()) {
mi::mdl::IDefinition const *sqrt_def = m_code_gen.find_stdlib_signature(
"::math", "sqrt(%(type)s)");
llvm::Function *sqrt_deriv_func = get_intrinsic_function(sqrt_def, /*return_derivs=*/ true);
llvm::Value *tmp = ctx.create_extract_allow_deriv(a, 0);
llvm::Type *base_type = ctx.get_deriv_base_type(tmp->getType());
tmp = ctx.create_deriv_mul(base_type, tmp, tmp);
for (unsigned i = 1; i < %(n_elems)d; ++i) {
llvm::Value *a_elem = ctx.create_extract_allow_deriv(a, i);
tmp = ctx.create_deriv_add(base_type, tmp, ctx.create_deriv_mul(base_type, a_elem, a_elem));
}
llvm::Value *sqrt_arg;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
sqrt_arg = ctx.create_local(tmp->getType(), "tmp");
ctx->CreateStore(tmp, sqrt_arg);
} else {
sqrt_arg = tmp;
}
res = ctx->CreateCall(sqrt_deriv_func, sqrt_arg);
} else {
llvm::Function *sqrt_func = get_runtime_func(%(sqrt_name)s);
llvm::Value *tmp = ctx.create_extract(a, 0);
tmp = ctx->CreateFMul(tmp, tmp);
for (unsigned i = 1; i < %(n_elems)d; ++i) {
llvm::Value *a_elem = ctx.create_extract(a, i);
tmp = ctx->CreateFAdd(tmp, ctx->CreateFMul(a_elem, a_elem));
}
res = ctx->CreateCall(sqrt_func, tmp);
}
""" % code_params
else:
# for atomic types, length() is abs()
atom_code = params[0]
f_name = "RT_ABS" + self.get_type_suffix(atom_code).upper()
code = """
if (inst.get_return_derivs()) {
mi::mdl::IDefinition const *abs_def = m_code_gen.find_stdlib_signature(
"::math", "abs(%(type)s)");
llvm::Function *abs_deriv_func = get_intrinsic_function(abs_def, /*return_derivs=*/ true);
llvm::Value *abs_arg;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
abs_arg = ctx.create_local(a->getType(), "tmp");
ctx->CreateStore(a, abs_arg);
} else {
abs_arg = a;
}
res = ctx->CreateCall(abs_deriv_func, abs_arg);
} else {
llvm::Function *abs_func = get_runtime_func(%(abs_name)s);
res = ctx->CreateCall(abs_func, a);
}
""" % {
"abs_name" : f_name,
"type" : self.m_inv_types[params[0]]
}
self.format_code(f, code)
elif mode == "math::normalize":
vt = self.get_vector_type_and_size(params[0])
if vt:
atom_code = self.do_get_type_code(vt[0])
n_elems = vt[1]
f_name = "RT_SQRT" + self.get_type_suffix(atom_code).upper()
code_params = {
"sqrt_name" : f_name,
"n_elems" : n_elems,
"vtype" : self.m_inv_types[params[0]]
}
code = """
if (inst.get_return_derivs()) {
mi::mdl::IDefinition const *length_def = m_code_gen.find_stdlib_signature(
"::math", "length(%(vtype)s)");
llvm::Function *length_deriv_func = get_intrinsic_function(length_def, /*return_derivs=*/ true);
llvm::Value *a_ptr = ctx.get_first_parameter();
llvm::Value *len = ctx->CreateCall(length_deriv_func, a_ptr);
llvm::Type *base_type = ctx.get_deriv_base_type(a->getType());
res = ctx.create_deriv_fdiv(base_type, a, len);
} else {
llvm::Function *sqrt_func = get_runtime_func(%(sqrt_name)s);
llvm::Type *arg_tp = a->getType();
res = llvm::ConstantAggregateZero::get(arg_tp);
if (arg_tp->isArrayTy()) {
unsigned idxes[1] = { 0 };
llvm::Value *tmp = ctx->CreateExtractValue(a, idxes);
tmp = ctx->CreateFMul(tmp, tmp);
for (unsigned i = 1; i < %(n_elems)d; ++i) {
idxes[0] = i;
llvm::Value *a_elem = ctx->CreateExtractValue(a, idxes);
tmp = ctx->CreateFAdd(tmp, ctx->CreateFMul(a_elem, a_elem));
}
llvm::Value *l = ctx->CreateCall(sqrt_func, tmp);
for (unsigned i = 0; i < %(n_elems)d; ++i) {
idxes[0] = i;
llvm::Value *a_elem = ctx->CreateExtractValue(a, idxes);
tmp = ctx->CreateFDiv(a_elem, l);
res = ctx->CreateInsertValue(res, tmp, idxes);
}
} else {
llvm::Value *idx = ctx.get_constant(0);
llvm::Value *tmp = ctx->CreateExtractElement(a, idx);
tmp = ctx->CreateFMul(tmp, tmp);
for (int i = 1; i < %(n_elems)d; ++i) {
idx = ctx.get_constant(i);
llvm::Value *a_elem = ctx->CreateExtractElement(a, idx);
tmp = ctx->CreateFAdd(tmp, ctx->CreateFMul(a_elem, a_elem));
}
llvm::Value *l = ctx->CreateCall(sqrt_func, tmp);
l = ctx.create_vector_splat(llvm::cast<llvm::VectorType>(arg_tp), l);
res = ctx->CreateFDiv(a, l);
}
}
""" % code_params
else:
# for atomic types, this normalize() is just sign()
f_name = self.get_runtime_enum("sign" + self.get_type_suffix(params[0]))
code = """
llvm::Function *callee = get_runtime_func(%s);
res = ctx->CreateCall(callee, ctx.get_dual_val(a));
if (inst.get_return_derivs()) { // expand to dual, derivatives are zero
res = ctx.get_dual(res);
}
""" % f_name
self.format_code(f, code)
elif mode == "math::distance":
vt = self.get_vector_type_and_size(params[0])
if vt:
atom_code = self.do_get_type_code(vt[0])
n_elems = vt[1]
f_name = "RT_SQRT" + self.get_type_suffix(atom_code).upper()
code_params = {
"sqrt_name" : f_name,
"n_elems" : n_elems,
"type" : self.m_inv_types[params[0]]
}
code = """
if (inst.get_return_derivs()) {
llvm::Type *base_type = ctx.get_deriv_base_type(a->getType());
llvm::Value *diff = ctx.create_deriv_sub(base_type, a, b);
mi::mdl::IDefinition const *length_def = m_code_gen.find_stdlib_signature(
"::math", "length(%(type)s)");
llvm::Function *length_deriv_func = get_intrinsic_function(length_def, /*return_derivs=*/ true);
llvm::Value *length_arg;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
length_arg = ctx.create_local(diff->getType(), "tmp");
ctx->CreateStore(diff, length_arg);
} else {
length_arg = diff;
}
res = ctx->CreateCall(length_deriv_func, length_arg);
} else {
llvm::Function *sqrt_func = get_runtime_func(%(sqrt_name)s);
llvm::Value *a_elem = ctx.create_extract(a, 0);
llvm::Value *b_elem = ctx.create_extract(b, 0);
llvm::Value *tmp = ctx->CreateFSub(a_elem, b_elem);
res = ctx->CreateFMul(tmp, tmp);
for (unsigned i = 1; i < %(n_elems)d; ++i) {
a_elem = ctx.create_extract(a, i);
b_elem = ctx.create_extract(b, i);
tmp = ctx->CreateFSub(a_elem, b_elem);
res = ctx->CreateFAdd(res, ctx->CreateFMul(tmp, tmp));
}
res = ctx->CreateCall(sqrt_func, res);
}
""" % code_params
else:
atom_code = params[0]
f_name = "RT_ABS" + self.get_type_suffix(atom_code).upper()
code = """
if (inst.get_return_derivs()) {
llvm::Type *base_type = ctx.get_deriv_base_type(a->getType());
llvm::Value *diff = ctx.create_deriv_sub(base_type, a, b);
mi::mdl::IDefinition const *abs_def = m_code_gen.find_stdlib_signature(
"::math", "abs(%(type)s)");
llvm::Function *abs_deriv_func = get_intrinsic_function(abs_def, /*return_derivs=*/ true);
llvm::Value *abs_arg;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
abs_arg = ctx.create_local(diff->getType(), "tmp");
ctx->CreateStore(diff, abs_arg);
} else {
abs_arg = diff;
}
res = ctx->CreateCall(abs_deriv_func, abs_arg);
} else {
llvm::Function *abs_func = get_runtime_func(%(abs_name)s);
res = ctx->CreateFSub(a, b);
res = ctx->CreateCall(abs_func, res);
}
""" % {
"abs_name" : f_name,
"type" : self.m_inv_types[params[0]]
}
self.format_code(f, code)
elif mode == "math::DX|DY":
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
if (m_code_gen.m_type_mapper.is_deriv_type(a->getType())) {
res = ctx.get_dual_%(comp)s(a);
} else {
// for non-derivative types, always return null
res = llvm::Constant::getNullValue(ret_tp);
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""" % { "comp": intrinsic.lower() }
self.format_code(f, code)
elif mode == "math::component_wise":
vt = self.get_vector_type_and_size(ret_type)
# vector/color all same base arguments
n_elems = 0
if ret_type == "CC":
n_elems = 3
else:
n_elems = vt[1]
atom_code = self.do_get_type_code(vt[0])
f_name = self.get_runtime_enum(intrinsic + self.get_type_suffix(atom_code))
# For derivatives:
# per component:
# get dual for component
# call atomic function on the dual
# add to result aggregate
self.format_code(f, """
if (inst.get_return_derivs()) {
// get atomic function (with derivatives)
mi::mdl::IDefinition const *a_def = m_code_gen.find_stdlib_signature(
"::math", "%(intrinsic)s(%(param_types)s)");
llvm::Function *a_func = get_intrinsic_function(a_def, /*return_derivs=*/ true);
llvm::Value *a_args[%(len_params)d];
llvm::Value *a_arg_vars[%(len_params)d] = { 0 };
llvm::Value *a_res[%(n_elems)d];
llvm::Value *tmp;
""" % {
"intrinsic": intrinsic,
"param_types": ",".join(map(
lambda t: (self.get_vector_type_and_size(t) or (self.m_inv_types[t],))[0],
params)),
"len_params": len(params),
"n_elems": n_elems
})
# TODO: Expensive copying around
for i in range(n_elems):
self.write(f, "arg_it = ctx.get_first_parameter();\n")
for idx, param in enumerate(params):
p_name = chr(ord('a') + idx)
if self.is_atomic_type(param):
self.write(f, "a_args[%d] = arg_it;\n" % idx)
else:
self.format_code(f, """
tmp = ctx.extract_dual(%(p_name)s, %(elem)d);
""" % {
"p_name": p_name,
"elem": i
})
if i == 0:
self.format_code(f,
"""if (m_code_gen.m_type_mapper.target_supports_pointers()) {
a_arg_vars[%(idx)d] = ctx.create_local(tmp->getType(), "%(p_name)s");
a_args[%(idx)d] = a_arg_vars[%(idx)d];
ctx->CreateStore(tmp, a_arg_vars[%(idx)d]);
} else {
a_args[%(idx)d] = tmp;
}
""" % {
"p_name": p_name,
"idx": idx
})
else:
self.format_code(f,
"""if (m_code_gen.m_type_mapper.target_supports_pointers()) {
ctx->CreateStore(tmp, a_arg_vars[%(idx)d]);
} else {
a_args[%(idx)d] = tmp;
}
""" % {
"p_name": p_name,
"idx": idx
})
self.write(f, "++arg_it;\n")
self.write(f, "a_res[%d] = ctx->CreateCall(a_func, a_args);\n" % i)
self.format_code(f, """
llvm::Type *ret_tp_elem = ctx.get_non_deriv_return_type();
llvm::Value *val = llvm::ConstantAggregateZero::get(ret_tp_elem);
llvm::Value *dx = llvm::ConstantAggregateZero::get(ret_tp_elem);
llvm::Value *dy = llvm::ConstantAggregateZero::get(ret_tp_elem);
""")
for i in range(n_elems):
self.format_code(f, """
val = ctx.create_insert(val, ctx.get_dual_val(a_res[%(idx)d]), %(idx)d);
dx = ctx.create_insert(dx, ctx.get_dual_dx(a_res[%(idx)d]), %(idx)d);
dy = ctx.create_insert(dy, ctx.get_dual_dy(a_res[%(idx)d]), %(idx)d);
""" % { "idx": i })
self.format_code(f, """
res = ctx.get_dual(val, dx, dy);
} else {
llvm::Value *args[%(len_params)d];
llvm::Value *tmp;
// get atomic function (without derivatives)
mi::mdl::IDefinition const *a_def = m_code_gen.find_stdlib_signature(
"::math", "%(intrinsic)s(%(param_types)s)");
llvm::Function *elem_func = get_intrinsic_function(a_def, /*return_derivs=*/false);
res = llvm::ConstantAggregateZero::get(ctx_data->get_return_type());
""" % {
"intrinsic": intrinsic,
"param_types": ",".join(map(
lambda t: (self.get_vector_type_and_size(t) or (self.m_inv_types[t],))[0],
params)),
"len_params": len(params)} )
for i in range(n_elems):
for idx, param in enumerate(params):
p_name = chr(ord('a') + idx)
if self.is_atomic_type(param):
self.write(f, "args[%d] = %s;\n" % (idx, p_name))
else:
self.write(f, "args[%d] = ctx.create_extract(%s, %d);\n" % (idx, p_name, i))
self.write(f, "tmp = ctx->CreateCall(elem_func, args);\n")
self.write(f, "res = ctx.create_insert(res, tmp, %s);\n" % i)
self.format_code(f, "}\n")
elif mode == "math::eval_at_wavelength":
code = ""
idx = 0
for param in params:
code += """
(void)%s;""" % chr(ord('a') + idx)
idx = idx + 1
code += """
// FIXME: unsupported yet
res = llvm::Constant::getNullValue(ctx_data->get_return_type());
"""
self.format_code(f, code)
elif mode == "math::blackbody":
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
llvm::Function *bb_func = get_runtime_func(RT_MDL_BLACKBODY);
llvm::ArrayType *arr_tp = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Value *tmp = ctx.create_local(arr_tp, "tmp");
ctx->CreateCall(bb_func, { tmp, ctx.get_dual_val(a) });
if (ret_tp->isArrayTy()) {
res = ctx->CreateLoad(tmp);
} else {
llvm::Value *arr = ctx->CreateLoad(tmp);
res = llvm::ConstantAggregateZero::get(ret_tp);
for (unsigned i = 0; i < 3; ++i) {
unsigned idxes[1] = { i };
tmp = ctx->CreateExtractValue(arr, idxes);
llvm::Value *idx = ctx.get_constant(int(i));
res = ctx->CreateInsertElement(res, tmp, idx);
}
}
if (!m_has_res_handler) {
// need libmdlrt
m_code_gen.m_link_libmdlrt = true;
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
"""
self.format_code(f, code)
elif mode == "math::first_arg":
code = ""
first = True
for param in params:
if first:
first = False
else:
code += """
(void)%s;""" % chr(ord('a') + idx)
idx = idx + 1
code += """
res = a;
"""
self.format_code(f, code)
elif mode == "math::emission_color" or mode == "spectrum_constructor":
params = {}
if mode == "math::emission_color":
params["intrinsic"] = "RT_MDL_EMISSION_COLOR"
else:
params["intrinsic"] = "RT_MDL_REFLECTION_COLOR"
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
llvm::Function *bb_func = get_runtime_func(%(intrinsic)s);
llvm::ArrayType *arr_tp = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Value *tmp = ctx.create_local(arr_tp, "tmp");
llvm::Value *a_desc = ctx.get_dual_val(a);
llvm::Value *b_desc = ctx.get_dual_val(b);
// this is a runtime function, and as such it is not instantiated, so the arrays are
// passed by array descriptors
if (m_code_gen.target_is_structured_language(m_target_lang)) {
// passed by value
// we must always inline this for GLSL/HLSL to avoid pointer type arguments
func->addFnAttr(llvm::Attribute::AlwaysInline);
llvm::Value *args[] = {
ctx->CreateBitCast(tmp, m_code_gen.m_type_mapper.get_float_ptr_type()),
ctx.get_deferred_base(a_desc),
ctx.get_deferred_base(b_desc),
ctx->CreateTrunc(
ctx.get_deferred_size(a_desc),
m_code_gen.m_type_mapper.get_int_type())
};
ctx->CreateCall(bb_func, args);
} else {
// passed by pointer
llvm::Value *args[] = {
ctx->CreateBitCast(tmp, m_code_gen.m_type_mapper.get_float_ptr_type()),
ctx.get_deferred_base_from_ptr(a_desc),
ctx.get_deferred_base_from_ptr(b_desc),
ctx->CreateTrunc(
ctx.get_deferred_size_from_ptr(a_desc),
m_code_gen.m_type_mapper.get_int_type())
};
ctx->CreateCall(bb_func, args);
}
if (ret_tp->isArrayTy()) {
res = ctx->CreateLoad(tmp);
} else {
llvm::Value *arr = ctx->CreateLoad(tmp);
res = llvm::ConstantAggregateZero::get(ret_tp);
for (unsigned i = 0; i < 3; ++i) {
unsigned idxes[1] = { i };
tmp = ctx->CreateExtractValue(arr, idxes);
llvm::Value *idx = ctx.get_constant(int(i));
res = ctx->CreateInsertElement(res, tmp, idx);
}
}
// need libmdlrt
m_code_gen.m_link_libmdlrt = true;
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
"""
self.format_code(f, code % params)
elif mode == "state::core_set":
self.format_code(f,
"""
llvm::Type *ret_tp = %s;
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *adr = ctx.create_simple_gep_in_bounds(
state, ctx.get_constant(m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_%s)));
res = ctx.load_and_convert(ret_tp, adr);
} else {
// zero in all other contexts
res = llvm::Constant::getNullValue(ret_tp);
}
""" % (
"ctx.get_return_type()" if intrinsic == "position" else "ctx.get_non_deriv_return_type()",
intrinsic.upper()
))
if intrinsic == "position":
self.format_code(f,
"""
// no derivatives requested? -> get value component
if (!inst.get_return_derivs() && m_code_gen.m_type_mapper.use_derivatives()) {
res = ctx.get_dual_val(res);
}
""")
else:
self.format_code(f,
"""
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""")
elif mode == "state::meters_per_scene_unit":
self.format_code(f,
"""
if (m_code_gen.m_fold_meters_per_scene_unit) {
res = ctx.get_constant(m_code_gen.m_meters_per_scene_unit);
} else {
llvm::Type *ret_tp = %s;
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *adr = ctx.create_simple_gep_in_bounds(
state, ctx.get_constant(m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_METERS_PER_SCENE_UNIT)));
res = ctx.load_and_convert(ret_tp, adr);
} else {
// zero in all other contexts, as currently not available in state
res = llvm::Constant::getNullValue(ret_tp);
}
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""" % (
"ctx.get_non_deriv_return_type()",
))
elif mode == "state::scene_units_per_meter":
self.format_code(f,
"""
if (m_code_gen.m_fold_meters_per_scene_unit) {
res = ctx.get_constant(1.f / m_code_gen.m_meters_per_scene_unit);
} else {
llvm::Type *ret_tp = %s;
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *adr = ctx.create_simple_gep_in_bounds(
state, ctx.get_constant(m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_METERS_PER_SCENE_UNIT)));
res = ctx.load_and_convert(ret_tp, adr);
res = ctx->CreateFDiv(ctx.get_constant(1.f), res);
} else {
// zero in all other contexts, as currently not available in state
res = llvm::Constant::getNullValue(ret_tp);
}
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""" % (
"ctx.get_non_deriv_return_type()",
))
elif mode == "state::wavelength_min_max":
self.format_code(f,
"""
res = ctx.get_constant(m_code_gen.m_%s);
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""" % intrinsic)
elif mode == "state::rounded_corner_normal":
code = """
// map to state::normal"""
idx = 0
for param in params:
code += """
(void)%s;""" % chr(ord('a') + idx)
idx = idx + 1
code += """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *adr = ctx.create_simple_gep_in_bounds(
state, ctx.get_constant(m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_NORMAL)));
res = ctx.load_and_convert(ret_tp, adr);
} else {
// zero in all other contexts
res = llvm::Constant::getNullValue(ret_tp);
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
"""
self.format_code(f, code)
elif mode == "state::texture_coordinate":
code = """
llvm::Type *ret_tp = ctx_data->get_return_type();
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *tex_coord_state_idx = ctx.get_constant(m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_%s));
llvm::Value *adr;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
adr = ctx.create_simple_gep_in_bounds(state, tex_coord_state_idx);
llvm::Value *tc = ctx->CreateLoad(adr);
adr = ctx->CreateInBoundsGEP(tc, a);
} else {
llvm::Value *idxs[] = {
ctx.get_constant(int(0)),
tex_coord_state_idx,
a
};
adr = ctx->CreateInBoundsGEP(state, idxs);
}
// no derivatives requested? -> get pointer to value component
if (!inst.get_return_derivs() && m_code_gen.m_type_mapper.use_derivatives()) {
adr = ctx.create_simple_gep_in_bounds(adr, 0u);
}
res = ctx.load_and_convert(ret_tp, adr);
} else {
// zero in all other contexts
res = llvm::Constant::getNullValue(ret_tp);
}
"""
self.format_code(f, code % intrinsic.upper())
elif mode == "state::texture_space_max":
code = """
// always a runtime-constant
res = ctx.get_constant(int(m_code_gen.m_num_texture_spaces));
"""
self.format_code(f, code)
elif mode == "state::texture_tangent_v":
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
if (m_code_gen.m_type_mapper.use_bitangents()) {
// encoded as bitangent
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *adr = ctx.create_simple_gep_in_bounds(
state, ctx.get_constant(m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_BITANGENTS)));
llvm::Value *tc = ctx->CreateLoad(adr);
adr = ctx->CreateInBoundsGEP(tc, a);
// we need only xyz from the float4, so just cast it
adr = ctx->CreateBitCast(adr, m_code_gen.m_type_mapper.get_arr_float_3_ptr_type());
res = ctx.load_and_convert(ret_tp, adr);
mi::mdl::IDefinition const *nz_def = m_code_gen.find_stdlib_signature("::math", "normalize(float3)");
llvm::Function *nz_fkt = get_intrinsic_function(nz_def, /*return_derivs=*/ false);
llvm::Value *nz_args[] = { res };
res = call_rt_func(ctx, nz_fkt, nz_args);
} else {
// directly encoded
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *tangent_v_state_idx = ctx.get_constant(
m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_TANGENT_V));
llvm::Value *adr;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
adr = ctx.create_simple_gep_in_bounds(state, tangent_v_state_idx);
llvm::Value *tc = ctx->CreateLoad(adr);
adr = ctx->CreateInBoundsGEP(tc, a);
} else {
llvm::Value *idxs[] = {
ctx.get_constant(int(0)),
tangent_v_state_idx,
a
};
adr = ctx->CreateInBoundsGEP(state, idxs);
}
res = ctx.load_and_convert(ret_tp, adr);
}
} else {
// zero in all other contexts
(void)a;
res = llvm::Constant::getNullValue(ret_tp);
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
"""
self.format_code(f, code)
elif mode == "state::texture_tangent_u":
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
if (m_code_gen.m_type_mapper.use_bitangents()) {
// encoded as bitangent
// float3 bitangent = cross(normal, tangent) * tangent_bitangentsign.w
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *exc = ctx.get_exc_state_parameter();
mi::mdl::IDefinition const *n_def = m_code_gen.find_stdlib_signature("::state", "normal()");
llvm::Function *n_fkt = get_intrinsic_function(n_def, /*return_derivs=*/ false);
llvm::Value *n_args[] = { state };
llvm::Value *normal = call_rt_func(ctx, n_fkt, n_args);
mi::mdl::IDefinition const *t_def = m_code_gen.find_stdlib_signature("::state", "texture_tangent_v(int)");
llvm::Function *t_fkt = get_intrinsic_function(t_def, /*return_derivs=*/ false);
llvm::Value *t_args[] = { state, exc, a };
llvm::Value *tangent = call_rt_func(ctx, t_fkt, t_args);
mi::mdl::IDefinition const *c_def = m_code_gen.find_stdlib_signature("::math", "cross(float3,float3)");
llvm::Function *c_fkt = get_intrinsic_function(c_def, /*return_derivs=*/ false);
llvm::Value *c_args[] = { normal, tangent };
llvm::Value *cross = call_rt_func(ctx, c_fkt, c_args);
mi::mdl::IDefinition const *nz_def = m_code_gen.find_stdlib_signature("::math", "normalize(float3)");
llvm::Function *nz_fkt = get_intrinsic_function(nz_def, /*return_derivs=*/ false);
llvm::Value *nz_args[] = { cross };
llvm::Value *n_cross = call_rt_func(ctx, nz_fkt, nz_args);
llvm::Value *adr = ctx.create_simple_gep_in_bounds(
state, ctx.get_constant(m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_BITANGENTS)));
llvm::Value *tc = ctx->CreateLoad(adr);
adr = ctx->CreateInBoundsGEP(tc, a);
// we need only w from the float4
adr = ctx.create_simple_gep_in_bounds(adr, ctx.get_constant(3));
llvm::Value *sign = ctx->CreateLoad(adr);
res = ctx.create_mul(ret_tp, n_cross, sign);
} else {
// directly encoded
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *tangent_u_state_idx = ctx.get_constant(
m_code_gen.m_type_mapper.get_state_index(Type_mapper::STATE_CORE_TANGENT_U));
llvm::Value *adr;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
adr = ctx.create_simple_gep_in_bounds(state, tangent_u_state_idx);
llvm::Value *tc = ctx->CreateLoad(adr);
adr = ctx->CreateInBoundsGEP(tc, a);
} else {
llvm::Value *idxs[] = {
ctx.get_constant(int(0)),
tangent_u_state_idx,
a
};
adr = ctx->CreateInBoundsGEP(state, idxs);
}
res = ctx.load_and_convert(ret_tp, adr);
}
} else {
// zero in all other contexts
(void)a;
res = llvm::Constant::getNullValue(ret_tp);
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
"""
self.format_code(f, code)
elif mode == "state::geometry_tangent_u":
code = """
// normal = state::geometry_normal()
// geom_tu = math::normalize(tangent_u - math::dot(tangent_u, normal) * normal);
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *tu_args[3] = { state, a, NULL };
size_t len = 2;
if (m_code_gen.target_uses_exception_state_parameter()) {
tu_args[1] = ctx.get_exc_state_parameter();
tu_args[2] = a;
++len;
}
mi::mdl::IDefinition const *gn_def = m_code_gen.find_stdlib_signature("::state", "geometry_normal()");
llvm::Function *gn_fkt = get_intrinsic_function(gn_def, /*return_derivs=*/ false);
llvm::Value *gn_args[] = { state };
llvm::Value *normal = call_rt_func(ctx, gn_fkt, gn_args);
mi::mdl::IDefinition const *tu_def = m_code_gen.find_stdlib_signature("::state", "texture_tangent_u(int)");
llvm::Function *tu_fkt = get_intrinsic_function(tu_def, /*return_derivs=*/ false);
llvm::Value *tangent_u = call_rt_func(ctx, tu_fkt, llvm::ArrayRef<llvm::Value *>(tu_args, len));
mi::mdl::IDefinition const *dot_def = m_code_gen.find_stdlib_signature("::math", "dot(float3,float3)");
llvm::Function *dot_fkt = get_intrinsic_function(dot_def, /*return_derivs=*/ false);
llvm::Value *dot_args[] = { tangent_u, normal };
llvm::Value *dot_res = call_rt_func(ctx, dot_fkt, dot_args);
llvm::Type *ret_tp = ctx_data->get_return_type();
llvm::Value *mul_res = ctx.create_mul(ret_tp, dot_res, normal);
llvm::Value *sub_res = ctx.create_sub(ret_tp, tangent_u, mul_res);
mi::mdl::IDefinition const *nz_def = m_code_gen.find_stdlib_signature("::math", "normalize(float3)");
llvm::Function *nz_fkt = get_intrinsic_function(nz_def, /*return_derivs=*/ false);
llvm::Value *nz_args[] = { sub_res };
res = call_rt_func(ctx, nz_fkt, nz_args);
"""
self.format_code(f, code)
elif mode == "state::geometry_tangent_v":
code = """
// normal = state::geometry_normal()
// geom_tv = math::normalize(tangent_v - math::dot(tangent_v, geom_tu) * geom_tu - math::dot(tangent_v, normal) * normal);
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *tu_args[3] = { state, a, NULL };
size_t len = 2;
if (m_code_gen.target_uses_exception_state_parameter()) {
tu_args[1] = ctx.get_exc_state_parameter();
tu_args[2] = a;
++len;
}
mi::mdl::IDefinition const *gn_def = m_code_gen.find_stdlib_signature("::state", "geometry_normal()");
llvm::Function *gn_fkt = get_intrinsic_function(gn_def, /*return_derivs=*/ false);
llvm::Value *gn_args[] = { state };
llvm::Value *normal = call_rt_func(ctx, gn_fkt, gn_args);
mi::mdl::IDefinition const *tu_def = m_code_gen.find_stdlib_signature("::state", "texture_tangent_u(int)");
llvm::Function *tu_fkt = get_intrinsic_function(tu_def, /*return_derivs=*/ false);
llvm::Value *tangent_u = call_rt_func(ctx, tu_fkt, llvm::ArrayRef<llvm::Value *>(tu_args, len));
mi::mdl::IDefinition const *dot_def = m_code_gen.find_stdlib_signature("::math", "dot(float3,float3)");
llvm::Function *dot_fkt = get_intrinsic_function(dot_def, /*return_derivs=*/ false);
llvm::Value *dot_args_u[] = { tangent_u, normal };
llvm::Value *dot_res_u = call_rt_func(ctx, dot_fkt, dot_args_u);
llvm::Type *ret_tp = ctx_data->get_return_type();
llvm::Value *mul_res_u = ctx.create_mul(ret_tp, dot_res_u, normal);
llvm::Value *sub_res_u = ctx.create_sub(ret_tp, tangent_u, mul_res_u);
mi::mdl::IDefinition const *nz_def = m_code_gen.find_stdlib_signature("::math", "normalize(float3)");
llvm::Function *nz_fkt = get_intrinsic_function(nz_def, /*return_derivs=*/ false);
llvm::Value *nz_args[] = { sub_res_u };
llvm::Value *geom_tu = call_rt_func(ctx, nz_fkt, nz_args);
mi::mdl::IDefinition const *tv_def = m_code_gen.find_stdlib_signature("::state", "texture_tangent_v(int)");
llvm::Function *tv_fkt = get_intrinsic_function(tv_def, /*return_derivs=*/ false);
llvm::Value *tangent_v = call_rt_func(ctx, tv_fkt, llvm::ArrayRef<llvm::Value *>(tu_args, len));
llvm::Value *dot_args_v[] = { tangent_v, normal };
llvm::Value *dot_res_v = call_rt_func(ctx, dot_fkt, dot_args_v);
llvm::Value *part_2 = ctx.create_mul(ret_tp, dot_res_v, normal);
llvm::Value *dot_args_tu[] = { tangent_v, geom_tu };
llvm::Value *dot_res_tu = call_rt_func(ctx, dot_fkt, dot_args_tu);
llvm::Value *part_1 = ctx.create_mul(ret_tp, dot_res_tu, geom_tu);
res = ctx.create_sub(ret_tp, tangent_v, part_1);
res = ctx.create_sub(ret_tp, res, part_2);
llvm::Value *nz_args_v[] = { res };
res = call_rt_func(ctx, nz_fkt, nz_args_v);
"""
self.format_code(f, code)
elif mode == "state::environment_set":
code = """
llvm::Type *ret_tp = ctx_data->get_return_type();
if (m_code_gen.m_state_mode & Type_mapper::SSM_ENVIRONMENT) {
// direction exists only in environmnt context
llvm::Value *state = ctx.get_state_parameter();
llvm::Value *adr = ctx.create_simple_gep_in_bounds(
state, ctx.get_constant(Type_mapper::STATE_ENV_%s));
res = ctx.load_and_convert(ret_tp, adr);
} else {
// zero in all other contexts
res = llvm::Constant::getNullValue(ret_tp);
}
"""
self.format_code(f, code % intrinsic.upper())
elif mode == "state::transform":
code = """
llvm::Type *ret_tp = ctx.get_non_deriv_return_type();
llvm::Value *from = a;
llvm::Value *to = b;
llvm::Value *internal = ctx.get_constant(LLVM_code_generator::coordinate_internal);
llvm::Value *encoding = ctx.get_constant(m_internal_space);
// map internal space
llvm::Value *f_cond = ctx->CreateICmpEQ(from, internal);
from = ctx->CreateSelect(f_cond, encoding, from);
llvm::Value *t_cond = ctx->CreateICmpEQ(to, internal);
to = ctx->CreateSelect(t_cond, encoding, to);
res = llvm::Constant::getNullValue(ret_tp);
llvm::Value *result = ctx.create_local(ret_tp, "result");
ctx->CreateStore(res, result);
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::Value *cond = ctx->CreateICmpEQ(from, to);
llvm::BasicBlock *id_bb = ctx.create_bb("id");
llvm::BasicBlock *non_id_bb = ctx.create_bb("non_id");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
if (ret_tp->isVectorTy()) {
// BIG vector mode
ctx->CreateCondBr(cond, id_bb, non_id_bb);
{
llvm::Value *idx;
// return the identity matrix
ctx->SetInsertPoint(id_bb);
llvm::Value *one = ctx.get_constant(1.0f);
idx = ctx.get_constant(0 * 4 + 0);
ctx->CreateInsertElement(res, one, idx);
idx = ctx.get_constant(1 * 4 + 1);
ctx->CreateInsertElement(res, one, idx);
idx = ctx.get_constant(2 * 4 + 2);
ctx->CreateInsertElement(res, one, idx);
idx = ctx.get_constant(3 * 4 + 3);
ctx->CreateInsertElement(res, one, idx);
ctx->CreateStore(res, result);
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(non_id_bb);
llvm::Value *worldToObject = ctx.get_constant(LLVM_code_generator::coordinate_world);
llvm::Value *cond = ctx->CreateICmpEQ(from, worldToObject);
// convert w2o or o2w matrix from row-major to col-major
llvm::Value *m_ptr = ctx->CreateSelect(
cond, ctx.get_w2o_transform_value(), ctx.get_o2w_transform_value());
res = llvm::Constant::getNullValue(ret_tp);
for (int i = 0; i < 3; ++i) {
llvm::Value *idx = ctx.get_constant(i);
llvm::Value *ptr = ctx->CreateInBoundsGEP(m_ptr, idx);
llvm::Value *row = ctx->CreateLoad(ptr);
for (int j = 0; j < 4; ++j) {
unsigned idxes[] = { unsigned(j) };
llvm::Value *elem = ctx->CreateExtractValue(row, idxes);
llvm::Value *idx = ctx.get_constant(i + j * 4);
res = ctx->CreateInsertElement(res, elem, idx);
}
}
{
// last row is always (0, 0, 0, 1)
for (int j = 0; j < 4; ++j) {
llvm::Value *elem = ctx.get_constant(j == 3 ? 1.0f : 0.0f);
llvm::Value *idx = ctx.get_constant(3 + j * 4);
res = ctx->CreateInsertElement(res, elem, idx);
}
}
ctx->CreateStore(res, result);
ctx->CreateBr(end_bb);
}
ctx->SetInsertPoint(end_bb);
} else if (ret_tp->isArrayTy()) {
llvm::ArrayType *arr_tp = llvm::cast<llvm::ArrayType>(ret_tp);
llvm::Type *e_tp = arr_tp->getElementType();
if (e_tp->isVectorTy()) {
// small vector mode
llvm::Value *col;
ctx->CreateCondBr(cond, id_bb, non_id_bb);
{
// return the identity matrix
ctx->SetInsertPoint(id_bb);
llvm::Value *one = ctx.get_constant(1.0f);
for (unsigned i = 0; i < 4; ++i) {
unsigned idxes[1] { i };
col = ctx->CreateExtractValue(res, idxes);
col = ctx->CreateInsertElement(col, one, ctx.get_constant(int(i)));
ctx->CreateInsertValue(res, col, idxes);
}
ctx->CreateStore(res, result);
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(non_id_bb);
llvm::Value *worldToObject = ctx.get_constant(LLVM_code_generator::coordinate_world);
llvm::Value *cond = ctx->CreateICmpEQ(from, worldToObject);
// convert w2o or o2w matrix from row-major to col-major
llvm::Value *matrix = ctx->CreateSelect(
cond, ctx.get_w2o_transform_value(), ctx.get_o2w_transform_value());
llvm::Value *m_ptr =
llvm::isa<llvm::PointerType>(matrix->getType()) ? matrix : NULL;
llvm::Value *res_cols[4] = {
llvm::Constant::getNullValue(e_tp),
llvm::Constant::getNullValue(e_tp),
llvm::Constant::getNullValue(e_tp),
llvm::Constant::getNullValue(e_tp)
};
res = llvm::Constant::getNullValue(ret_tp);
for (int i = 0; i < 3; ++i) {
llvm::Value *row;
unsigned idxes[] = { unsigned(i) };
if (m_ptr != NULL) {
// matrix is a pointer
llvm::Value *idx = ctx.get_constant(i);
llvm::Value *ptr = ctx->CreateInBoundsGEP(m_ptr, idx);
row = ctx->CreateLoad(ptr);
} else {
// matrix is a value
row = ctx->CreateExtractValue(matrix, idxes);
}
for (int j = 0; j < 4; ++j) {
unsigned elem_idx = { unsigned(j) };
llvm::Value *elem = ctx->CreateExtractElement(row, elem_idx);
res_cols[j] = ctx->CreateInsertElement(res_cols[j], elem, unsigned(i));
}
}
// last row is always (0, 0, 0, 1), so insert the 1 into res_cols[3][3]
llvm::Value *one = ctx.get_constant(1.0f);
res_cols[3] = ctx->CreateInsertElement(res_cols[3], one, 3);
for (unsigned i = 0; i < 4; ++i) {
res = ctx->CreateInsertValue(res, res_cols[i], i);
}
ctx->CreateStore(res, result);
ctx->CreateBr(end_bb);
}
ctx->SetInsertPoint(end_bb);
} else {
// scalar mode
ctx->CreateCondBr(cond, id_bb, non_id_bb);
{
// return the identity matrix
ctx->SetInsertPoint(id_bb);
unsigned idxes[] = { 0 * 4 + 0 };
llvm::Value *one = ctx.get_constant(1.0f);
ctx->CreateInsertValue(res, one, idxes);
idxes[0] = 1 * 4 + 1;
ctx->CreateInsertValue(res, one, idxes);
idxes[0] = 2 * 4 + 2;
ctx->CreateInsertValue(res, one, idxes);
idxes[0] = 3 * 4 + 3;
ctx->CreateInsertValue(res, one, idxes);
ctx->CreateStore(res, result);
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(non_id_bb);
llvm::Value *worldToObject = ctx.get_constant(LLVM_code_generator::coordinate_world);
llvm::Value *cond = ctx->CreateICmpEQ(from, worldToObject);
// convert w2o or o2w matrix from row-major to col-major
llvm::Value *m_ptr = ctx->CreateSelect(
cond, ctx.get_w2o_transform_value(), ctx.get_o2w_transform_value());
res = llvm::Constant::getNullValue(ret_tp);
for (int i = 0; i < 3; ++i) {
llvm::Value *idx = ctx.get_constant(i);
llvm::Value *ptr = ctx->CreateInBoundsGEP(m_ptr, idx);
llvm::Value *row = ctx->CreateLoad(ptr);
for (unsigned j = 0; j < 4; ++j) {
unsigned idxes[] = { j };
llvm::Value *elem = ctx->CreateExtractValue(row, idxes);
idxes[0] = unsigned(i) + j * 4;
res = ctx->CreateInsertValue(res, elem, idxes);
}
}
{
// last row is always (0, 0, 0, 1)
for (unsigned j = 0; j < 4; ++j) {
unsigned idxes[] = { 3 + j * 4 };
llvm::Value *elem = ctx.get_constant(j == 3 ? 1.0f : 0.0f);
res = ctx->CreateInsertValue(res, elem, idxes);
}
}
ctx->CreateStore(res, result);
ctx->CreateBr(end_bb);
}
ctx->SetInsertPoint(end_bb);
}
}
} else {
// zero in all other contexts
}
res = ctx->CreateLoad(result);
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
"""
self.format_code(f, code)
elif mode == "state::transform_point":
code = """
llvm::Type *ret_tp = ctx.get_return_type();
llvm::Value *from = a;
llvm::Value *to = b;
llvm::Value *point = c;
llvm::Value *internal = ctx.get_constant(LLVM_code_generator::coordinate_internal);
llvm::Value *encoding = ctx.get_constant(m_internal_space);
// map internal space
llvm::Value *f_cond = ctx->CreateICmpEQ(from, internal);
from = ctx->CreateSelect(f_cond, encoding, from);
llvm::Value *t_cond = ctx->CreateICmpEQ(to, internal);
to = ctx->CreateSelect(t_cond, encoding, to);
llvm::Value *cond = ctx->CreateICmpEQ(from, to);
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::BasicBlock *pre_if_bb = ctx->GetInsertBlock();
llvm::BasicBlock *non_id_bb = ctx.create_bb("non_id");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
llvm::Value *non_id_res;
ctx->CreateCondBr(cond, end_bb, non_id_bb);
{
// "from" and "to" are unequal
ctx->SetInsertPoint(non_id_bb);
llvm::Value *worldToObject = ctx.get_constant(LLVM_code_generator::coordinate_world);
llvm::Value *cond_is_w2o = ctx->CreateICmpEQ(from, worldToObject);
llvm::Value *matrix = ctx->CreateSelect(
cond_is_w2o,
ctx.get_w2o_transform_value(),
ctx.get_o2w_transform_value());
if (inst.get_return_derivs()) {
non_id_res = ctx.create_deriv_mul_state_V3xM(
ret_tp, point, matrix, /*ignore_translation=*/ false, /*transposed=*/ false);
} else {
non_id_res = ctx.create_mul_state_V3xM(
ret_tp, point, matrix, /*ignore_translation=*/ false, /*transposed=*/ false);
}
ctx->CreateBr(end_bb);
}
ctx->SetInsertPoint(end_bb);
llvm::PHINode *phi = ctx->CreatePHI(ret_tp, 2);
phi->addIncoming(point, pre_if_bb); // the matrix is the identity, return the point
phi->addIncoming(non_id_res, non_id_bb);
res = phi;
} else {
// either identity or zero in all other contexts
res = ctx->CreateSelect(cond, point, llvm::Constant::getNullValue(ret_tp));
}
"""
self.format_code(f, code)
elif mode == "state::transform_vector":
code = """
llvm::Type *ret_tp = ctx.get_return_type();
llvm::Value *from = a;
llvm::Value *to = b;
llvm::Value *vector = c;
llvm::Value *internal = ctx.get_constant(LLVM_code_generator::coordinate_internal);
llvm::Value *encoding = ctx.get_constant(m_internal_space);
// map internal space
llvm::Value *f_cond = ctx->CreateICmpEQ(from, internal);
from = ctx->CreateSelect(f_cond, encoding, from);
llvm::Value *t_cond = ctx->CreateICmpEQ(to, internal);
to = ctx->CreateSelect(t_cond, encoding, to);
llvm::Value *cond = ctx->CreateICmpEQ(from, to);
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::BasicBlock *pre_if_bb = ctx->GetInsertBlock();
llvm::BasicBlock *non_id_bb = ctx.create_bb("non_id");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
llvm::Value *non_id_res;
ctx->CreateCondBr(cond, end_bb, non_id_bb);
{
// "from" and "to" are unequal
ctx->SetInsertPoint(non_id_bb);
llvm::Value *worldToObject = ctx.get_constant(LLVM_code_generator::coordinate_world);
llvm::Value *cond_is_w2o = ctx->CreateICmpEQ(from, worldToObject);
llvm::Value *matrix = ctx->CreateSelect(
cond_is_w2o,
ctx.get_w2o_transform_value(),
ctx.get_o2w_transform_value());
if (inst.get_return_derivs()) {
non_id_res = ctx.create_deriv_mul_state_V3xM(
ret_tp, vector, matrix, /*ignore_translation=*/ true, /*transposed=*/ false);
} else {
non_id_res = ctx.create_mul_state_V3xM(
ret_tp, vector, matrix, /*ignore_translation=*/ true, /*transposed=*/ false);
}
ctx->CreateBr(end_bb);
}
ctx->SetInsertPoint(end_bb);
llvm::PHINode *phi = ctx->CreatePHI(ret_tp, 2);
phi->addIncoming(vector, pre_if_bb); // the matrix is the identity, return the vector
phi->addIncoming(non_id_res, non_id_bb);
res = phi;
} else {
// either identity or zero in all other contexts
res = ctx->CreateSelect(cond, vector, llvm::Constant::getNullValue(ret_tp));
}
"""
self.format_code(f, code)
elif mode == "state::transform_normal":
code = """
llvm::Type *ret_tp = ctx.get_return_type();
llvm::Value *from = a;
llvm::Value *to = b;
llvm::Value *normal = c;
llvm::Value *internal = ctx.get_constant(LLVM_code_generator::coordinate_internal);
llvm::Value *encoding = ctx.get_constant(m_internal_space);
// map internal space
llvm::Value *f_cond = ctx->CreateICmpEQ(from, internal);
from = ctx->CreateSelect(f_cond, encoding, from);
llvm::Value *t_cond = ctx->CreateICmpEQ(to, internal);
to = ctx->CreateSelect(t_cond, encoding, to);
llvm::Value *cond = ctx->CreateICmpEQ(from, to);
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::BasicBlock *pre_if_bb = ctx->GetInsertBlock();
llvm::BasicBlock *non_id_bb = ctx.create_bb("non_id");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
llvm::Value *non_id_res;
ctx->CreateCondBr(cond, end_bb, non_id_bb);
{
// "from" and "to" are unequal
ctx->SetInsertPoint(non_id_bb);
llvm::Value *worldToObject = ctx.get_constant(LLVM_code_generator::coordinate_world);
llvm::Value *cond_is_w2o = ctx->CreateICmpEQ(from, worldToObject);
// for normals, we multiply by the transpose of the inverse matrix
llvm::Value *matrix = ctx->CreateSelect(
cond_is_w2o,
ctx.get_o2w_transform_value(),
ctx.get_w2o_transform_value());
if (inst.get_return_derivs()) {
non_id_res = ctx.create_deriv_mul_state_V3xM(
ret_tp, normal, matrix, /*ignore_translation=*/ true, /*transposed=*/ true);
} else {
non_id_res = ctx.create_mul_state_V3xM(
ret_tp, normal, matrix, /*ignore_translation=*/ true, /*transposed=*/ true);
}
ctx->CreateBr(end_bb);
}
ctx->SetInsertPoint(end_bb);
llvm::PHINode *phi = ctx->CreatePHI(ret_tp, 2);
phi->addIncoming(normal, pre_if_bb); // the matrix is the identity, return the normal
phi->addIncoming(non_id_res, non_id_bb);
res = phi;
} else {
// either identity or zero in all other contexts
res = ctx->CreateSelect(cond, normal, llvm::Constant::getNullValue(ret_tp));
}
"""
self.format_code(f, code)
elif mode == "state::transform_scale":
code = """
llvm::Type *ret_tp = ctx.get_return_type();
llvm::Value *from = a;
llvm::Value *to = b;
llvm::Value *scale = c;
llvm::Value *internal = ctx.get_constant(LLVM_code_generator::coordinate_internal);
llvm::Value *encoding = ctx.get_constant(m_internal_space);
// map internal space
llvm::Value *f_cond = ctx->CreateICmpEQ(from, internal);
from = ctx->CreateSelect(f_cond, encoding, from);
llvm::Value *t_cond = ctx->CreateICmpEQ(to, internal);
to = ctx->CreateSelect(t_cond, encoding, to);
llvm::Value *cond = ctx->CreateICmpEQ(from, to);
if (m_code_gen.m_state_mode & Type_mapper::SSM_CORE) {
llvm::BasicBlock *pre_if_bb = ctx->GetInsertBlock();
llvm::BasicBlock *non_id_bb = ctx.create_bb("non_id");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
llvm::Value *non_id_res;
ctx->CreateCondBr(cond, end_bb, non_id_bb);
{
// "from" and "to" are unequal
ctx->SetInsertPoint(non_id_bb);
llvm::Value *worldToObject = ctx.get_constant(LLVM_code_generator::coordinate_world);
llvm::Value *cond = ctx->CreateICmpEQ(from, worldToObject);
llvm::Value *matrix = ctx->CreateSelect(
cond, ctx.get_w2o_transform_value(), ctx.get_o2w_transform_value());
llvm::Value *m_ptr =
llvm::isa<llvm::PointerType>(matrix->getType()) ? matrix : NULL;
mi::mdl::IDefinition const *t_def = m_code_gen.find_stdlib_signature("::math", "length(float3)");
llvm::Function *t_fkt = get_intrinsic_function(t_def, /*return_derivs=*/ false);
llvm::Type *float3_tp = m_code_gen.get_type_mapper().get_float3_type();
llvm::Value *t_args[1];
static int const xyz[] = { 0, 1, 2 };
llvm::Value *shuffle = m_ptr != NULL ? NULL : ctx.get_shuffle(xyz);
// || transform_vector(float3(1,0,0), a, b) || == || transform[0] ||
if (m_ptr != NULL) {
llvm::Value *idx = ctx.get_constant(0);
llvm::Value *ptr = ctx->CreateInBoundsGEP(m_ptr, idx);
t_args[0] = ctx.load_and_convert(float3_tp, ptr);
} else {
llvm::Value *row = ctx.create_extract(matrix, 0);
t_args[0] = ctx->CreateShuffleVector(row, row, shuffle);
}
llvm::Value *v_x = call_rt_func(ctx, t_fkt, t_args);
// || transform_vector(float3(0,1,0), a, b) || == || transform[1] ||
if (m_ptr != NULL) {
llvm::Value *idx = ctx.get_constant(1);
llvm::Value *ptr = ctx->CreateInBoundsGEP(m_ptr, idx);
t_args[0] = ctx.load_and_convert(float3_tp, ptr);
} else {
llvm::Value *row = ctx.create_extract(matrix, 1);
t_args[0] = ctx->CreateShuffleVector(row, row, shuffle);
}
llvm::Value *v_y = call_rt_func(ctx, t_fkt, t_args);
// || transform_vector(float3(0,0,1), a, b) || == || transform[2] ||
if (m_ptr != NULL) {
llvm::Value *idx = ctx.get_constant(2);
llvm::Value *ptr = ctx->CreateInBoundsGEP(m_ptr, idx);
t_args[0] = ctx.load_and_convert(float3_tp, ptr);
} else {
llvm::Value *row = ctx.create_extract(matrix, 2);
t_args[0] = ctx->CreateShuffleVector(row, row, shuffle);
}
llvm::Value *v_z = call_rt_func(ctx, t_fkt, t_args);
// calc average
llvm::Value *factor = ctx->CreateFAdd(v_x, v_y);
factor = ctx->CreateFAdd(factor, v_z);
factor = ctx->CreateFMul(factor, ctx.get_constant((float)(1.0/3.0)));
non_id_res = ctx->CreateFMul(factor, ctx.get_dual_val(scale));
if (inst.get_return_derivs()) {
llvm::Value *dx = ctx->CreateFMul(factor, ctx.get_dual_dx(scale));
llvm::Value *dy = ctx->CreateFMul(factor, ctx.get_dual_dy(scale));
non_id_res = ctx.get_dual(non_id_res, dx, dy);
}
ctx->CreateBr(end_bb);
}
ctx->SetInsertPoint(end_bb);
llvm::PHINode *phi = ctx->CreatePHI(ret_tp, 2);
phi->addIncoming(scale, pre_if_bb); // the matrix is the identity, return the scale
phi->addIncoming(non_id_res, non_id_bb);
res = phi;
} else {
// either identity or zero in all other contexts
res = ctx->CreateSelect(cond, scale, llvm::Constant::getNullValue(ret_tp));
}
"""
self.format_code(f, code)
elif mode == "tex::attr_lookup" \
or mode == "tex::attr_lookup_uvtile" \
or mode == "tex::attr_lookup_uvtile_frame" \
or mode == "tex::attr_lookup_frame":
texture_param = params[0]
tex_dim = "3d" if texture_param == "T3" else "2d"
code = ""
# texture attribute
code_params = { "intrinsic": intrinsic }
if intrinsic == "width":
code_params["name"] = "WIDTH"
code_params["handler_name"] = "tex_resolution_" + tex_dim
elif intrinsic == "height":
code_params["name"] = "HEIGHT"
code_params["handler_name"] = "tex_resolution_" + tex_dim
elif intrinsic == "depth":
code_params["name"] = "DEPTH"
code_params["handler_name"] = "tex_resolution_3d"
elif intrinsic == "texture_isvalid":
code_params["name"] = "ISVALID"
code_params["handler_name"] = "tex_texture_isvalid"
if mode == "tex::attr_lookup":
code_params["get_uv_tile"] = "ctx.store_int2_zero(uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = ctx.get_constant(0.0f);"
elif mode == "tex::attr_lookup_uvtile":
code_params["get_uv_tile"] = "ctx.convert_and_store(b, uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = ctx.get_constant(0.0f);"
elif mode == "tex::attr_lookup_uvtile_frame":
code_params["get_uv_tile"] = "ctx.convert_and_store(b, uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = c;"
elif mode == "tex::attr_lookup_frame":
code_params["get_frame"] = "llvm::Value *frame = b;"
else:
assert(False)
# check for udim special cases
if texture_param == "T2" and intrinsic in ["width", "height"]:
# special handling for texture_2d width() and height(), because these have
# uv_tile extra parameter, use the resource handler or resolution function
# (i.e. no resource table)
if intrinsic == "width":
code_params["res_proj"] = "0"
code_params["comment_name"] = "width"
else:
code_params["res_proj"] = "1"
code_params["comment_name"] = "height"
code += """
if (m_has_res_handler) {
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *uv_tile = ctx.create_local(coord_type, "uv_tile");
%(get_frame)s
%(get_uv_tile)s
llvm::Function *glue_func = get_runtime_func(RT_MDL_TEX_RESOLUTION_2D);
ctx->CreateCall(glue_func, { tmp, res_data, a, uv_tile, frame });
// return the %(comment_name)s component of the resolution
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { %(res_proj)s };
res = ctx->CreateExtractValue(arr, idxs);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee resolution_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_resolution_2d);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *uv_tile = ctx.create_local(coord_type, "uv_tile");
%(get_frame)s
%(get_uv_tile)s
llvm::Value *args[] = { tmp, self, a, uv_tile, frame };
llvm::CallInst *call = ctx->CreateCall(resolution_func, args);
call->setDoesNotThrow();
// return the %(comment_name)s component of the resolution
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { %(res_proj)s };
res = ctx->CreateExtractValue(arr, idxs);
}
""" % code_params
elif mode == "tex::attr_lookup_frame":
# use resource handler
code += """
llvm::Type *res_type = ctx.get_non_deriv_return_type();
%(get_frame)s
res = call_tex_attr_func(
ctx,
RT_MDL_TEX_%(name)s,
Type_mapper::THV_%(handler_name)s,
res_data,
a,
nullptr,
frame,
res_type);
""" % code_params
elif mode == "tex::attr_lookup":
# FIXME: When is the lookup table supposed to be used? Right now it is *not* used for 2d
# width()/height() without uvtile/frame parameter, but it *is* used for 3d
# width()/height()/depth() without frame parameter.
# use resource handler or lookup table
code += """
llvm::Type *res_type = ctx.get_non_deriv_return_type();
llvm::Value *lut = m_code_gen.get_attribute_table(
ctx, LLVM_code_generator::RTK_TEXTURE);
llvm::Value *lut_size = m_code_gen.get_attribute_table_size(
ctx, LLVM_code_generator::RTK_TEXTURE);
if (lut != NULL) {
// have a lookup table
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *cond = ctx->CreateICmpULT(a, lut_size);
llvm::BasicBlock *lut_bb = ctx.create_bb("lut_bb");
llvm::BasicBlock *bad_bb = ctx.create_bb("bad_bb");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
// we do not expect out of bounds here
ctx.CreateWeightedCondBr(cond, lut_bb, bad_bb, 1, 0);
{
ctx->SetInsertPoint(lut_bb);
llvm::Value *select[] = {
a,
ctx.get_constant(int(Type_mapper::TAE_%(name)s))
};
llvm::Value *adr = ctx->CreateInBoundsGEP(lut, select);
llvm::Value *v = ctx->CreateLoad(adr);
ctx->CreateStore(v, tmp);
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(bad_bb);
llvm::Value *val = call_tex_attr_func(
ctx,
RT_MDL_TEX_%(name)s,
Type_mapper::THV_%(handler_name)s,
res_data,
a,
nullptr,
nullptr,
res_type);
ctx->CreateStore(val, tmp);
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(end_bb);
res = ctx->CreateLoad(tmp);
}
} else {
// no lookup table, call resource handler
res = call_tex_attr_func(
ctx,
RT_MDL_TEX_%(name)s,
Type_mapper::THV_%(handler_name)s,
res_data,
a,
nullptr,
nullptr,
res_type);
}
""" % code_params
else:
assert(False)
self.format_code(f, code)
self.format_code(f, """
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""")
elif mode == "tex::frame":
code = ""
code_params = { "intrinsic": intrinsic }
if intrinsic == "first_frame":
code_params["res_proj"] = "0"
code_params["comment_name"] = "first"
else:
code_params["res_proj"] = "1"
code_params["comment_name"] = "second"
code += """
if (m_has_res_handler) {
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Function *glue_func = get_runtime_func(RT_MDL_TEX_FRAME);
ctx->CreateCall(glue_func, { tmp, res_data, a });
// return the %(comment_name)s component of the frame numbers
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { %(res_proj)s };
res = ctx->CreateExtractValue(arr, idxs);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee resolution_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_frame);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *args[] = { tmp, self, a };
llvm::CallInst *call = ctx->CreateCall(resolution_func, args);
call->setDoesNotThrow();
// return the %(comment_name)s component of the frame numbers
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { %(res_proj)s };
res = ctx->CreateExtractValue(arr, idxs);
}
""" % code_params
self.format_code(f, code)
self.format_code(f, """
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""")
elif mode == "tex::lookup_float":
# texture lookup for texture
texture_param = params[0]
code = "";
if texture_param == "T2" and len(params) < 7:
code += """
llvm::Value *g = ctx.get_constant(0.0f);
""";
if texture_param == "T3" and len(params) < 9:
code += """
llvm::Value *i = ctx.get_constant(0.0f);
""";
if texture_param == "T2":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func;
llvm::Type *coord_type;
if (m_code_gen.is_texruntime_with_derivs()) {
lookup_func = get_runtime_func(RT_MDL_TEX_LOOKUP_DERIV_FLOAT_2D);
coord_type = m_code_gen.m_type_mapper.get_deriv_arr_float_2_type();
} else {
lookup_func = get_runtime_func(RT_MDL_TEX_LOOKUP_FLOAT_2D);
coord_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
}
llvm::Type *f2_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(f2_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(f2_type, "crop_v");
ctx.convert_and_store(e, crop_u);
ctx.convert_and_store(f, crop_v);
llvm::Value *args[] = { res_data, a, coord, c, d, crop_u, crop_v, g };
res = ctx->CreateCall(lookup_func, args);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee lookup_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_lookup_float3_2d);
llvm::Type *coord_type;
if (m_code_gen.is_texruntime_with_derivs()) {
coord_type = m_code_gen.m_type_mapper.get_deriv_arr_float_2_type();
} else {
coord_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
}
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Type *crop_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(crop_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(crop_type, "crop_v");
ctx.convert_and_store(e, crop_u);
ctx.convert_and_store(f, crop_v);
llvm::Value *args[] = { tmp, self, a, coord, c, d, crop_u, crop_v, g };
llvm::CallInst *call = ctx->CreateCall(lookup_func, args);
call->setDoesNotThrow();
// return the first component of the float3 array
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { 0 };
res = ctx->CreateExtractValue(arr, idxs);
}
"""
elif texture_param == "T3":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_LOOKUP_FLOAT_3D);
llvm::Type *f2_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Type *f3_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(f3_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(f2_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(f2_type, "crop_v");
llvm::Value *crop_w = ctx.create_local(f2_type, "crop_w");
ctx.convert_and_store(f, crop_u);
ctx.convert_and_store(g, crop_v);
ctx.convert_and_store(h, crop_w);
llvm::Value *args[] = { res_data, a, coord, c, d, e, crop_u, crop_v, crop_w, i };
res = ctx->CreateCall(lookup_func, args);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee lookup_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_lookup_float3_3d);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Type *crop_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(crop_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(crop_type, "crop_v");
llvm::Value *crop_w = ctx.create_local(crop_type, "crop_w");
ctx.convert_and_store(f, crop_u);
ctx.convert_and_store(g, crop_v);
ctx.convert_and_store(h, crop_w);
llvm::Value *args[] = { tmp, self, a, coord, c, d, e, crop_u, crop_v, crop_w, i };
llvm::CallInst *call = ctx->CreateCall(lookup_func, args);
call->setDoesNotThrow();
// return the first component of the float3 array
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { 0 };
res = ctx->CreateExtractValue(arr, idxs);
}
"""
elif texture_param == "TC":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_LOOKUP_FLOAT_CUBE);
llvm::Type *f3_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(f3_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *args[] = { res_data, a, coord };
res = ctx->CreateCall(lookup_func, args);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee lookup_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_lookup_float3_cube);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *args[] = { tmp, self, a, coord };
llvm::CallInst *call = ctx->CreateCall(lookup_func, args);
call->setDoesNotThrow();
// return the first component of the float3 array
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { 0 };
res = ctx->CreateExtractValue(arr, idxs);
}
"""
elif texture_param == "TP":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_LOOKUP_FLOAT_PTEX);
llvm::Value *args[] = { res_data, a, b };
res = ctx->CreateCall(lookup_func, args);
} else {
res = llvm::Constant::getNullValue(ctx.get_non_deriv_return_type());
}
"""
else:
error("Unsupported texture type")
code = ""
self.format_code(f, code)
self.format_code(f, """
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""")
elif mode == "tex::lookup_floatX":
# texture lookup_floatX()
code_params = {"core_th" : "false", "vt_size" : "0" }
if intrinsic == "lookup_float2":
code_params["size"] = "2"
code_params["func"] = "LOOKUP_FLOAT2"
code_params["deriv_func"] = "LOOKUP_DERIV_FLOAT2"
code_params["vt_size"] = "3"
elif intrinsic == "lookup_float3":
code_params["size"] = "3"
code_params["func"] = "LOOKUP_FLOAT3"
code_params["deriv_func"] = "LOOKUP_DERIV_FLOAT3"
code_params["vt_size"] = "3"
elif intrinsic == "lookup_float4":
code_params["size"] = "4"
code_params["func"] = "LOOKUP_FLOAT4"
code_params["deriv_func"] = "LOOKUP_DERIV_FLOAT4"
code_params["vt_size"] = "4"
elif intrinsic == "lookup_color":
code_params["size"] = "3"
code_params["func"] = "LOOKUP_COLOR"
code_params["deriv_func"] = "LOOKUP_DERIV_COLOR"
code_params["vt_size"] = "3"
else:
error("Unsupported tex lookup function '%s'" % intrinsic)
texture_param = params[0]
code = "";
if texture_param == "T2" and len(params) < 7:
code += """
llvm::Value *g = ctx.get_constant(0.0f);
""";
if texture_param == "T3" and len(params) < 9:
code += """
llvm::Value *i = ctx.get_constant(0.0f);
""";
if texture_param == "T2":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func;
llvm::Type *coord_type;
if (m_code_gen.is_texruntime_with_derivs()) {
lookup_func = get_runtime_func(RT_MDL_TEX_%(deriv_func)s_2D);
coord_type = m_code_gen.m_type_mapper.get_deriv_arr_float_2_type();
} else {
lookup_func = get_runtime_func(RT_MDL_TEX_%(func)s_2D);
coord_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
}
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(size)s_type();
llvm::Type *crop_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(crop_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(crop_type, "crop_v");
ctx.convert_and_store(e, crop_u);
ctx.convert_and_store(f, crop_v);
llvm::Value *args[] = { tmp, res_data, a, coord, c, d, crop_u, crop_v, g };
ctx->CreateCall(lookup_func, args);
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee lookup_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_lookup_float%(vt_size)s_2d);
llvm::Type *coord_type;
if (m_code_gen.is_texruntime_with_derivs()) {
coord_type = m_code_gen.m_type_mapper.get_deriv_arr_float_2_type();
} else {
coord_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
}
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(vt_size)s_type();
llvm::Type *crop_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(crop_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(crop_type, "crop_v");
ctx.convert_and_store(e, crop_u);
ctx.convert_and_store(f, crop_v);
llvm::Value *args[] = { tmp, self, a, coord, c, d, crop_u, crop_v, g };
llvm::CallInst *call = ctx->CreateCall(lookup_func, args);
call->setDoesNotThrow();
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
}
"""
elif texture_param == "T3":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_%(func)s_3D);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(size)s_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Type *crop_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(crop_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(crop_type, "crop_v");
llvm::Value *crop_w = ctx.create_local(crop_type, "crop_w");
ctx.convert_and_store(f, crop_u);
ctx.convert_and_store(g, crop_v);
ctx.convert_and_store(h, crop_w);
llvm::Value *args[] = { tmp, res_data, a, coord, c, d, e, crop_u, crop_v, crop_w, i };
ctx->CreateCall(lookup_func, args);
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee lookup_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_lookup_float%(vt_size)s_3d);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(vt_size)s_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Type *crop_type = m_code_gen.m_type_mapper.get_arr_float_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *crop_u = ctx.create_local(crop_type, "crop_u");
llvm::Value *crop_v = ctx.create_local(crop_type, "crop_v");
llvm::Value *crop_w = ctx.create_local(crop_type, "crop_w");
ctx.convert_and_store(f, crop_u);
ctx.convert_and_store(g, crop_v);
ctx.convert_and_store(h, crop_w);
llvm::Value *args[] = { tmp, self, a, coord, c, d, e, crop_u, crop_v, crop_w, i };
llvm::CallInst *call = ctx->CreateCall(lookup_func, args);
call->setDoesNotThrow();
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
}
"""
elif texture_param == "TC":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_%(func)s_CUBE);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(size)s_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *args[] = { tmp, res_data, a, coord };
ctx->CreateCall(lookup_func, args);
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee lookup_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_lookup_float%(vt_size)s_cube);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(vt_size)s_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_float_3_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord;
if (m_code_gen.m_type_mapper.target_supports_pointers()) {
coord = ctx.create_local(coord_type, "coord");
ctx.convert_and_store(b, coord);
} else {
coord = b;
}
llvm::Value *args[] = { tmp, self, a, coord };
llvm::CallInst *call = ctx->CreateCall(lookup_func, args);
call->setDoesNotThrow();
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
}
"""
elif texture_param == "TP":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_%(func)s_PTEX);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(size)s_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *args[] = { tmp, res_data, a, b };
ctx->CreateCall(lookup_func, args);
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
} else {
res = llvm::Constant::getNullValue(ctx.get_non_deriv_return_type());
}
"""
else:
error("Unsupported texture type")
code = ""
self.format_code(f, code % code_params)
self.format_code(f, """
if (inst.get_return_derivs()){ // expand to dual
res = ctx.get_dual(res);
}
""")
elif mode == "tex::texel_float" \
or mode == "tex::texel_float_uvtile" \
or mode == "tex::texel_float_uvtile_frame" \
or mode == "tex::texel_float_frame":
# texture texel_float()
texture_param = params[0]
code_params = {}
code = ""
if mode == "tex::texel_float":
code_params["get_uv_tile"] = "ctx.store_int2_zero(uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = ctx.get_constant(0.0f);"
elif mode == "tex::texel_float_uvtile":
code_params["get_uv_tile"] = "ctx.convert_and_store(c, uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = ctx.get_constant(0.0f);"
elif mode == "tex::texel_float_uvtile_frame":
code_params["get_uv_tile"] = "ctx.convert_and_store(c, uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = d;"
elif mode == "tex::texel_float_frame":
code_params["get_uv_tile"] = "ctx.store_int2_zero(uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = c;"
else:
assert(False)
if texture_param == "T2":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_TEXEL_FLOAT_2D);
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *coord = ctx.create_local(coord_type, "coord");
llvm::Value *uv_tile = ctx.create_local(coord_type, "uv_tile");
%(get_frame)s
ctx.convert_and_store(b, coord);
%(get_uv_tile)s
llvm::Value *args[] = { res_data, a, coord, uv_tile, frame };
res = ctx->CreateCall(lookup_func, args);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee texel_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_texel_float4_2d);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_4_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord = ctx.create_local(coord_type, "coord");
llvm::Value *uv_tile = ctx.create_local(coord_type, "uv_tile");
%(get_frame)s
ctx.convert_and_store(b, coord);
%(get_uv_tile)s
llvm::Value *args[] = { tmp, self, a, coord, uv_tile, frame };
llvm::CallInst *call = ctx->CreateCall(texel_func, args);
call->setDoesNotThrow();
// return the first component of the float4 array
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { 0 };
res = ctx->CreateExtractValue(arr, idxs);
}
"""
elif texture_param == "T3":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_TEXEL_FLOAT_3D);
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_3_type();
llvm::Value *coord = ctx.create_local(coord_type, "coord");
%(get_frame)s
ctx.convert_and_store(b, coord);
llvm::Value *args[] = { res_data, a, coord, frame };
res = ctx->CreateCall(lookup_func, args);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee texel_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_texel_float4_3d);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_4_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_3_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord = ctx.create_local(coord_type, "coord");
%(get_frame)s
ctx.convert_and_store(b, coord);
llvm::Value *args[] = { tmp, self, a, coord, frame };
llvm::CallInst *call = ctx->CreateCall(texel_func, args);
call->setDoesNotThrow();
// return the first component of the float4 array
llvm::Value *arr = ctx->CreateLoad(tmp);
unsigned idxs[] = { 0 };
res = ctx->CreateExtractValue(arr, idxs);
}
"""
else:
error("Unsupported texture type")
return
self.format_code(f, code % code_params)
self.format_code(f, """
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""")
elif mode == "tex::texel_floatX" \
or mode == "tex::texel_floatX_uvtile" \
or mode == "tex::texel_floatX_uvtile_frame" \
or mode == "tex::texel_floatX_frame":
# texture texel_floatX()
texture_param = params[0]
code_params = {}
code = ""
if intrinsic == "texel_float2":
code_params["size"] = "2"
code_params["func"] = "TEXEL_FLOAT2"
elif intrinsic == "texel_float3":
code_params["size"] = "3"
code_params["func"] = "TEXEL_FLOAT3"
elif intrinsic == "texel_float4":
code_params["size"] = "4"
code_params["func"] = "TEXEL_FLOAT4"
elif intrinsic == "texel_color":
code_params["size"] = "3"
code_params["func"] = "TEXEL_COLOR"
else:
error("Unsupported tex texel function '%s'" % intrinsic)
if mode == "tex::texel_floatX":
code_params["get_uv_tile"] = "ctx.store_int2_zero(uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = ctx.get_constant(0.0f);"
elif mode == "tex::texel_floatX_uvtile":
code_params["get_uv_tile"] = "ctx.convert_and_store(c, uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = ctx.get_constant(0.0f);"
elif mode == "tex::texel_floatX_uvtile_frame":
code_params["get_uv_tile"] = "ctx.convert_and_store(c, uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = d;"
elif mode == "tex::texel_floatX_frame":
code_params["get_uv_tile"] = "ctx.store_int2_zero(uv_tile);"
code_params["get_frame"] = "llvm::Value *frame = c;"
else:
assert(False)
if texture_param == "T2":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_%(func)s_2D);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(size)s_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord = ctx.create_local(coord_type, "coord");
llvm::Value *uv_tile = ctx.create_local(coord_type, "uv_tile");
%(get_frame)s
ctx.convert_and_store(b, coord);
%(get_uv_tile)s
llvm::Value *args[] = { tmp, res_data, a, coord, uv_tile, frame };
ctx->CreateCall(lookup_func, args);
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee texel_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_texel_float4_2d);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_4_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_2_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord = ctx.create_local(coord_type, "coord");
llvm::Value *uv_tile = ctx.create_local(coord_type, "uv_tile");
%(get_frame)s
ctx.convert_and_store(b, coord);
%(get_uv_tile)s
llvm::Value *args[] = { tmp, self, a, coord, uv_tile, frame };
llvm::CallInst *call = ctx->CreateCall(texel_func, args);
call->setDoesNotThrow();
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
}
"""
elif texture_param == "T3":
code += """
if (m_has_res_handler) {
llvm::Function *lookup_func = get_runtime_func(RT_MDL_TEX_%(func)s_3D);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_%(size)s_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_3_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord = ctx.create_local(coord_type, "coord");
%(get_frame)s
ctx.convert_and_store(b, coord);
llvm::Value *args[] = { tmp, res_data, a, coord, frame };
ctx->CreateCall(lookup_func, args);
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee texel_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_tex_texel_float4_3d);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_4_type();
llvm::Type *coord_type = m_code_gen.m_type_mapper.get_arr_int_3_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *coord = ctx.create_local(coord_type, "coord");
%(get_frame)s
ctx.convert_and_store(b, coord);
llvm::Value *args[] = { tmp, self, a, coord, frame };
llvm::CallInst *call = ctx->CreateCall(texel_func, args);
call->setDoesNotThrow();
res = ctx.load_and_convert(ctx.get_non_deriv_return_type(), tmp);
}
"""
else:
error("Unsupported texture type")
return
self.format_code(f, code % code_params)
self.format_code(f, """
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""")
elif mode == "tex::zero_return":
# suppress unused variable warnings
idx = 0
for param in params:
self.write(f, "(void)%s;\n" % chr(ord('a') + idx))
self.write(f, "(void)res_data;\n")
idx += 1
self.write(f, "res = llvm::Constant::getNullValue(ctx_data->get_return_type());\n")
elif mode == "scene::data_isvalid":
code = """
if (m_has_res_handler) {
MDL_ASSERT(!"not implemented yet");
res = nullptr;
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::THV_scene_data_isvalid);
llvm::Value *args[] = { self, ctx.get_state_parameter(), a };
llvm::CallInst *call = ctx->CreateCall(runtime_func, args);
call->setDoesNotThrow();
res = call;
}
"""
self.format_code(f, code)
elif mode == "scene::data_lookup_atomic" or mode == "scene::data_lookup_uniform_atomic":
runtime_func_enum_name = "THV_scene_" + intrinsic.replace("uniform_", "")
runtime_func_enum_deriv_name = runtime_func_enum_name.replace("lookup", "lookup_deriv")
if "_int" in intrinsic:
code = """
if (m_has_res_handler) {
MDL_ASSERT(!"not implemented yet");
res = nullptr;
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::%(runtime_func_enum_name)s);
llvm::Value *args[] = {
self, ctx.get_state_parameter(), a, b, ctx.get_constant(%(is_uniform)s) };
llvm::CallInst *call = ctx->CreateCall(runtime_func, args);
call->setDoesNotThrow();
res = call;
}
""" % {
"runtime_func_enum_name": runtime_func_enum_name,
"is_uniform": "true" if "uniform" in intrinsic else "false"
}
else:
code = """
if (m_has_res_handler) {
MDL_ASSERT(!"not implemented yet");
res = nullptr;
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
if (inst.get_return_derivs()) {
llvm::FunctionCallee runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::%(runtime_func_enum_deriv_name)s);
llvm::Value *tmp = ctx.create_local(ctx.get_return_type(), "tmp");
llvm::Value *def_value = ctx.create_local(ctx.get_return_type(), "def_value");
ctx.convert_and_store(b, def_value);
llvm::Value *args[] = {
tmp, self, ctx.get_state_parameter(), a, def_value, ctx.get_constant(%(is_uniform)s) };
llvm::CallInst *call = ctx->CreateCall(runtime_func, args);
call->setDoesNotThrow();
res = ctx->CreateLoad(tmp);
} else {
llvm::FunctionCallee runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::%(runtime_func_enum_name)s);
llvm::Value *args[] = {
self, ctx.get_state_parameter(), a, b, ctx.get_constant(%(is_uniform)s) };
llvm::CallInst *call = ctx->CreateCall(runtime_func, args);
call->setDoesNotThrow();
res = call;
}
}
""" % {
"runtime_func_enum_name": runtime_func_enum_name,
"runtime_func_enum_deriv_name": runtime_func_enum_deriv_name,
"elem_type": "float",
"is_uniform": "true" if "uniform" in intrinsic else "false"
}
self.format_code(f, code)
elif mode == "scene::data_lookup_vector" or mode == "scene::data_lookup_uniform_vector":
runtime_func_enum_name = "THV_scene_" + intrinsic.replace("uniform_", "")
runtime_func_enum_deriv_name = runtime_func_enum_name.replace("lookup", "lookup_deriv")
if "_float4x4" in intrinsic:
code = """
if (m_has_res_handler) {
MDL_ASSERT(!"not implemented yet");
res = nullptr;
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::%(runtime_func_enum_name)s);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_float_16_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *def_value = ctx.create_local(res_type, "def_value");
// convert default value b to float[16]
ctx.convert_and_store(b, def_value);
// call runtime function
llvm::Value *args[] = {
tmp, self, ctx.get_state_parameter(), a, def_value, ctx.get_constant(%(is_uniform)s) };
llvm::CallInst *call = ctx->CreateCall(runtime_func, args);
call->setDoesNotThrow();
// convert result from float[16] to matrix type
res = ctx.load_and_convert(ctx.get_return_type(), tmp);
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""" % {
"runtime_func_enum_name": runtime_func_enum_name,
"is_uniform": "true" if "uniform" in intrinsic else "false"
}
elif "_int" in intrinsic:
code = """
if (m_has_res_handler) {
MDL_ASSERT(!"not implemented yet");
res = nullptr;
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::%(runtime_func_enum_name)s);
llvm::Type *res_type = m_code_gen.m_type_mapper.get_arr_%(elem_type)s_%(vector_dim)s_type();
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *def_value = ctx.create_local(res_type, "def_value");
ctx.convert_and_store(b, def_value);
llvm::Value *args[] = {
tmp, self, ctx.get_state_parameter(), a, def_value, ctx.get_constant(%(is_uniform)s) };
llvm::CallInst *call = ctx->CreateCall(runtime_func, args);
call->setDoesNotThrow();
res = ctx.load_and_convert(ctx.get_return_type(), tmp);
}
""" % {
"runtime_func_enum_name": runtime_func_enum_name,
"vector_dim": "3" if "color" in intrinsic else intrinsic[-1], # last character of name is dim if not color
"elem_type": "int",
"is_uniform": "true" if "uniform" in intrinsic else "false"
}
else:
code = """
if (m_has_res_handler) {
MDL_ASSERT(!"not implemented yet");
res = nullptr;
} else {
llvm::Value *self_adr = ctx.create_simple_gep_in_bounds(
res_data, ctx.get_constant(Type_mapper::RDP_THREAD_DATA));
llvm::Value *self = ctx->CreateBitCast(
ctx->CreateLoad(self_adr),
m_code_gen.m_type_mapper.get_core_tex_handler_ptr_type());
llvm::FunctionCallee runtime_func;
llvm::Type *res_type;
if (inst.get_return_derivs()) {
runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::%(runtime_func_enum_deriv_name)s);
res_type = m_code_gen.m_type_mapper.get_deriv_arr_%(elem_type)s_%(vector_dim)s_type();
} else {
runtime_func = ctx.get_tex_lookup_func(
self, Type_mapper::%(runtime_func_enum_name)s);
res_type = m_code_gen.m_type_mapper.get_arr_%(elem_type)s_%(vector_dim)s_type();
}
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *def_value = ctx.create_local(res_type, "def_value");
ctx.convert_and_store(b, def_value);
llvm::Value *args[] = {
tmp, self, ctx.get_state_parameter(), a, def_value, ctx.get_constant(%(is_uniform)s) };
llvm::CallInst *call = ctx->CreateCall(runtime_func, args);
call->setDoesNotThrow();
res = ctx.load_and_convert(ctx.get_return_type(), tmp);
}
""" % {
"runtime_func_enum_name": runtime_func_enum_name,
"runtime_func_enum_deriv_name": runtime_func_enum_deriv_name,
"vector_dim": "3" if "color" in intrinsic else intrinsic[-1], # last character of name is dim if not color
"elem_type": "float",
"is_uniform": "true" if "uniform" in intrinsic else "false"
}
self.format_code(f, code)
elif mode == "debug::breakpoint":
code = """
if (m_target_lang == ICode_generator::TL_NATIVE) {
llvm::Function *break_func = get_runtime_func(RT_MDL_DEBUGBREAK);
ctx->CreateCall(break_func);
} else if (m_target_lang == ICode_generator::TL_PTX) {
llvm::FunctionType *f_tp = llvm::FunctionType::get(
m_code_gen.m_type_mapper.get_void_type(), /*is_VarArg=*/false);
llvm::InlineAsm *ia = llvm::InlineAsm::get(
f_tp,
"brkpt;",
"",
/*hasSideEffects=*/false);
ctx->CreateCall(ia);
}
res = ctx.get_constant(true);
"""
self.format_code(f, code)
elif mode == "debug::assert":
code = """
if (!m_code_gen.target_is_structured_language(m_target_lang)) {
llvm::Function *conv_func = get_runtime_func(RT_MDL_TO_CSTRING);
llvm::Value *cond = ctx->CreateICmpNE(a, ctx.get_constant(false));
llvm::BasicBlock *fail_bb = ctx.create_bb("fail_bb");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
// we do not expect the assertion to fail here
ctx.CreateWeightedCondBr(cond, end_bb, fail_bb, 1, 0);
{
ctx->SetInsertPoint(fail_bb);
// convert the string arguments to cstrings
b = ctx->CreateCall(conv_func, b); // message
c = ctx->CreateCall(conv_func, c); // function name
d = ctx->CreateCall(conv_func, d); // file
if (m_target_lang == ICode_generator::TL_NATIVE) {
llvm::Value *args[] = {
b, // message
c, // function name
d, // file
e // line
};
llvm::Function *assert_func = get_runtime_func(RT_MDL_ASSERTFAIL);
ctx->CreateCall(assert_func, args);
} else if (m_target_lang == ICode_generator::TL_PTX) {
llvm::Value *args[] = {
b, // message
d, // file
e, // line
c, // function name
ctx.get_constant(size_t(1)) // charSize
};
llvm::Function *assert_func = get_runtime_func(RT___ASSERTFAIL);
ctx->CreateCall(assert_func, args);
}
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(end_bb);
}
}
res = ctx.get_constant(true);
"""
self.format_code(f, code)
elif mode == "debug::print":
# conversion from id to C-string
conv_from_string_id = """
llvm::Function *conv_func = get_runtime_func(RT_MDL_TO_CSTRING);
%(what)s = ctx->CreateCall(conv_func, %(what)s);
"""
# PTX prolog
code = """
if (m_target_lang == ICode_generator::TL_PTX) {
llvm::Function *vprintf_func = get_runtime_func(RT_VPRINTF);
llvm::PointerType *void_ptr_tp = m_code_gen.m_type_mapper.get_void_ptr_type();
llvm::DataLayout data_layout(m_code_gen.get_llvm_module());
llvm::Twine format_str;
int buffer_size = 0;
llvm::Type *operand_type;
"""
self.format_code(f, code)
# Determine buffer size for valist, argument types and format string
arg_types = []
format_str = ""
for param in params:
atomic_chk = self.get_atomic_type_kind(param)
vector_chk = self.get_vector_type_and_size(param)
if param == "CC": # color
format_str += "(%s)" % ', '.join(["%f"] * vector_chk[1])
arg_type = "m_code_gen.m_type_mapper.get_double_type()"
elif atomic_chk:
if param == "BB":
format_str += "%s"
arg_type = "m_code_gen.m_type_mapper.get_cstring_type()"
elif param == "II":
format_str += "%i"
arg_type = "m_code_gen.m_type_mapper.get_int_type()"
elif param == "FF":
format_str += "%f"
arg_type = "m_code_gen.m_type_mapper.get_double_type()"
elif param == "DD":
format_str += "%f"
arg_type = "m_code_gen.m_type_mapper.get_double_type()"
elif param == "SS":
format_str += "%s"
arg_type = "m_code_gen.m_type_mapper.get_cstring_type()"
else:
error("Unsupported print type '%s'" % param)
code = """
get_next_valist_entry_offset(buffer_size, %s);
""" % arg_type
self.format_code(f, code)
elif vector_chk:
size = vector_chk[1]
if vector_chk[0] == "bool":
elem_format = "%s"
arg_type = "m_code_gen.m_type_mapper.get_cstring_type()"
elif vector_chk[0] == "int":
elem_format = "%i"
arg_type = "m_code_gen.m_type_mapper.get_int_type()"
elif vector_chk[0] == "float":
elem_format = "%f"
arg_type = "m_code_gen.m_type_mapper.get_double_type()"
elif vector_chk[0] == "double":
elem_format = "%f"
arg_type = "m_code_gen.m_type_mapper.get_double_type()"
else:
error("Unsupported print type '%s'" % param)
format_str += "<%s>" % ', '.join([elem_format] * vector_chk[1])
code = """
operand_type = %(arg_type)s;
for (unsigned i = 0; i < %(size)d; ++i) {
get_next_valist_entry_offset(buffer_size, operand_type);
}
""" % { "arg_type" : arg_type, "size" : size }
self.format_code(f, code)
else:
error("Unsupported debug::print() parameter type '%s'" % param)
arg_types.append((arg_type, vector_chk[1] if vector_chk else 1))
# Allocate valist buffer
code = """
buffer_size = int(llvm::alignTo(buffer_size, VPRINTF_BUFFER_ROUND_UP));
llvm::AllocaInst *valist = ctx.create_local(
llvm::ArrayType::get(
m_code_gen.m_type_mapper.get_char_type(),
buffer_size
),
"vprintf.valist");
valist->setAlignment(llvm::Align(VPRINTF_BUFFER_ALIGNMENT));
int offset = 0;
llvm::Value *elem;
llvm::Value *pointer;
"""
self.format_code(f, code)
# Fill valist buffer
idx = 0
for param in params:
self.format_code(f, "operand_type = %s;" % arg_types[idx][0])
# For color and float types, we need to cast the value to double
if param[0] in ['C', 'F']:
optcast = """
elem = ctx->CreateFPExt(elem,
m_code_gen.m_type_mapper.get_double_type());
"""
# For bool types we need to convert it to "true" or "false"
elif param[0] == 'B':
optcast = """
elem = ctx->CreateICmpNE(elem, ctx.get_constant(false));
elem = ctx->CreateSelect(
elem, ctx.get_constant("true"), ctx.get_constant("false"));
"""
elif param == 'SS':
optcast = conv_from_string_id % { "what" : "elem" }
else:
optcast = ""
size = arg_types[idx][1]
if size > 1:
code = """
if (llvm::isa<llvm::ArrayType>(%(param)s->getType())) {
unsigned idxes[1];
for (unsigned i = 0; i < %(size)d; ++i) {
idxes[0] = i;
elem = ctx->CreateExtractValue(%(param)s, idxes);
%(optcast)s
pointer = get_next_valist_pointer(ctx, valist,
offset, operand_type);
ctx->CreateStore(elem, pointer);
}
} else {
for (int i = 0; i < %(size)d; ++i) {
llvm::Value *idx = ctx.get_constant(i);
elem = ctx->CreateExtractElement(%(param)s, idx);
%(optcast)s
pointer = get_next_valist_pointer(ctx, valist,
offset, operand_type);
ctx->CreateStore(elem, pointer);
}
}
""" % { "size" : size, "param" : chr(ord('a') + idx), "optcast" : optcast }
else:
code = """
elem = %(param)s;
%(optcast)s
pointer = get_next_valist_pointer(ctx, valist, offset, operand_type);
ctx->CreateStore(elem, pointer);
""" % { "param" : chr(ord('a') + idx), "optcast" : optcast }
self.format_code(f, code)
idx = idx + 1
# PTX epilog and CPU prolog
code = """
llvm::Value *args[] = {
ctx.get_constant("%s"),
ctx->CreateBitCast(valist, void_ptr_tp)
};
ctx->CreateCall(vprintf_func, args);
} else if (m_target_lang == ICode_generator::TL_NATIVE) {
llvm::Function *begin_func = get_runtime_func(RT_MDL_PRINT_BEGIN);
llvm::Value *buf = ctx->CreateCall(begin_func);
""" % format_str
self.format_code(f, code)
idx = 0
for param in params:
type = ""
size = 0
atomic_chk = self.get_atomic_type_kind(param)
vector_chk = self.get_vector_type_and_size(param)
if param == "CC":
# color
code = """
{
llvm::Function *print_func = get_runtime_func(RT_MDL_PRINT_FLOAT);
llvm::Function *prints_func = get_runtime_func(RT_MDL_PRINT_STRING);
llvm::Type *arg_tp = %(param)s->getType();
llvm::Value *comma = ctx.get_constant("(");
llvm::Value *next = ctx.get_constant(", ");
if (llvm::isa<llvm::ArrayType>(arg_tp)) {
unsigned idxes[1];
for (unsigned i = 0; i < 3; ++i) {
ctx->CreateCall(prints_func, { buf, comma });
comma = next;
idxes[0] = i;
llvm::Value *elem = ctx->CreateExtractValue(%(param)s, idxes);
ctx->CreateCall(print_func, { buf, elem });
}
} else {
for (int i = 0; i < 3; ++i) {
ctx->CreateCall(prints_func, { buf, comma });
comma = next;
llvm::Value *idx = ctx.get_constant(i);
llvm::Value *elem = ctx->CreateExtractElement(%(param)s, idx);
ctx->CreateCall(print_func, { buf, elem });
}
}
llvm::Value *end = ctx.get_constant(")");
ctx->CreateCall(prints_func, { buf, end });
}
"""
elif atomic_chk:
add_conv = ""
type = ""
if param == "BB":
type = "BOOL"
elif param == "II":
type = "INT"
elif param == "FF":
type = "FLOAT"
elif param == "DD":
type = "DOUBLE"
elif param == "SS":
type = "STRING"
add_conv = conv_from_string_id % { "what" : chr(ord('a') + idx) }
else:
error("Unsupported print type '%s'" % param)
code = add_conv + """
{
llvm::Function *print_func = get_runtime_func(RT_MDL_PRINT_%(type)s);
ctx->CreateCall(print_func, { buf, %(param)s });
}
"""
elif vector_chk:
size = vector_chk[1]
type = vector_chk[0].upper()
code = """
{
llvm::Function *print_func = get_runtime_func(RT_MDL_PRINT_%(type)s);
llvm::Function *prints_func = get_runtime_func(RT_MDL_PRINT_STRING);
llvm::Type *arg_tp = %(param)s->getType();
llvm::Value *comma = ctx.get_constant("<");
llvm::Value *next = ctx.get_constant(", ");
if (llvm::isa<llvm::ArrayType>(arg_tp)) {
unsigned idxes[1];
for (unsigned i = 0; i < %(size)d; ++i) {
ctx->CreateCall(prints_func, { buf, comma });
comma = next;
idxes[0] = i;
llvm::Value *elem = ctx->CreateExtractValue(%(param)s, idxes);
ctx->CreateCall(print_func, { buf, elem });
}
} else {
for (int i = 0; i < %(size)d; ++i) {
ctx->CreateCall(prints_func, { buf, comma });
comma = next;
llvm::Value *idx = ctx.get_constant(i);
llvm::Value *elem = ctx->CreateExtractElement(%(param)s, idx);
ctx->CreateCall(print_func, { buf, elem });
}
}
llvm::Value *end = ctx.get_constant(">");
ctx->CreateCall(prints_func, { buf, end });
}
"""
else:
error("Unsupported debug::print() parameter type '%s'" % param)
code = """
(void)%(param)s;
"""
self.format_code(f, code % { "type" : type, "size" : size, "param" : chr(ord('a') + idx) })
idx = idx + 1
# CPU epilog
code = """
llvm::Function *end_func = get_runtime_func(RT_MDL_PRINT_END);
ctx->CreateCall(end_func, buf);
}
"""
self.format_code(f, code)
self.format_code(f, "res = ctx.get_constant(true);\n")
elif mode == "state::zero_return":
# suppress unused variable warnings
idx = 0
for param in params:
self.write(f, "(void)%s;\n" % chr(ord('a') + idx))
idx += 1
self.write(f, "res = llvm::Constant::getNullValue(ctx_data->get_return_type());\n")
elif mode == "df::attr_lookup":
# light profile or bsdf measurement attribute
code_params = { "TYPE" : "LIGHT_PROFILE", "intrinsic" : intrinsic }
if intrinsic == "light_profile_power":
code_params["name"] = "POWER"
elif intrinsic == "light_profile_maximum":
code_params["name"] = "MAXIMUM"
elif intrinsic == "light_profile_isvalid":
code_params["name"] = "ISVALID"
elif intrinsic == "bsdf_measurement_isvalid":
code_params["TYPE"] = "BSDF_MEASUREMENT"
code_params["name"] = "ISVALID"
code = """
llvm::Type *res_type = ctx.get_non_deriv_return_type();
llvm::Value *lut = m_code_gen.get_attribute_table(
ctx, LLVM_code_generator::RTK_%(TYPE)s);
llvm::Value *lut_size = m_code_gen.get_attribute_table_size(
ctx, LLVM_code_generator::RTK_%(TYPE)s);
if (lut != NULL) {
// have a lookup table
llvm::Value *tmp = ctx.create_local(res_type, "tmp");
llvm::Value *cond = ctx->CreateICmpULT(a, lut_size);
llvm::BasicBlock *lut_bb = ctx.create_bb("lut_bb");
llvm::BasicBlock *bad_bb = ctx.create_bb("bad_bb");
llvm::BasicBlock *end_bb = ctx.create_bb("end");
// we do not expect out of bounds here
ctx.CreateWeightedCondBr(cond, lut_bb, bad_bb, 1, 0);
{
ctx->SetInsertPoint(lut_bb);
llvm::Value *select[] = {
a,
ctx.get_constant(int(Type_mapper::LAE_%(name)s))
};
llvm::Value *adr = ctx->CreateInBoundsGEP(lut, select);
llvm::Value *v = ctx->CreateLoad(adr);
ctx->CreateStore(v, tmp);
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(bad_bb);
llvm::Value *val = call_attr_func(
ctx,
RT_MDL_DF_%(TYPE)s_%(name)s,
Type_mapper::THV_%(intrinsic)s,
res_data,
a);
ctx->CreateStore(val, tmp);
ctx->CreateBr(end_bb);
}
{
ctx->SetInsertPoint(end_bb);
res = ctx->CreateLoad(tmp);
}
} else {
// no lookup table
res = call_attr_func(
ctx,
RT_MDL_DF_%(TYPE)s_%(name)s,
Type_mapper::THV_%(intrinsic)s,
res_data,
a);
}
if (inst.get_return_derivs()) { // expand to dual
res = ctx.get_dual(res);
}
""" % code_params
self.format_code(f, code)
elif mode == None:
error("Mode not set for intrinsic: %s %s" % (intrinsic, signature))
else:
warning("Unsupported mode '%s' for intrinsic: (%s %s)" % (mode, intrinsic, signature))
# suppress unused variable warnings
idx = 0
for param in params:
self.write(f, "(void)%s;\n" % chr(ord('a') + idx))
idx += 1
self.write(f, "res = llvm::UndefValue::get(ctx_data->get_return_type());\n")
self.write(f, "ctx.create_return(res);\n")
self.write(f, "return func;\n")
def handle_signatures(self, f, intrinsic, signatures):
"""Create code all sigtatures of one intrinsic."""
if len(signatures) == 1:
# no overloads
params = signatures[0].split('_')[1:]
if params == ['']:
# fix for (void) signature
params = []
block = self.gen_condition(f, params, not self.strict)
if block:
self.indent += 1
self.create_lazy_ir_construction(f, intrinsic, signatures[0])
if block:
self.indent -= 1
self.write(f, "}\n")
else:
# have overloads
signatures.sort()
pre_if = ""
for sig in signatures:
params = sig.split('_')[1:]
self.gen_condition(f, params, False, pre_if)
pre_if = "} else "
self.indent += 1
self.create_lazy_ir_construction(f, intrinsic, sig)
self.indent -= 1
self.write(f, "}\n")
def get_function_index(self, intrinsic_signature_pair):
"""Get the index for a given intrinsic seiganture pair"""
return self.m_func_index[intrinsic_signature_pair]
def create_function_index(self, intrinsic_signature_pair):
"""Get the index for a given intrinsic seiganture pair"""
if self.m_func_index.get(intrinsic_signature_pair) != None:
error("Signature pair '%s'already in use" % str(intrinsic_signature_pair))
self.m_func_index[intrinsic_signature_pair] = self.m_next_func_index;
self.m_next_func_index += 1;
def handle_intrinsic(self, f, intrinsic):
"""Create code for one intrinsic."""
sigs = self.m_intrinsics[intrinsic]
# order all signatures by ascending lenght
l = {}
for sig in sigs:
sig_token = sig.split('_')
n_params = len(sig_token) - 1
if n_params == 1 and sig_token[1] == '':
n_params = 0
l.setdefault(n_params, []).append(sig)
keys = list(l.keys())
if len(keys) == 1:
# typical case: all signatures have the same length
n_param = keys[0]
if self.strict:
self.write(f, "if (n_params == %d) {\n" % n_param)
self.indent += 1
else:
# create just an assertion
self.write(f, "MDL_ASSERT(n_params == %d);\n" % n_param)
for n_param in keys:
self.handle_signatures(f, intrinsic, l[n_param])
if self.strict:
self.indent -= 1
self.write(f, "}\n")
else:
# overloads with different signature length
self.write(f, "switch (n_params) {\n")
n_params = list(l.keys())
n_params.sort()
for n_param in n_params:
self.write(f, "case %d:\n" % n_param)
self.indent += 1
self.write(f, "{\n")
self.indent += 1
self.handle_signatures(f, intrinsic, l[n_param])
self.indent -= 1
self.write(f, "}\n")
self.write(f, "break;\n")
self.indent -= 1
self.write(f, "}\n")
def create_type_sig_tuple(self, params):
"""Create a type signature tuple (a, b) for a signature a_b."""
res = []
comma = ""
for param in params:
try:
type_name = self.m_inv_types[param]
except KeyError:
error("Unknown type_code '%s' found" % param)
sys.exit(1)
res.append(type_name)
return "(" + ", ".join(res) + ")"
def gen_type_check(self, f, idx, type_code):
"""Create a check for the idx parameter to be of given type."""
atomic_chk = self.get_atomic_type_kind(type_code)
self.write(f, "f_type->get_parameter(%s, p_type, p_sym);\n" % idx)
self.write(f, "p_type = p_type->skip_type_alias();\n")
if atomic_chk:
code = """
if (p_type->get_kind() != %s) {
return false;
}
""" % atomic_chk
self.format_code(f, code)
elif type_code[0] == 'E':
# check for enum type only, should be enough, we do not expect overloads with different
# enum types
code = """
if (p_type->get_kind() != mi::mdl::IType::TK_ENUM) {
return false;
}
"""
self.format_code(f, code)
elif type_code[0] == 'U':
# unsupported types
code = ""
elif type_code[1] == 'A':
# handle arrays
code = "{\n";
code += """
if (p_type->get_kind() != mi::mdl::IType::TK_ARRAY) {
return false;
}
mi::mdl::IType_array const *a_type = mi::mdl::cast<mi::mdl::IType_array>(p_type);
(void)a_type;
"""
if type_code[2] == 'N' or type_code[2] == 'n':
# deferred size array
code += """
if (a_type->is_immediate_sized()) {
return false;
}
"""
if type_code[0] == 'F':
code += """
mi::mdl::IType const *e_type = a_type->get_element_type();
if (e_type->get_kind() != mi::mdl::IType::TK_FLOAT) {
return false;
}
"""
else:
code += """
// Unsupported
return false;
"""
error("Unsupported type code " + type_code)
else:
code += """
// Unsupported
return false;
"""
error("Unsupported type code " + type_code)
code += "\n}\n"
self.format_code(f, code)
else:
vector_chk = self.get_vector_type_kind(type_code)
matrix_chk = self.get_matrix_type_kind(type_code)
text_shape = self.get_texture_shape(type_code)
if vector_chk:
params = {
"size" : type_code[-1],
"e_kind" : vector_chk
}
code = """
if (mi::mdl::IType_vector const *v_type = as<mi::mdl::IType_vector>(p_type)) {
if (v_type->get_size() != %(size)s) {
return false;
}
mi::mdl::IType_atomic const *e_type = v_type->get_element_type();
if (e_type->get_kind() != %(e_kind)s) {
return false;
}
} else {
return false;
}
"""
self.format_code(f, code % params)
elif matrix_chk:
params = {
"columns" : type_code[-2],
"size" : type_code[-1],
"e_kind" : matrix_chk
}
code = """
if (mi::mdl::IType_matrix const *m_type = as<mi::mdl::IType_matrix>(p_type)) {
if (m_type->get_columns() != %(columns)s) {
return false;
}
mi::mdl::IType_vector const *v_type = m_type->get_element_type();
if (v_type->get_size() != %(size)s) {
return false;
}
mi::mdl::IType_atomic const *e_type = v_type->get_element_type();
if (e_type->get_kind() != %(e_kind)s) {
return false;
}
} else {
return false;
}
"""
self.format_code(f, code % params)
elif text_shape:
code = """
if (mi::mdl::IType_texture const *t_type = as<mi::mdl::IType_texture>(p_type)) {
if (t_type->get_shape() != %s) {
return false;
}
}
"""
self.format_code(f, code % text_shape)
else:
code = """
// Unsupported
return false;
"""
error("Unsupported type code " + type_code)
self.format_code(f, code)
def create_signature_checker(self, f):
"""Create all signature checker functions."""
signatures = list(self.m_signatures.keys())
signatures.sort()
for sig in signatures:
if sig == '':
# we don't need a check for the (void) signature
continue
params = sig.split('_')
self.write(f, "/// Check that the given arguments have the signature %s.\n" % self.create_type_sig_tuple(params))
self.write(f, "///\n")
self.write(f, "/// \\param f_type an MDL function type\n")
self.write(f, "static bool check_sig_%s(mi::mdl::IType_function const *f_type)\n" % sig)
self.write(f, "{\n")
self.indent += 1
self.write(f, "mi::mdl::IType const *p_type;\n")
self.write(f, "mi::mdl::ISymbol const *p_sym;\n")
i = -1
last_p = None
seq = 0
params.append(None) # add a sentinal
for param in params:
if last_p != param:
if seq == 0:
pass
elif seq > 1:
self.write(f, "for (size_t i = %d; i < %d; ++i) {\n" % (i - seq + 1, i + 1))
self.indent += 1
self.gen_type_check(f, 'i', last_p)
self.indent -= 1
self.write(f, "}\n")
else:
self.gen_type_check(f, str(i), last_p)
last_p = param
seq = 1
else:
seq += 1
i += 1
self.write(f, "return true;\n")
self.indent -= 1
self.write(f, "}\n\n")
def write_access_specifier(self, f, specifier):
"""Write a class access specifier"""
self.indent -= 1
self.write(f, "\n%s:\n" % specifier)
self.indent += 1
def add_class_member(self, type, name, comment = None, from_constructor = False):
"""Add a class member to the generator class"""
self.m_class_members[name] = (type, name, comment, from_constructor)
self.m_class_member_names.append(name)
def generate_class_members(self, f):
"""Generate all class members of the generator class"""
self.write_access_specifier(f, "private")
for key in self.m_class_member_names:
type, name, comment, _ = self.m_class_members[key]
if comment:
self.write(f, "// %s\n" % comment)
space = ' '
if type[-1] == '&' or type[-1] == '*':
space = ''
self.write(f, "%s%s%s;\n\n" % (type, space, name))
def generate_constructor_comment(self, f):
"""Generate the doxygen comments for the constructor."""
self.write(f, "/// Constructor.\n")
keys = self.m_class_member_names
if len(keys) == 0:
return
self.write(f, "///\n")
max_len = 0
for key in keys:
_, name, _, from_constr = self.m_class_members[key]
if not from_constr:
continue
l = len(name)
if l > max_len:
max_len = l
max_len += 1
for key in keys:
type, name, comment, from_constr = self.m_class_members[key]
if not from_constr:
continue
space = ' ' * (max_len - len(name))
if comment:
self.write(f, "/// \param %s%s%s\n" % (name[2:], space, comment))
else:
self.write(f, "/// \param %s\n" % name[2:])
def generate_constructor_parameter(self, f):
"""Generate the parameter for the constructor."""
keys = self.m_class_member_names
if len(keys) == 0:
f.write("()\n")
return
self.indent += 1
max_len = 0
for key in keys:
type, _, _, from_constr = self.m_class_members[key]
if not from_constr:
continue
l = len(type)
if type[-1] != '*' and type[-1] != '&':
l += 1
if l > max_len:
max_len = l
comma = '('
for key in keys:
type, name, comment, from_constr = self.m_class_members[key]
if not from_constr:
continue
space = ' ' * (max_len - len(type))
f.write(comma + '\n')
comma = ','
if type[-1] == '&':
# cannot pass references, because we are constructor through templates
type = type[:-1] + '*'
self.write(f, "%s%s%s" % (type, space, name[2:]))
f.write(')\n')
self.indent -= 1
comma = ':'
for key in keys:
type, name, _, from_constr = self.m_class_members[key]
if not from_constr:
continue
if type[-1] == '&':
# passed by pointer, convert back to reference
self.write(f, "%s %s(*%s)\n" % (comma, name, name[2:]))
else:
self.write(f, "%s %s(%s)\n" % (comma, name, name[2:]))
comma = ','
def create_constructor(self, f):
"""Create the constructor for the class."""
self.generate_constructor_comment(f)
self.write(f, "MDL_runtime_creator")
self.generate_constructor_parameter(f)
code = """
{
m_use_user_state_module = false;
for (size_t i = 0, n = dimension_of(m_runtime_funcs); i < n; ++i) {
m_runtime_funcs[i] = NULL;
}
for (size_t i = 0, n = dimension_of(m_intrinsics); i < n; ++i) {
m_intrinsics[i] = NULL;
}
for (size_t i = 0, n = dimension_of(m_internal_funcs); i < n; ++i) {
m_internal_funcs[i] = NULL;
}
}
"""
self.format_code(f, code)
def register_c_runtime(self):
"""Register functions from the C runtime."""
# note: this section contains only functions supported in the C-runtime of Windows and Linux
self.register_runtime_func("absi", "II_II")
self.register_runtime_func("absf", "FF_FF")
self.register_runtime_func("abs", "DD_DD")
self.register_runtime_func("acos", "DD_DD")
self.register_runtime_func("acosf", "FF_FF")
self.register_runtime_func("asin", "DD_DD")
self.register_runtime_func("asinf", "FF_FF")
self.register_runtime_func("atan", "DD_DD")
self.register_runtime_func("atanf", "FF_FF")
self.register_runtime_func("atan2", "DD_DDDD")
self.register_runtime_func("atan2f", "FF_FFFF")
self.register_runtime_func("ceil", "DD_DD")
self.register_runtime_func("ceilf", "FF_FF")
self.register_runtime_func("cos", "DD_DD")
self.register_runtime_func("cosf", "FF_FF")
self.register_runtime_func("cosh", "DD_DD")
self.register_runtime_func("coshf", "FF_FF")
self.register_runtime_func("exp", "DD_DD")
self.register_runtime_func("expf", "FF_FF")
self.register_runtime_func("floor", "DD_DD")
self.register_runtime_func("floorf", "FF_FF")
self.register_runtime_func("fmod", "DD_DDDD")
self.register_runtime_func("fmodf", "FF_FFFF")
self.register_runtime_func("log", "DD_DD")
self.register_runtime_func("logf", "FF_FF")
self.register_runtime_func("log10", "DD_DD")
self.register_runtime_func("log10f", "FF_FF")
self.register_runtime_func("modf", "DD_DDdd")
self.register_runtime_func("modff", "FF_FFff")
self.register_runtime_func("pow", "DD_DDDD")
self.register_runtime_func("powf", "FF_FFFF")
self.register_runtime_func("powi", "DD_DDII")
self.register_runtime_func("sin", "DD_DD")
self.register_runtime_func("sinf", "FF_FF")
self.register_runtime_func("sinh", "DD_DD")
self.register_runtime_func("sinhf", "FF_FF")
self.register_runtime_func("sqrt", "DD_DD")
self.register_runtime_func("sqrtf", "FF_FF")
self.register_runtime_func("tan", "DD_DD")
self.register_runtime_func("tanf", "FF_FF")
self.register_runtime_func("tanh", "DD_DD")
self.register_runtime_func("tanhf", "FF_FF")
# used by other functions if supported
self.register_runtime_func("copysign", "DD_DDDD")
self.register_runtime_func("copysignf", "FF_FFFF")
# optional supported
self.register_runtime_func("sincosf", "VV_FFffff")
self.register_runtime_func("exp2f", "FF_FF")
self.register_runtime_func("exp2", "DD_DD")
self.register_runtime_func("fracf", "FF_FF")
self.register_runtime_func("frac", "DD_DD")
self.register_runtime_func("log2f", "FF_FF")
self.register_runtime_func("log2", "DD_DD")
self.register_runtime_func("mini", "II_IIII")
self.register_runtime_func("maxi", "II_IIII")
self.register_runtime_func("minf", "FF_FFFF")
self.register_runtime_func("maxf", "FF_FFFF")
self.register_runtime_func("min", "DD_DDDD")
self.register_runtime_func("max", "DD_DDDD")
self.register_runtime_func("rsqrtf", "FF_FF")
self.register_runtime_func("rsqrt", "DD_DD")
self.register_runtime_func("signf", "II_FF")
self.register_runtime_func("sign", "II_DD")
self.register_runtime_func("fsignf", "FF_FF")
self.register_runtime_func("fsign", "DD_DD")
self.register_runtime_func("int_bits_to_float", "FF_II")
self.register_runtime_func("float_bits_to_int", "II_FF")
self.register_runtime_func("stepFF", "FF_FFFF")
self.register_runtime_func("stepF2", "F2_F2F2")
self.register_runtime_func("stepF3", "F3_F3F3")
self.register_runtime_func("stepF4", "F4_F4F4")
self.register_runtime_func("stepDD", "DD_DDDD")
self.register_runtime_func("stepD2", "D2_D2D2")
self.register_runtime_func("stepD3", "D3_D3D3")
self.register_runtime_func("stepD4", "D4_D4D4")
def register_atomic_runtime(self):
self.register_mdl_runtime_func("mdl_clampi", "II_IIIIII")
self.register_mdl_runtime_func("mdl_clampf", "FF_FFFFFF")
self.register_mdl_runtime_func("mdl_clamp", "DD_DDDDDD")
self.register_mdl_runtime_func("mdl_exp2f", "FF_FF")
self.register_mdl_runtime_func("mdl_exp2", "DD_DD")
self.register_mdl_runtime_func("mdl_fracf", "FF_FF")
self.register_mdl_runtime_func("mdl_frac", "DD_DD")
self.register_mdl_runtime_func("mdl_log2f", "FF_FF")
self.register_mdl_runtime_func("mdl_log2", "DD_DD")
self.register_mdl_runtime_func("mdl_powi", "II_IIII")
self.register_mdl_runtime_func("mdl_roundf", "FF_FF")
self.register_mdl_runtime_func("mdl_round", "DD_DD")
self.register_mdl_runtime_func("mdl_rsqrtf", "FF_FF")
self.register_mdl_runtime_func("mdl_rsqrt", "DD_DD")
self.register_mdl_runtime_func("mdl_saturatef", "FF_FF")
self.register_mdl_runtime_func("mdl_saturate", "DD_DD")
self.register_mdl_runtime_func("mdl_signi", "II_II")
self.register_mdl_runtime_func("mdl_signf", "FF_FF")
self.register_mdl_runtime_func("mdl_sign", "DD_DD")
self.register_mdl_runtime_func("mdl_smoothstepf", "FF_FFFFFF")
self.register_mdl_runtime_func("mdl_smoothstep", "DD_DDDDDD")
self.register_mdl_runtime_func("mdl_int_bits_to_floati", "FF_II")
self.register_mdl_runtime_func("mdl_float_bits_to_intf", "II_FF")
# from libmdlrt
self.register_mdl_runtime_func("mdl_blackbody", "FA3_FF")
self.register_mdl_runtime_func("mdl_emission_color", "vv_ffffffII")
self.register_mdl_runtime_func("mdl_reflection_color", "vv_ffffffII")
# extra used by other functions
self.register_mdl_runtime_func("mdl_mini", "II_IIII")
self.register_mdl_runtime_func("mdl_minf", "FF_FFFF")
self.register_mdl_runtime_func("mdl_min", "DD_DDDD")
self.register_mdl_runtime_func("mdl_maxi", "II_IIII")
self.register_mdl_runtime_func("mdl_maxf", "FF_FFFF")
self.register_mdl_runtime_func("mdl_max", "DD_DDDD")
# tex functions
self.register_mdl_runtime_func("mdl_tex_resolution_2d", "IA2_PTIIIA2FF")
self.register_mdl_runtime_func("mdl_tex_resolution_3d", "IA3_PTIIFF")
self.register_mdl_runtime_func("mdl_tex_width", "II_PTIIFF")
self.register_mdl_runtime_func("mdl_tex_height", "II_PTIIFF")
self.register_mdl_runtime_func("mdl_tex_depth", "II_PTIIFF")
self.register_mdl_runtime_func("mdl_tex_isvalid", "BB_PTII")
self.register_mdl_runtime_func("mdl_tex_frame", "IA2_PTII")
self.register_mdl_runtime_func("mdl_tex_lookup_float_2d", "FF_PTIIFA2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_deriv_float_2d", "FF_PTIIFD2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float_3d", "FF_PTIIFA3EWMEWMEWMFA2FA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float_cube", "FF_PTIIFA3")
self.register_mdl_runtime_func("mdl_tex_lookup_float_ptex", "FF_PTIIII")
self.register_mdl_runtime_func("mdl_tex_lookup_float2_2d", "FA2_PTIIFA2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_deriv_float2_2d", "FA2_PTIIFD2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float2_3d", "FA2_PTIIFA3EWMEWMEWMFA2FA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float2_cube", "FA2_PTIIFA3")
self.register_mdl_runtime_func("mdl_tex_lookup_float2_ptex", "FA2_PTIIII")
self.register_mdl_runtime_func("mdl_tex_lookup_float3_2d", "FA3_PTIIFA2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_deriv_float3_2d", "FA3_PTIIFD2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float3_3d", "FA3_PTIIFA3EWMEWMEWMFA2FA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float3_cube", "FA3_PTIIFA3")
self.register_mdl_runtime_func("mdl_tex_lookup_float3_ptex", "FA3_PTIIII")
self.register_mdl_runtime_func("mdl_tex_lookup_float4_2d", "FA4_PTIIFA2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_deriv_float4_2d", "FA4_PTIIFD2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float4_3d", "FA4_PTIIFA3EWMEWMEWMFA2FA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_float4_cube", "FA4_PTIIFA3")
self.register_mdl_runtime_func("mdl_tex_lookup_float4_ptex", "FA4_PTIIII")
self.register_mdl_runtime_func("mdl_tex_lookup_color_2d", "FA3_PTIIFA2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_deriv_color_2d", "FA3_PTIIFD2EWMEWMFA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_color_3d", "FA3_PTIIFA3EWMEWMEWMFA2FA2FA2FF")
self.register_mdl_runtime_func("mdl_tex_lookup_color_cube", "FA3_PTIIFA3")
self.register_mdl_runtime_func("mdl_tex_lookup_color_ptex", "FA3_PTIIII")
self.register_mdl_runtime_func("mdl_tex_texel_float_2d", "FF_PTIIIA2IA2FF")
self.register_mdl_runtime_func("mdl_tex_texel_float2_2d", "FA2_PTIIIA2IA2FF")
self.register_mdl_runtime_func("mdl_tex_texel_float3_2d", "FA3_PTIIIA2IA2FF")
self.register_mdl_runtime_func("mdl_tex_texel_float4_2d", "FA4_PTIIIA2IA2FF")
self.register_mdl_runtime_func("mdl_tex_texel_color_2d", "FA3_PTIIIA2IA2FF")
self.register_mdl_runtime_func("mdl_tex_texel_float_3d", "FF_PTIIIA3FF")
self.register_mdl_runtime_func("mdl_tex_texel_float2_3d", "FA2_PTIIIA3FF")
self.register_mdl_runtime_func("mdl_tex_texel_float3_3d", "FA3_PTIIIA3FF")
self.register_mdl_runtime_func("mdl_tex_texel_float4_3d", "FA4_PTIIIA3FF")
self.register_mdl_runtime_func("mdl_tex_texel_color_3d", "FA3_PTIIIA3FF")
# GLSL support functions
self.register_mdl_runtime_func("mdl_equal_B2", "B2_B2B2")
self.register_mdl_runtime_func("mdl_equal_B3", "B3_B3B3")
self.register_mdl_runtime_func("mdl_equal_B4", "B4_B4B4")
self.register_mdl_runtime_func("mdl_equal_D2", "B2_D2D2")
self.register_mdl_runtime_func("mdl_equal_D3", "B3_D3D3")
self.register_mdl_runtime_func("mdl_equal_D4", "B4_D4D4")
self.register_mdl_runtime_func("mdl_notEqual_B2", "B2_B2B2")
self.register_mdl_runtime_func("mdl_notEqual_B3", "B3_B3B3")
self.register_mdl_runtime_func("mdl_notEqual_B4", "B4_B4B4")
self.register_mdl_runtime_func("mdl_notEqual_D2", "B2_D2D2")
self.register_mdl_runtime_func("mdl_notEqual_D3", "B3_D3D3")
self.register_mdl_runtime_func("mdl_notEqual_D4", "B4_D4D4")
self.register_mdl_runtime_func("mdl_lessThan_D2", "B2_D2D2")
self.register_mdl_runtime_func("mdl_lessThan_D3", "B3_D3D3")
self.register_mdl_runtime_func("mdl_lessThan_D4", "B4_D4D4")
self.register_mdl_runtime_func("mdl_lessThanEqual_D2", "B2_D2D2")
self.register_mdl_runtime_func("mdl_lessThanEqual_D3", "B3_D3D3")
self.register_mdl_runtime_func("mdl_lessThanEqual_D4", "B4_D4D4")
self.register_mdl_runtime_func("mdl_greaterThan_D2", "B2_D2D2")
self.register_mdl_runtime_func("mdl_greaterThan_D3", "B3_D3D3")
self.register_mdl_runtime_func("mdl_greaterThan_D4", "B4_D4D4")
self.register_mdl_runtime_func("mdl_greaterThanEqual_D2", "B2_D2D2")
self.register_mdl_runtime_func("mdl_greaterThanEqual_D3", "B3_D3D3")
self.register_mdl_runtime_func("mdl_greaterThanEqual_D4", "B4_D4D4")
self.register_mdl_runtime_func("mdl_and_B2", "B2_B2B2")
self.register_mdl_runtime_func("mdl_and_B3", "B3_B3B3")
self.register_mdl_runtime_func("mdl_and_B4", "B4_B4B4")
self.register_mdl_runtime_func("mdl_or_B2", "B2_B2B2")
self.register_mdl_runtime_func("mdl_or_B3", "B3_B3B3")
self.register_mdl_runtime_func("mdl_or_B4", "B4_B4B4")
# df functions
self.register_mdl_runtime_func("mdl_df_light_profile_power", "FF_PTII")
self.register_mdl_runtime_func("mdl_df_light_profile_maximum", "FF_PTII")
self.register_mdl_runtime_func("mdl_df_light_profile_isvalid", "BB_PTII")
self.register_mdl_runtime_func("mdl_df_bsdf_measurement_isvalid", "BB_PTII")
self.register_mdl_runtime_func("mdl_df_bsdf_measurement_resolution", "IA3_PTIIEMP")
self.register_mdl_runtime_func("mdl_df_bsdf_measurement_evaluate", "FA3_PTIIFA2FA2EMP")
self.register_mdl_runtime_func("mdl_df_bsdf_measurement_sample", "FA3_PTIIFA2FA3EMP")
self.register_mdl_runtime_func("mdl_df_bsdf_measurement_pdf", "FF_PTIIFA2FA2EMP")
self.register_mdl_runtime_func("mdl_df_bsdf_measurement_albedos", "FA4_PTIIFA2")
self.register_mdl_runtime_func("mdl_df_light_profile_evaluate", "FF_PTIIFA2")
self.register_mdl_runtime_func("mdl_df_light_profile_sample", "FA3_PTIIFA3")
self.register_mdl_runtime_func("mdl_df_light_profile_pdf", "FF_PTIIFA2")
# renderer support
self.register_mdl_runtime_func("mdl_adapt_normal", "FA3_PTFA3")
# exception handling
self.register_mdl_runtime_func("mdl_out_of_bounds", "VV_xsIIZZCSII")
self.register_mdl_runtime_func("mdl_div_by_zero", "VV_xsCSII")
# debug support
self.register_mdl_runtime_func("mdl_debugbreak", "VV_")
self.register_mdl_runtime_func("mdl_assertfail", "VV_CSCSCSII")
self.register_mdl_runtime_func("__assertfail", "VV_CSCSIICSZZ")
self.register_mdl_runtime_func("mdl_print_begin", "lb_")
self.register_mdl_runtime_func("mdl_print_end", "VV_lb")
self.register_mdl_runtime_func("mdl_print_bool", "VV_lbBB")
self.register_mdl_runtime_func("mdl_print_int", "VV_lbII")
self.register_mdl_runtime_func("mdl_print_float", "VV_lbFF")
self.register_mdl_runtime_func("mdl_print_double", "VV_lbDD")
self.register_mdl_runtime_func("mdl_print_string", "VV_lbCS")
self.register_mdl_runtime_func("vprintf", "II_CSvv")
# string ID support
self.register_mdl_runtime_func("mdl_to_cstring", "CS_SS")
# JIT support
self.register_mdl_runtime_func("mdl_tex_res_float", "FF_scII")
self.register_mdl_runtime_func("mdl_tex_res_float3", "F3_scII")
self.register_mdl_runtime_func("mdl_tex_res_color", "CC_scII")
self.register_mdl_runtime_func("mdl_enter_func", "VV_vv")
def generate_runtime_enum(self, f):
"""Generate the enum for the runtime functions."""
self.write(f, "/// Used functions from the C-runtime.\n")
self.write(f, "enum Runtime_function {\n")
self.indent += 1
last = None
self.write(f, "RT_C_FIRST,\n")
init = " = RT_C_FIRST"
keys = list(self.m_c_runtime_functions.keys())
keys.sort()
for func in keys:
enum_value = "RT_" + func
enum_value = enum_value.upper()
last = enum_value
self.write(f, "%s%s,\n" % (enum_value.upper(), init))
init = ""
self.write(f, "RT_C_LAST = %s,\n" % last.upper())
self.write(f, "RT_MDL_FIRST,\n")
init = " = RT_MDL_FIRST"
keys = list(self.m_mdl_runtime_functions.keys())
keys.sort()
for func in keys:
enum_value = "RT_" + func
enum_value = enum_value.upper()
last = enum_value
self.write(f, "%s%s,\n" % (enum_value.upper(), init))
init = ""
self.write(f, "RT_MDL_LAST = %s,\n" % last.upper())
self.write(f, "RT_LAST = RT_MDL_LAST\n")
self.indent -= 1
self.write(f, "};\n")
def generate_runtime_func_cache(self, f):
"""Generate the lazy runtime function getter."""
self.write(f, "/// Get a runtime function lazily.\n")
self.write(f, "///\n")
self.write(f, "/// \\param code The runtime function code.\n")
self.write(f, "llvm::Function *get_runtime_func(Runtime_function code) {\n")
self.indent += 1
self.write(f, "llvm::Function *func = m_runtime_funcs[code];\n")
self.write(f, "if (func != NULL)\n")
self.indent += 1
self.write(f, "return func;\n")
self.indent -= 1
self.write(f, "switch (code) {\n")
for name, signature in self.m_c_runtime_functions.items():
enum_value = "RT_" + name
enum_value = enum_value.upper()
self.write(f, "case %s:\n" % enum_value)
self.indent += 1
self.write(f, 'func = get_c_runtime_func(%s, "%s");\n' % (enum_value, signature))
self.write(f, "break;\n")
self.indent -= 1
for name, signature in self.m_mdl_runtime_functions.items():
enum_value = "RT_" + name
enum_value = enum_value.upper()
self.write(f, "case %s:\n" % enum_value)
self.indent += 1
self.write(f, 'func = create_runtime_func(code, "%s", "%s");\n' % (name, signature))
self.write(f, "break;\n")
self.indent -= 1
code ="""
default:
MDL_ASSERT(!"unsupported runtime function!");
break;
}
m_runtime_funcs[code] = func;
return func;
"""
self.format_code(f, code)
self.indent -= 1
self.write(f, "}\n")
code = """
/// Return an LLVM type for a (single type) signature.
///
/// \\param sig The signature, will be moved.
/// \\param by_ref True if this type must passed by reference.
llvm::Type *type_from_signature(
char const * &sig,
bool &by_ref);
/// Create a function declaration from a signature.
///
/// \\param[in] name The name of the C runtime function.
/// \\param[in] signature The signature of the C runtime function.
/// \\param[out] is_sret Set to true, if this is a sret function, else set to false.
llvm::Function *decl_from_signature(
char const *name,
char const *signature,
bool &is_sret);
/// Get an external C-runtime function.
///
/// \\param func The code of the C runtime function.
/// \\param signature The signature of the C runtime function.
llvm::Function *get_c_runtime_func(
Runtime_function func,
char const *signature);
/// Check if a given MDL runtime function exists inside the C-runtime.
///
/// \\param code The (MDL) runtime function code.
/// \\param signature The signature of the runtime function.
llvm::Function *find_in_c_runtime(
Runtime_function code,
char const *signature);
/// Create a runtime function.
///
/// \\param code The runtime function code.
/// \\param name The name of the runtime function.
/// \\param signature The signature of the runtime function.
llvm::Function *create_runtime_func(
Runtime_function code,
char const *name,
char const *signature);
/// Load an runtime function arguments value.
///
/// \param ctx the current function context
/// \param arg the passed argument, either a reference or the value instead
llvm::Value *load_by_value(Function_context &ctx, llvm::Value *arg);
/// Get the start offset of the next entry with the given type in a valist.
///
/// \param offset the offset into a valist in bytes pointing to after the last
/// entry. it will be advanced to after the new entry.
/// \param operand_type the operand type for the next entry
int get_next_valist_entry_offset(int &offset, llvm::Type *operand_type);
/// Get a pointer to the next entry in the given valist buffer.
///
/// \param ctx the current function context
/// \param valist the valist buffer
/// \param offset the offset into valist in bytes pointing to after the last entry.
/// it will be advanced to after the new entry.
/// \param operand_type the operand type for the next entry
llvm::Value *get_next_valist_pointer(Function_context &ctx,
llvm::Value *valist, int &offset, llvm::Type *operand_type);
/// Call a runtime function.
///
/// \param ctx the current function context
/// \param callee the called function
/// \param args function arguments
llvm::Value *call_rt_func(
Function_context &ctx,
llvm::Function *callee,
llvm::ArrayRef<llvm::Value *> args);
/// Call a void runtime function.
///
/// \param ctx the current function context
/// \param callee the called function
/// \param args function arguments
void call_rt_func_void(
Function_context &ctx,
llvm::Function *callee,
llvm::ArrayRef<llvm::Value *> args);
/// Call texture attribute runtime function.
///
/// \param ctx the current function context
/// \param tex_func_code the runtime function code
/// \param tex_func_idx the index in the texture handler vtable
/// \param res_data the resource data
/// \param tex_id the ID of the texture
/// \param opt_uv_tile the UV tile, if resolution_2d will be called
/// \param opt_frame the frame (optional)
/// \param res_type the type of the attribute
llvm::Value *call_tex_attr_func(
Function_context &ctx,
Runtime_function tex_func_code,
Type_mapper::Tex_handler_vtable_index tex_func_idx,
llvm::Value *res_data,
llvm::Value *tex_id,
llvm::Value *opt_uv_tile,
llvm::Value *opt_frame,
llvm::Type *res_type);
/// Call attribute runtime function.
///
/// \param ctx the current function context
/// \param func_code the runtime function code
/// \param tex_func_idx the index in the texture handler vtable
/// \param res_data the resource data
/// \param res_id the ID of the resource
llvm::Value *call_attr_func(
Function_context &ctx,
Runtime_function func_code,
Type_mapper::Tex_handler_vtable_index tex_func_idx,
llvm::Value *res_data,
llvm::Value *res_id);
"""
self.format_code(f, code)
def create_intrinsic_func_indexes(self, intrinsics):
"""Create function indexes for all intrinsic functions."""
for intrinsic in intrinsics:
sigs = self.m_intrinsics[intrinsic]
# order all signatures by ascending lenght
l = {}
for sig in sigs:
sig_token = sig.split('_')
n_params = len(sig_token) - 1
l.setdefault(n_params, []).append(sig)
n_params = list(l.keys())
n_params.sort()
for n_param in n_params:
signatures = l[n_param]
signatures.sort()
for sig in signatures:
self.create_function_index((intrinsic, sig))
def create_check_state_module(self, f):
code = """
/// Check whether the given module contains the given function and create an error if not.
///
/// \param mod The module
/// \param func_name The function name
/// \param ret_type The return type the function should have, or NULL for not checking it
/// \param optional If true, no error will be generated when then function does not exist
///
/// \\returns true, if the module contains the function.
bool check_function_exists(
llvm::Module *mod,
char const *func_name,
llvm::Type *ret_type,
bool optional)
{
llvm::Function *func = mod->getFunction(func_name);
if (func == NULL) {
if (optional) return true;
m_code_gen.error(STATE_MODULE_FUNCTION_MISSING, func_name);
return false;
}
if (ret_type != NULL && func->getReturnType() != ret_type) {
m_code_gen.error(WRONG_RETURN_TYPE_FOR_STATE_MODULE_FUNCTION, func_name);
return false;
}
return true;
}
/// Check whether the given module contains the given function returning a pointer
/// and create an error if not.
///
/// \param mod The module
/// \param func_name The function name
///
/// \\returns true, if the module contains the function.
bool check_function_returns_pointer(llvm::Module *mod, char const *func_name) {
llvm::Function *func = mod->getFunction(func_name);
if (func == NULL) {
m_code_gen.error(STATE_MODULE_FUNCTION_MISSING, func_name);
return false;
}
if (!func->getReturnType()->isPointerTy()) {
m_code_gen.error(WRONG_RETURN_TYPE_FOR_STATE_MODULE_FUNCTION, func_name);
return false;
}
return true;
}
"""
self.format_code(f, code)
code = """
/// Check whether the given module can be used as user-implemented state module.
///
/// \param mod The module containing the user implementation of state.
///
/// \\returns true, if the module can be used as a user implementation of state.
bool check_state_module(llvm::Module *mod) {
bool success = true;
#define HAS_FUNC(x, ret_type) if (!check_function_exists(mod, x, ret_type, false)) success = false;
#define HAS_OPT_FUNC(x, ret_type) if (!check_function_exists(mod, x, ret_type, true)) success = false;
llvm::Type *char_ptr_type = m_code_gen.m_type_mapper.get_char_ptr_type();
llvm::Type *float_type = m_code_gen.m_type_mapper.get_float_type();
llvm::Type *float_ptr_type = m_code_gen.m_type_mapper.get_float_ptr_type();
llvm::Type *float3_type = m_code_gen.m_type_mapper.get_float3_type();
llvm::Type *float3x3_type = m_code_gen.m_type_mapper.get_float3x3_type();
llvm::Type *float4x4_type = m_code_gen.m_type_mapper.get_float4x4_type();
llvm::Type *int_type = m_code_gen.m_type_mapper.get_int_type();
llvm::Type *void_type = m_code_gen.m_type_mapper.get_void_type();
"""
self.format_code(f, code)
# all these functions have to be defined with a State_core parameter
state_core_intrinsics = [
("position", "float3_type"),
("normal", "float3_type"),
("set_normal", "void_type"),
("geometry_normal", "float3_type"),
("motion", "float3_type"),
("texture_coordinate", "float3_type"),
("texture_tangent_u", "float3_type"),
("texture_tangent_v", "float3_type"),
("tangent_space", "float3x3_type"),
("geometry_tangent_u", "float3_type"),
("geometry_tangent_v", "float3_type"),
("animation_time", "float_type"),
("wavelength_base", "float_ptr_type"),
("transform", "float4x4_type"),
("transform_point", "float3_type"),
("transform_normal", "float3_type"),
("transform_vector", "float3_type"),
("transform_scale", "float_type"),
("object_id", "int_type"),
("get_texture_results", "NULL"),
("get_ro_data_segment", "char_ptr_type")
]
# optional functions with State_core parameter
state_core_intrinsics_opt = [
("rounded_corner_normal", "float3_type")
]
# all these functions have to be defined with a State_environment parameter
state_env_intrinsics = [
("direction", "float3_type")
]
for intrinsic, ret_type in state_core_intrinsics:
self.write(f, "HAS_FUNC(\"%s\", %s)\n" % (
self.get_mangled_state_func_name(intrinsic, "State_core"), ret_type))
for intrinsic, ret_type in state_core_intrinsics_opt:
self.write(f, "HAS_OPT_FUNC(\"%s\", %s)\n" % (
self.get_mangled_state_func_name(intrinsic, "State_core"), ret_type))
for intrinsic, ret_type in state_env_intrinsics:
self.write(f, "HAS_FUNC(\"%s\", %s)\n" % (
self.get_mangled_state_func_name(intrinsic, "State_environment"), ret_type))
self.write(f, "\n")
self.write(f, "if (!success) return false;\n")
self.write(f, "m_use_user_state_module = true;\n")
self.write(f, "return true;\n")
self.indent -= 1
self.write(f, "}\n")
self.write(f, "\n")
def finalize(self):
"""Create output."""
intrinsics = []
unsupported = []
for intrinsic in self.m_intrinsics.keys():
if self.unsupported_intrinsics.get(intrinsic):
# filter out unnsupported ones
unsupported.append(intrinsic)
else:
intrinsics.append(intrinsic)
unsupported.sort()
intrinsics.sort()
self.create_intrinsic_func_indexes(intrinsics)
self.register_c_runtime()
self.register_atomic_runtime();
f = open(self.out_name, "w")
# add class members
self.add_class_member("mi::mdl::IAllocator *", "m_alloc", "The allocator.", True)
self.add_class_member("LLVM_code_generator &", "m_code_gen", "The code generator.", True)
self.add_class_member("LLVM_code_generator::Target_language", "m_target_lang", "The target language.", True)
self.add_class_member("bool const", "m_fast_math", "True if fast-math is enabled.", True)
self.add_class_member("bool const", "m_has_sincosf", "True if destination has sincosf.", True)
self.add_class_member("bool const", "m_has_res_handler", "True if a resource handler I/F is available.", True)
self.add_class_member("bool", "m_use_user_state_module", "True if user-defined state module functions should be used.", False)
self.add_class_member("bool", "m_always_inline_rt", "True if small runtime functions should be marked as always_inline", True)
self.add_class_member("int", "m_internal_space", "The internal_space encoding.", True)
self.add_class_member("llvm::Function *", "m_runtime_funcs[RT_LAST + 1]", "Runtime functions.", False)
self.add_class_member("llvm::Function *", "m_intrinsics[%d * 2]" % self.m_next_func_index, "Cache for intrinsic functions, with and without derivative returns.", False)
self.add_class_member("llvm::Function *", "m_internal_funcs[Internal_function::KI_NUM_INTERNAL_FUNCTIONS]", "Cache for internal functions.", False)
# start class
self.write(f, "class MDL_runtime_creator {\n")
self.indent += 1
self.write_access_specifier(f, "public")
self.write(f, "/// Number of supported intrinsics.\n")
self.write(f, "static size_t const NUM_INTRINSICS = %d;\n\n" % self.m_next_func_index)
self.generate_runtime_enum(f)
self.write_access_specifier(f, "public")
# generate the constructor
self.create_constructor(f)
# write prototypes of internal function creation functions
self.write(f, "/// Generate LLVM IR for state::set_normal()\n")
self.write(f, "llvm::Function *create_state_set_normal(Internal_function const *int_func);\n\n")
self.write(f, "/// Generate LLVM IR for state::get_texture_results()\n")
self.write(f, "llvm::Function *create_state_get_texture_results(Internal_function const *int_func);\n\n")
self.write(f, "/// Generate LLVM IR for state::get_arg_block()\n")
self.write(f, "llvm::Function *create_state_get_arg_block(Internal_function const *int_func);\n\n")
self.write(f, "/// Generate LLVM IR for state::get_arg_block_float/float3/uint/bool()\n")
self.write(f, "llvm::Function *create_state_get_arg_block_value(Internal_function const *int_func);\n\n")
self.write(f, "/// Generate LLVM IR for state::get_ro_data_segment()\n")
self.write(f, "llvm::Function *create_state_get_ro_data_segment(Internal_function const *int_func);\n\n")
self.write(f, "/// Generate LLVM IR for state::object_id()\n")
self.write(f, "llvm::Function *create_state_object_id(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for state::get_material_ior()\n")
self.write(f, "llvm::Function *create_state_get_material_ior(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for state::get_thin_walled()\n")
self.write(f, "llvm::Function *create_state_get_thin_walled(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for state::adapt_microfacet_roughness()\n")
self.write(f, "llvm::Function *create_state_adapt_microfacet_roughness(Internal_function const *int_func);\n\n")
self.write(f, "/// Generate LLVM IR for state::adapt_normal()\n")
self.write(f, "llvm::Function *create_state_adapt_normal(Internal_function const *int_func);\n\n")
self.write(f, "/// Generate LLVM IR for df::bsdf_measurement_resolution()\n")
self.write(f, "llvm::Function *create_df_bsdf_measurement_resolution(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for df::bsdf_measurement_evaluate()\n")
self.write(f, "llvm::Function *create_df_bsdf_measurement_evaluate(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for df::bsdf_measurement_sample()\n")
self.write(f, "llvm::Function *create_df_bsdf_measurement_sample(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for df::bsdf_measurement_pdf()\n")
self.write(f, "llvm::Function *create_df_bsdf_measurement_pdf(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for df::bsdf_measurement_albedos()\n")
self.write(f, "llvm::Function *create_df_bsdf_measurement_albedos(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for df::light_profile_evaluate()\n")
self.write(f, "llvm::Function *create_df_light_profile_evaluate(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for df::light_profile_sample()\n")
self.write(f, "llvm::Function *create_df_light_profile_sample(Internal_function const *int_func);\n")
self.write(f, "/// Generate LLVM IR for df::light_profile_pdf()\n")
self.write(f, "llvm::Function *create_df_light_profile_pdf(Internal_function const *int_func);\n")
self.write(f, "\n")
# generate the public functions
self.write(f, "/// Generate LLVM IR for an internal function.\n")
self.write(f, "///\n")
self.write(f, "/// \\param int_func Information about the internal function\n")
self.write(f, "///\n")
self.write(f, "/// \\return The LLVM Function object or NULL if the function could\n")
self.write(f, "/// not be generated\n")
self.write(f, "llvm::Function *get_internal_function(\n")
self.indent += 1
self.write(f, "Internal_function const *int_func);\n")
self.indent -= 1
self.write(f, "\n")
self.create_check_state_module(f)
self.write(f, "/// Generate LLVM IR for an intrinsic function.\n")
self.write(f, "///\n")
self.write(f, "/// \\param func_def The definition of the intrinsic function\n")
self.write(f, "/// \\param return_derivs If true, the funcion will return derivatives\n")
self.write(f, "///\n")
self.write(f, "/// \\return The LLVM Function object or NULL if the function could\n")
self.write(f, "/// not be generated\n")
self.write(f, "llvm::Function *get_intrinsic_function(\n")
self.indent += 1
self.write(f, "mi::mdl::IDefinition const *func_def,\n")
self.write(f, "bool return_derivs)\n")
self.indent -= 1
self.write(f, "{\n")
self.indent += 1
self.write(f, "mi::mdl::IType_function const *f_type = cast<mi::mdl::IType_function>(func_def->get_type());\n")
self.write(f, "int n_params = f_type->get_parameter_count();\n")
self.write(f, "\n")
self.write(f, "switch (func_def->get_semantics()) {\n")
for intrinsic in intrinsics:
mod_name = self.m_intrinsic_mods[intrinsic]
if mod_name == "" and intrinsic == "color":
self.write(f, "case mi::mdl::IDefinition::DS_COLOR_SPECTRUM_CONSTRUCTOR:\n")
else:
self.write(f, "case mi::mdl::IDefinition::DS_INTRINSIC_%s_%s:\n" % (mod_name.upper(), intrinsic.upper()))
self.indent += 1
self.handle_intrinsic(f, intrinsic)
self.write(f, "break;\n");
self.indent -= 1
for intrinsic in unsupported:
mod_name = self.m_intrinsic_mods[intrinsic]
if mod_name == "" and intrinsic == "color":
self.write(f, "case mi::mdl::IDefinition::DS_COLOR_SPECTRUM_CONSTRUCTOR:\n")
else:
self.write(f, "case mi::mdl::IDefinition::DS_INTRINSIC_%s_%s:\n" % (mod_name.upper(), intrinsic.upper()))
if len(unsupported) > 0:
self.indent += 1
self.write(f, 'MDL_ASSERT(!"Cannot generate unsupported intrinsic");\n')
self.write(f, "break;\n");
self.indent -= 1
self.write(f, "default:\n")
self.indent += 1
self.write(f, "break;\n");
self.indent -= 1
self.write(f, "}\n")
self.write(f, "// cannot generate\n")
self.write(f, "return NULL;\n")
self.indent -= 1
self.write(f, "}\n")
self.generate_runtime_func_cache(f)
# generate private helper functions
self.write_access_specifier(f, "private")
self.create_signature_checker(f)
# create the constructor functions
for intrinsic in intrinsics:
sigs = self.m_intrinsics[intrinsic]
# order all signatures by ascending lenght
l = {}
for sig in sigs:
sig_token = sig.split('_')
n_params = len(sig_token) - 1
l.setdefault(n_params, []).append(sig)
n_params = list(l.keys())
n_params.sort()
for n_param in n_params:
sigs_same_len = l[n_param]
for signature in sigs_same_len:
self.create_ir_constructor(f, intrinsic, signature)
self.generate_class_members(f)
# end of the class
self.indent -= 1
self.write(f, "};\n")
f.close()
def usage(args):
"""print usage info and exit"""
print("Usage: %s stdlib_directory outputfile" % args[0])
return 1
def main(args):
"""Process one file and generate signatures."""
if len(args) != 3:
return usage(args)
stdlib_dir = args[1]
out_name = args[2]
strict = True
try:
parser = SignatureParser(args[0], stdlib_dir, out_name, strict)
parser.parse("math")
parser.parse("state")
parser.parse("df")
parser.parse("tex")
parser.parse("scene")
parser.parse("debug")
parser.parse_builtins(
"""
// spectrum constructor
export color color(float[<N>] wavelenghts, float[N] amplitudes) uniform [[ intrinsic() ]];
""")
parser.finalize()
except IOError as e:
error(str(e))
return 1
return 0
if __name__ == "__main__":
if len(sys.argv) == 1:
# called 'as script': assume 64bit debug
obj = os.environ['MI_OBJ'] + '/neuray_vc11/x64_Debug/mdl_jit_generator_jit';
dbg_args = ["../../compiler/stdmodule", obj + '/generator_jit_intrinsic_func.i']
sys.exit(main([sys.argv[0]] + dbg_args))
else:
sys.exit(main(sys.argv))
| MDL-SDK-master | src/mdl/jit/generator_jit/gen_intrinsic_func.py |
#!/bin/env python
#*****************************************************************************
# Copyright (c) 2017-2023, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#*****************************************************************************
# This script generates the MDL runtime header file for user modules.
#
# Call it like this:
# python gen_user_modules_runtime_header.py ../../compiler/stdmodule ../../../prod/bin/mdl_sdk_example/user_modules/mdl_runtime.h
#
# python 2.6 or higher is needed
#
import sys
import re
import os
from gen_intrinsic_func import SignatureParser, error
type_map = {
"int2": "vint2",
"int3": "vint3",
"int4": "vint4",
"float2": "vfloat2",
"float3": "vfloat3",
"float4": "vfloat4",
"double2": "vdouble2",
"double3": "vdouble3",
"double4": "vdouble4",
"bool2": "vbool2",
"bool3": "vbool3",
"bool4": "vbool4",
}
reference_parameter_types = {
"bool2",
"bool3",
"bool4",
"color",
"double2",
"double3",
"double4",
"float2",
"float3",
"float4",
"int2",
"int3",
"int4"
}
def eat_until(token_set, tokens):
"""eat tokens until token_kind is found and return them, handle parenthesis"""
r = 0
e = 0
g = 0
a = 0
l = len(tokens)
eaten_tokens = []
while l > 0:
tok = tokens[0]
if r == 0 and e == 0 and g == 0 and a == 0 and tok in token_set:
return eaten_tokens, tokens
if tok == '(':
r += 1
elif tok == ')':
r -= 1
elif tok == '[':
e += 1
elif tok == ']':
e -= 1
elif tok == '{':
g += 1
elif tok == '}':
g -= 1
elif tok == '[[':
a += 1
elif tok == ']]':
a -= 1
eaten_tokens.append(tokens[0])
tokens = tokens[1:]
l -= 1
# do not return empty tokens, the parser do not like that
return eaten_tokens, [None]
def format_param(param):
typename, name, defparam = param
typename = type_map.get(typename, typename)
if typename in reference_parameter_types:
res = "%s const &%s" % (typename, name)
else:
res = "%s %s" % (typename, name)
if defparam:
res += " = %s" % defparam
return res
def parse_prototype(sigparser, decl, prototypes):
"""Get the C++ prototype for a given function declaration."""
# poor man's scanner :-)
tokens = re.sub(r'[,()]', lambda m: ' ' + m.group(0) + ' ', decl).split()
tokens, ret_type = sigparser.get_type(tokens)
name = tokens[0]
if tokens[1] != '(':
error("unknown token '" + tokens[1] + "' while processing '" + decl + "': '(' expected")
sys.exit(1)
tokens = tokens[2:]
params = []
if tokens[0] != ')':
while True:
tokens, t = sigparser.get_type(tokens)
paramname = tokens[0]
tokens = tokens[1:]
if tokens[0] == '=':
# default argument
defarg, tokens = eat_until({',':None, ')':None}, tokens[1:])
else:
defarg = []
params.append((t, paramname, ''.join(defarg)))
if tokens[0] == ')':
break
if tokens[0] != ',':
error("unknown token '" + tokens[1] + "' while processing '"
+ decl + "': ',' expected")
sys.exit(1)
# skip the comma
tokens = tokens[1:]
ret_type = type_map.get(ret_type, ret_type)
prototype = "%s %s(%s);" % (ret_type, name, ", ".join(map(format_param, params)))
if "[" in ret_type or name == "transpose" or "[<N>]" in prototype or "color " in prototype:
prototype = "// %s (not supported yet)" % prototype
prototypes.append(prototype)
def print_wrapped(parser, fileobj, line, wrap_pos = 99):
"""print the given line (provided without newline at end) and wrap it at wrap_pos,
splitting the line at commas. Also handles commented out lines."""
orig_line = line
prefix = ""
next_prefix = "// " if line.startswith("//") else " "
while parser.indent * 4 + len(prefix) + len(line) >= wrap_pos:
splitpos = line.rfind(',', 0, wrap_pos - parser.indent * 4 - len(prefix))
if splitpos == -1:
raise Exception("Unable to split line: %s" % orig_line)
parser.write(fileobj, prefix + line[:splitpos + 1] + "\n")
line = line[splitpos + 1:].lstrip()
prefix = next_prefix
parser.write(fileobj, prefix + line + "\n")
def usage(args):
"""print usage info and exit"""
print "Usage: %s stdlib_directory outputfile" % args[0]
return 1
def main(args):
"""Process one file and generate signatures."""
if len(args) != 3:
return usage(args)
stdlib_dir = args[1]
out_name = args[2]
strict = True
prototypes = []
# monkey patch SignatureParser to generate signature names suitable for C++ header files
SignatureParser.get_signature = (
lambda self, decl: parse_prototype(self, decl, prototypes))
try:
parser = SignatureParser(args[0], stdlib_dir, out_name, strict)
# copy the copyright from first 3 lines of state.cpp
state_cpp_path = os.path.join(os.path.dirname(out_name), "state.cpp")
with open(state_cpp_path) as f:
copyright = "".join([next(f) for x in xrange(3)])
with open(out_name, "w") as f:
parser.write(f, copyright)
parser.write(f, "\n#ifndef MDL_USER_MODULES_MDL_RUNTIME_H\n"
"#define MDL_USER_MODULES_MDL_RUNTIME_H\n")
for module_name in ["math", "debug"]:
# clear list before parsing next module
del prototypes[:]
parser.parse(module_name)
parser.write(f, "\nnamespace %s\n" % module_name)
parser.write(f, "{\n")
parser.indent += 1
for prototype in prototypes:
print_wrapped(parser, f, prototype)
parser.indent -= 1
parser.write(f, "}\n")
parser.write(f, "\n#endif // MDL_USER_MODULES_MDL_RUNTIME_H\n")
except Exception as e:
error(str(e))
return 1
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
| MDL-SDK-master | src/mdl/jit/generator_jit/gen_user_modules_runtime_header.py |
#!/usr/bin/env python
#*****************************************************************************
# Copyright (c) 2019-2023, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#*****************************************************************************
# This script generates libmdlrt_bitcode.h from libmdlrt.bc
import sys
import os
copyright_str = """
/******************************************************************************
* Copyright 2023 NVIDIA Corporation. All rights reserved.
*****************************************************************************/
"""
def xxd(filename, fout):
f = open(filename, "rb")
bytes = f.read()
i = 0
fout.write("\t")
for byte in bytes:
if isinstance(byte, str):
byte = ord(byte)
fout.write("0x%02x, " % byte)
if i == 7:
fout.write("\n\t")
i = 0
else:
i += 1
def usage():
print("Usage: %s <inputfile> <output directory>" % sys.argv[0])
return 1
def main(args):
if len(args) != 3:
return usage()
bc_name = args[1]
IntDir = args[2]
out_name = "libmdlrt_bitcode.h"
print("Generating %s ..." % out_name)
with open(os.path.join(IntDir, out_name), "w") as f:
f.write(copyright_str)
f.write("\n// Automatically generated from libmdlrt.bc\n\n"
"static unsigned char const libmdlrt_bitcode[] = {\n")
xxd(bc_name, f)
f.write("};\n")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
| MDL-SDK-master | src/mdl/jit/generator_jit/gen_libmdlrt.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.