Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/utils/lit/tests/Inputs
repos/DirectXShaderCompiler/utils/lit/tests/Inputs/shtest-shell/error-0.txt
# Check error on an internal shell error (unable to find command). # # RUN: not-a-real-command
0
repos/DirectXShaderCompiler/utils/lit/tests/Inputs
repos/DirectXShaderCompiler/utils/lit/tests/Inputs/shtest-shell/error-1.txt
# Check error on a shell parsing failure. # # RUN: echo "missing quote
0
repos/DirectXShaderCompiler/utils/lit/tests/Inputs
repos/DirectXShaderCompiler/utils/lit/tests/Inputs/shtest-shell/redirects.txt
# Check stdout redirect (> and >>). # # RUN: echo "not-present" > %t.stdout-write # RUN: echo "is-present" > %t.stdout-write # RUN: FileCheck --check-prefix=STDOUT-WRITE < %t.stdout-write %s # # STDOUT-WRITE-NOT: not-present # STDOUT-WRITE: is-present # # RUN: echo "appended-line" >> %t.stdout-write # RUN: FileCheck --check-prefix=STDOUT-APPEND < %t.stdout-write %s # # STDOUT-APPEND: is-present # STDOUT-APPEND: appended-line # Check stderr redirect (2> and 2>>). # # RUN: echo "not-present" > %t.stderr-write # RUN: %S/write-to-stderr.sh 2> %t.stderr-write # RUN: FileCheck --check-prefix=STDERR-WRITE < %t.stderr-write %s # # STDERR-WRITE-NOT: not-present # STDERR-WRITE: a line on stderr # # RUN: %S/write-to-stderr.sh 2>> %t.stderr-write # RUN: FileCheck --check-prefix=STDERR-APPEND < %t.stderr-write %s # # STDERR-APPEND: a line on stderr # STDERR-APPEND: a line on stderr # Check combined redirect (&>). # # RUN: echo "not-present" > %t.combined # RUN: %S/write-to-stdout-and-stderr.sh &> %t.combined # RUN: FileCheck --check-prefix=COMBINED-WRITE < %t.combined %s # # COMBINED-WRITE-NOT: not-present # COMBINED-WRITE: a line on stdout # COMBINED-WRITE: a line on stderr
0
repos/DirectXShaderCompiler/utils/lit/tests/Inputs
repos/DirectXShaderCompiler/utils/lit/tests/Inputs/shtest-shell/error-2.txt
# Check error on a unsupported redirect. # # RUN: echo "hello" 3>&1
0
repos/DirectXShaderCompiler/utils/lit/tests/Inputs
repos/DirectXShaderCompiler/utils/lit/tests/Inputs/shtest-shell/write-to-stderr.sh
#!/bin/sh echo "a line on stderr" 1>&2
0
repos/DirectXShaderCompiler/utils/lit/tests/Inputs
repos/DirectXShaderCompiler/utils/lit/tests/Inputs/exec-discovery-in-tree/test-one.txt
# RUN: true
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/examples/README.txt
============== lit Examples ============== This directory contains examples of 'lit' test suite configurations. The test suites they define can be run with 'lit examples/example-name', for more details see the README in each example.
0
repos/DirectXShaderCompiler/utils/lit/examples
repos/DirectXShaderCompiler/utils/lit/examples/many-tests/README.txt
======================== Many Tests lit Example ======================== This directory contains a trivial lit test suite configuration that defines a custom test format which just generates a large (N=10000) number of tests that do a small amount of work in the Python test execution code. This test suite is useful for testing the performance of lit on large numbers of tests.
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/utils/README.txt
Utilities for the project that aren't intended to be part of a source distribution.
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/ShCommands.py
class Command: def __init__(self, args, redirects): self.args = list(args) self.redirects = list(redirects) def __repr__(self): return 'Command(%r, %r)' % (self.args, self.redirects) def __eq__(self, other): if not isinstance(other, Command): return False return ((self.args, self.redirects) == (other.args, other.redirects)) def toShell(self, file): for arg in self.args: if "'" not in arg: quoted = "'%s'" % arg elif '"' not in arg and '$' not in arg: quoted = '"%s"' % arg else: raise NotImplementedError('Unable to quote %r' % arg) file.write(quoted) # For debugging / validation. import ShUtil dequoted = list(ShUtil.ShLexer(quoted).lex()) if dequoted != [arg]: raise NotImplementedError('Unable to quote %r' % arg) for r in self.redirects: if len(r[0]) == 1: file.write("%s '%s'" % (r[0][0], r[1])) else: file.write("%s%s '%s'" % (r[0][1], r[0][0], r[1])) class Pipeline: def __init__(self, commands, negate=False, pipe_err=False): self.commands = commands self.negate = negate self.pipe_err = pipe_err def __repr__(self): return 'Pipeline(%r, %r, %r)' % (self.commands, self.negate, self.pipe_err) def __eq__(self, other): if not isinstance(other, Pipeline): return False return ((self.commands, self.negate, self.pipe_err) == (other.commands, other.negate, self.pipe_err)) def toShell(self, file, pipefail=False): if pipefail != self.pipe_err: raise ValueError('Inconsistent "pipefail" attribute!') if self.negate: file.write('! ') for cmd in self.commands: cmd.toShell(file) if cmd is not self.commands[-1]: file.write('|\n ') class Seq: def __init__(self, lhs, op, rhs): assert op in (';', '&', '||', '&&') self.op = op self.lhs = lhs self.rhs = rhs def __repr__(self): return 'Seq(%r, %r, %r)' % (self.lhs, self.op, self.rhs) def __eq__(self, other): if not isinstance(other, Seq): return False return ((self.lhs, self.op, self.rhs) == (other.lhs, other.op, other.rhs)) def toShell(self, file, pipefail=False): self.lhs.toShell(file, pipefail) file.write(' %s\n' % self.op) self.rhs.toShell(file, pipefail)
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/ShUtil.py
from __future__ import absolute_import import itertools import lit.util from lit.ShCommands import Command, Pipeline, Seq class ShLexer: def __init__(self, data, win32Escapes = False): self.data = data self.pos = 0 self.end = len(data) self.win32Escapes = win32Escapes def eat(self): c = self.data[self.pos] self.pos += 1 return c def look(self): return self.data[self.pos] def maybe_eat(self, c): """ maybe_eat(c) - Consume the character c if it is the next character, returning True if a character was consumed. """ if self.data[self.pos] == c: self.pos += 1 return True return False def lex_arg_fast(self, c): # Get the leading whitespace free section. chunk = self.data[self.pos - 1:].split(None, 1)[0] # If it has special characters, the fast path failed. if ('|' in chunk or '&' in chunk or '<' in chunk or '>' in chunk or "'" in chunk or '"' in chunk or ';' in chunk or '\\' in chunk): return None self.pos = self.pos - 1 + len(chunk) return chunk def lex_arg_slow(self, c): if c in "'\"": str = self.lex_arg_quoted(c) else: str = c while self.pos != self.end: c = self.look() if c.isspace() or c in "|&;": break elif c in '><': # This is an annoying case; we treat '2>' as a single token so # we don't have to track whitespace tokens. # If the parse string isn't an integer, do the usual thing. if not str.isdigit(): break # Otherwise, lex the operator and convert to a redirection # token. num = int(str) tok = self.lex_one_token() assert isinstance(tok, tuple) and len(tok) == 1 return (tok[0], num) elif c == '"': self.eat() str += self.lex_arg_quoted('"') elif c == "'": self.eat() str += self.lex_arg_quoted("'") elif not self.win32Escapes and c == '\\': # Outside of a string, '\\' escapes everything. self.eat() if self.pos == self.end: lit.util.warning( "escape at end of quoted argument in: %r" % self.data) return str str += self.eat() else: str += self.eat() return str def lex_arg_quoted(self, delim): str = '' while self.pos != self.end: c = self.eat() if c == delim: return str elif c == '\\' and delim == '"': # Inside a '"' quoted string, '\\' only escapes the quote # character and backslash, otherwise it is preserved. if self.pos == self.end: lit.util.warning( "escape at end of quoted argument in: %r" % self.data) return str c = self.eat() if c == '"': # str += '"' elif c == '\\': str += '\\' else: str += '\\' + c else: str += c lit.util.warning("missing quote character in %r" % self.data) return str def lex_arg_checked(self, c): pos = self.pos res = self.lex_arg_fast(c) end = self.pos self.pos = pos reference = self.lex_arg_slow(c) if res is not None: if res != reference: raise ValueError("Fast path failure: %r != %r" % ( res, reference)) if self.pos != end: raise ValueError("Fast path failure: %r != %r" % ( self.pos, end)) return reference def lex_arg(self, c): return self.lex_arg_fast(c) or self.lex_arg_slow(c) def lex_one_token(self): """ lex_one_token - Lex a single 'sh' token. """ c = self.eat() if c == ';': return (c,) if c == '|': if self.maybe_eat('|'): return ('||',) return (c,) if c == '&': if self.maybe_eat('&'): return ('&&',) if self.maybe_eat('>'): return ('&>',) return (c,) if c == '>': if self.maybe_eat('&'): return ('>&',) if self.maybe_eat('>'): return ('>>',) return (c,) if c == '<': if self.maybe_eat('&'): return ('<&',) if self.maybe_eat('>'): return ('<<',) return (c,) return self.lex_arg(c) def lex(self): while self.pos != self.end: if self.look().isspace(): self.eat() else: yield self.lex_one_token() ### class ShParser: def __init__(self, data, win32Escapes = False, pipefail = False): self.data = data self.pipefail = pipefail self.tokens = ShLexer(data, win32Escapes = win32Escapes).lex() def lex(self): for item in self.tokens: return item return None def look(self): token = self.lex() if token is not None: self.tokens = itertools.chain([token], self.tokens) return token def parse_command(self): tok = self.lex() if not tok: raise ValueError("empty command!") if isinstance(tok, tuple): raise ValueError("syntax error near unexpected token %r" % tok[0]) args = [tok] redirects = [] while 1: tok = self.look() # EOF? if tok is None: break # If this is an argument, just add it to the current command. if isinstance(tok, str): args.append(self.lex()) continue # Otherwise see if it is a terminator. assert isinstance(tok, tuple) if tok[0] in ('|',';','&','||','&&'): break # Otherwise it must be a redirection. op = self.lex() arg = self.lex() if not arg: raise ValueError("syntax error near token %r" % op[0]) redirects.append((op, arg)) return Command(args, redirects) def parse_pipeline(self): negate = False commands = [self.parse_command()] while self.look() == ('|',): self.lex() commands.append(self.parse_command()) return Pipeline(commands, negate, self.pipefail) def parse(self): lhs = self.parse_pipeline() while self.look(): operator = self.lex() assert isinstance(operator, tuple) and len(operator) == 1 if not self.look(): raise ValueError( "missing argument to operator %r" % operator[0]) # FIXME: Operator precedence!! lhs = Seq(lhs, operator[0], self.parse_pipeline()) return lhs ### import unittest 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()
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/LitConfig.py
from __future__ import absolute_import import inspect import os import sys import lit.Test import lit.formats import lit.TestingConfig import lit.util class LitConfig: """LitConfig - Configuration data for a 'lit' test runner instance, shared across all tests. The LitConfig object is also used to communicate with client configuration files, it is always passed in as the global variable 'lit' so that configuration files can access common functionality and internal components easily. """ def __init__(self, progname, path, quiet, useValgrind, valgrindLeakCheck, valgrindArgs, noExecute, debug, isWindows, params, config_prefix = None): # The name of the test runner. self.progname = progname # The items to add to the PATH environment variable. self.path = [str(p) for p in path] self.quiet = bool(quiet) self.useValgrind = bool(useValgrind) self.valgrindLeakCheck = bool(valgrindLeakCheck) self.valgrindUserArgs = list(valgrindArgs) self.noExecute = noExecute self.debug = debug self.isWindows = bool(isWindows) self.params = dict(params) self.bashPath = None # Configuration files to look for when discovering test suites. self.config_prefix = config_prefix or 'lit' self.config_name = '%s.cfg' % (self.config_prefix,) self.site_config_name = '%s.site.cfg' % (self.config_prefix,) self.local_config_name = '%s.local.cfg' % (self.config_prefix,) self.numErrors = 0 self.numWarnings = 0 self.valgrindArgs = [] if self.useValgrind: self.valgrindArgs = ['valgrind', '-q', '--run-libc-freeres=no', '--tool=memcheck', '--trace-children=yes', '--error-exitcode=123'] if self.valgrindLeakCheck: self.valgrindArgs.append('--leak-check=full') else: # The default is 'summary'. self.valgrindArgs.append('--leak-check=no') self.valgrindArgs.extend(self.valgrindUserArgs) def load_config(self, config, path): """load_config(config, path) - Load a config object from an alternate path.""" if self.debug: self.note('load_config from %r' % path) config.load_from_path(path, self) return config def getBashPath(self): """getBashPath - Get the path to 'bash'""" if self.bashPath is not None: return self.bashPath self.bashPath = lit.util.which('bash', os.pathsep.join(self.path)) if self.bashPath is None: self.bashPath = lit.util.which('bash') if self.bashPath is None: self.bashPath = '' return self.bashPath def getToolsPath(self, dir, paths, tools): if dir is not None and os.path.isabs(dir) and os.path.isdir(dir): if not lit.util.checkToolsPath(dir, tools): return None else: dir = lit.util.whichTools(tools, paths) # bash self.bashPath = lit.util.which('bash', dir) if self.bashPath is None: self.bashPath = '' return dir def _write_message(self, kind, message): # Get the file/line where this message was generated. f = inspect.currentframe() # Step out of _write_message, and then out of wrapper. f = f.f_back.f_back file,line,_,_,_ = inspect.getframeinfo(f) location = '%s:%d' % (os.path.basename(file), line) sys.stderr.write('%s: %s: %s: %s\n' % (self.progname, location, kind, message)) def note(self, message): self._write_message('note', message) def warning(self, message): self._write_message('warning', message) self.numWarnings += 1 def error(self, message): self._write_message('error', message) self.numErrors += 1 def fatal(self, message): self._write_message('fatal', message) sys.exit(2)
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/main.py
#!/usr/bin/env python """ lit - LLVM Integrated Tester. See lit.pod for more information. """ from __future__ import absolute_import import math, os, platform, random, re, sys, time import lit.ProgressBar import lit.LitConfig import lit.Test import lit.run import lit.util import lit.discovery class TestingProgressDisplay(object): def __init__(self, opts, numTests, progressBar=None): self.opts = opts self.numTests = numTests self.current = None self.progressBar = progressBar self.completed = 0 def finish(self): if self.progressBar: self.progressBar.clear() elif self.opts.quiet: pass elif self.opts.succinct: sys.stdout.write('\n') def update(self, test): self.completed += 1 if self.opts.incremental: update_incremental_cache(test) if self.progressBar: self.progressBar.update(float(self.completed)/self.numTests, test.getFullName()) shouldShow = test.result.code.isFailure or \ (not self.opts.quiet and not self.opts.succinct) if not shouldShow: return if self.progressBar: self.progressBar.clear() # Show the test result line. test_name = test.getFullName() print('%s: %s (%d of %d)' % (test.result.code.name, test_name, self.completed, self.numTests)) # Show the test failure output, if requested. if test.result.code.isFailure and self.opts.showOutput: print("%s TEST '%s' FAILED %s" % ('*'*20, test.getFullName(), '*'*20)) print(test.result.output) print("*" * 20) if self.opts.showAllOutput: print(test.result.output) # Report test metrics, if present. if test.result.metrics: print("%s TEST '%s' RESULTS %s" % ('*'*10, test.getFullName(), '*'*10)) items = sorted(test.result.metrics.items()) for metric_name, value in items: print('%s: %s ' % (metric_name, value.format())) print("*" * 10) # Ensure the output is flushed. sys.stdout.flush() def write_test_results(run, lit_config, testing_time, output_path): try: import json except ImportError: lit_config.fatal('test output unsupported with Python 2.5') # Construct the data we will write. data = {} # Encode the current lit version as a schema version. data['__version__'] = lit.__versioninfo__ data['elapsed'] = testing_time # FIXME: Record some information on the lit configuration used? # FIXME: Record information from the individual test suites? # Encode the tests. data['tests'] = tests_data = [] for test in run.tests: test_data = { 'name' : test.getFullName(), 'code' : test.result.code.name, 'output' : test.result.output, 'elapsed' : test.result.elapsed } # Add test metrics, if present. if test.result.metrics: test_data['metrics'] = metrics_data = {} for key, value in test.result.metrics.items(): metrics_data[key] = value.todata() tests_data.append(test_data) # Write the output. f = open(output_path, 'w') try: json.dump(data, f, indent=2, sort_keys=True) f.write('\n') finally: f.close() def update_incremental_cache(test): if not test.result.code.isFailure: return fname = test.getFilePath() os.utime(fname, None) def sort_by_incremental_cache(run): def sortIndex(test): fname = test.getFilePath() try: return -os.path.getmtime(fname) except: return 0 run.tests.sort(key = lambda t: sortIndex(t)) def main(builtinParameters = {}): # Use processes by default on Unix platforms. isWindows = platform.system() == 'Windows' useProcessesIsDefault = not isWindows global options from optparse import OptionParser, OptionGroup parser = OptionParser("usage: %prog [options] {file-or-path}") parser.add_option("", "--version", dest="show_version", help="Show version and exit", action="store_true", default=False) parser.add_option("-j", "--threads", dest="numThreads", metavar="N", help="Number of testing threads", type=int, action="store", default=None) parser.add_option("", "--config-prefix", dest="configPrefix", metavar="NAME", help="Prefix for 'lit' config files", action="store", default=None) parser.add_option("-D", "--param", dest="userParameters", metavar="NAME=VAL", help="Add 'NAME' = 'VAL' to the user defined parameters", type=str, action="append", default=[]) group = OptionGroup(parser, "Output Format") # FIXME: I find these names very confusing, although I like the # functionality. group.add_option("-q", "--quiet", dest="quiet", help="Suppress no error output", action="store_true", default=False) group.add_option("-s", "--succinct", dest="succinct", help="Reduce amount of output", action="store_true", default=False) group.add_option("-v", "--verbose", dest="showOutput", help="Show all test output", action="store_true", default=False) group.add_option("-a", "--show-all", dest="showAllOutput", help="Display all commandlines and output", action="store_true", default=False) group.add_option("-o", "--output", dest="output_path", help="Write test results to the provided path", action="store", type=str, metavar="PATH") group.add_option("", "--no-progress-bar", dest="useProgressBar", help="Do not use curses based progress bar", action="store_false", default=True) group.add_option("", "--show-unsupported", dest="show_unsupported", help="Show unsupported tests", action="store_true", default=False) group.add_option("", "--show-xfail", dest="show_xfail", help="Show tests that were expected to fail", action="store_true", default=False) parser.add_option_group(group) group = OptionGroup(parser, "Test Execution") group.add_option("", "--path", dest="path", help="Additional paths to add to testing environment", action="append", type=str, default=[]) group.add_option("", "--vg", dest="useValgrind", help="Run tests under valgrind", action="store_true", default=False) group.add_option("", "--vg-leak", dest="valgrindLeakCheck", help="Check for memory leaks under valgrind", action="store_true", default=False) group.add_option("", "--vg-arg", dest="valgrindArgs", metavar="ARG", help="Specify an extra argument for valgrind", type=str, action="append", default=[]) group.add_option("", "--time-tests", dest="timeTests", help="Track elapsed wall time for each test", action="store_true", default=False) group.add_option("", "--no-execute", dest="noExecute", help="Don't execute any tests (assume PASS)", action="store_true", default=False) group.add_option("", "--xunit-xml-output", dest="xunit_output_file", help=("Write XUnit-compatible XML test reports to the" " specified file"), default=None) parser.add_option_group(group) group = OptionGroup(parser, "Test Selection") group.add_option("", "--max-tests", dest="maxTests", metavar="N", help="Maximum number of tests to run", action="store", type=int, default=None) group.add_option("", "--max-time", dest="maxTime", metavar="N", help="Maximum time to spend testing (in seconds)", action="store", type=float, default=None) group.add_option("", "--shuffle", dest="shuffle", help="Run tests in random order", action="store_true", default=False) group.add_option("-i", "--incremental", dest="incremental", help="Run modified and failing tests first (updates " "mtimes)", action="store_true", default=False) group.add_option("", "--filter", dest="filter", metavar="REGEX", help=("Only run tests with paths matching the given " "regular expression"), action="store", default=None) parser.add_option_group(group) group = OptionGroup(parser, "Debug and Experimental Options") group.add_option("", "--debug", dest="debug", help="Enable debugging (for 'lit' development)", action="store_true", default=False) group.add_option("", "--show-suites", dest="showSuites", help="Show discovered test suites", action="store_true", default=False) group.add_option("", "--show-tests", dest="showTests", help="Show all discovered tests", action="store_true", default=False) group.add_option("", "--use-processes", dest="useProcesses", help="Run tests in parallel with processes (not threads)", action="store_true", default=useProcessesIsDefault) group.add_option("", "--use-threads", dest="useProcesses", help="Run tests in parallel with threads (not processes)", action="store_false", default=useProcessesIsDefault) group.add_option("", "--xml-include-test-output", dest="xmlIncludeTestOutput", help="Include system out in xml output for all tests", action="store_true", default=False) parser.add_option_group(group) (opts, args) = parser.parse_args() if opts.show_version: print("lit %s" % (lit.__version__,)) return if not args: parser.error('No inputs specified') if opts.numThreads is None: # Python <2.5 has a race condition causing lit to always fail with numThreads>1 # http://bugs.python.org/issue1731717 # I haven't seen this bug occur with 2.5.2 and later, so only enable multiple # threads by default there. if sys.hexversion >= 0x2050200: opts.numThreads = lit.util.detectCPUs() else: opts.numThreads = 1 inputs = args # Create the user defined parameters. userParams = dict(builtinParameters) for entry in opts.userParameters: if '=' not in entry: name,val = entry,'' else: name,val = entry.split('=', 1) userParams[name] = val # Create the global config object. litConfig = lit.LitConfig.LitConfig( progname = os.path.basename(sys.argv[0]), path = opts.path, quiet = opts.quiet, useValgrind = opts.useValgrind, valgrindLeakCheck = opts.valgrindLeakCheck, valgrindArgs = opts.valgrindArgs, noExecute = opts.noExecute, debug = opts.debug, isWindows = isWindows, params = userParams, config_prefix = opts.configPrefix) # Perform test discovery. run = lit.run.Run(litConfig, lit.discovery.find_tests_for_inputs(litConfig, inputs)) if opts.showSuites or opts.showTests: # Aggregate the tests by suite. suitesAndTests = {} for result_test in run.tests: if result_test.suite not in suitesAndTests: suitesAndTests[result_test.suite] = [] suitesAndTests[result_test.suite].append(result_test) suitesAndTests = list(suitesAndTests.items()) suitesAndTests.sort(key = lambda item: item[0].name) # Show the suites, if requested. if opts.showSuites: print('-- Test Suites --') for ts,ts_tests in suitesAndTests: print(' %s - %d tests' %(ts.name, len(ts_tests))) print(' Source Root: %s' % ts.source_root) print(' Exec Root : %s' % ts.exec_root) # Show the tests, if requested. if opts.showTests: print('-- Available Tests --') for ts,ts_tests in suitesAndTests: ts_tests.sort(key = lambda test: test.path_in_suite) for test in ts_tests: print(' %s' % (test.getFullName(),)) # Exit. sys.exit(0) # Select and order the tests. numTotalTests = len(run.tests) # First, select based on the filter expression if given. if opts.filter: try: rex = re.compile(opts.filter) except: parser.error("invalid regular expression for --filter: %r" % ( opts.filter)) run.tests = [result_test for result_test in run.tests if rex.search(result_test.getFullName())] # Then select the order. if opts.shuffle: random.shuffle(run.tests) elif opts.incremental: sort_by_incremental_cache(run) else: run.tests.sort(key = lambda result_test: result_test.getFullName()) # Finally limit the number of tests, if desired. if opts.maxTests is not None: run.tests = run.tests[:opts.maxTests] # Don't create more threads than tests. opts.numThreads = min(len(run.tests), opts.numThreads) extra = '' if len(run.tests) != numTotalTests: extra = ' of %d' % numTotalTests header = '-- Testing: %d%s tests, %d threads --'%(len(run.tests), extra, opts.numThreads) progressBar = None if not opts.quiet: if opts.succinct and opts.useProgressBar: try: tc = lit.ProgressBar.TerminalController() progressBar = lit.ProgressBar.ProgressBar(tc, header) except ValueError: print(header) progressBar = lit.ProgressBar.SimpleProgressBar('Testing: ') else: print(header) startTime = time.time() display = TestingProgressDisplay(opts, len(run.tests), progressBar) try: run.execute_tests(display, opts.numThreads, opts.maxTime, opts.useProcesses) except KeyboardInterrupt: sys.exit(2) display.finish() testing_time = time.time() - startTime if not opts.quiet: print('Testing Time: %.2fs' % (testing_time,)) # Write out the test data, if requested. if opts.output_path is not None: write_test_results(run, litConfig, testing_time, opts.output_path) # List test results organized by kind. hasFailures = False byCode = {} for test in run.tests: if test.result.code not in byCode: byCode[test.result.code] = [] byCode[test.result.code].append(test) if test.result.code.isFailure: hasFailures = True # Print each test in any of the failing groups. for title,code in (('Unexpected Passing Tests', lit.Test.XPASS), ('Failing Tests', lit.Test.FAIL), ('Unresolved Tests', lit.Test.UNRESOLVED), ('Unsupported Tests', lit.Test.UNSUPPORTED), ('Expected Failing Tests', lit.Test.XFAIL)): if (lit.Test.XFAIL == code and not opts.show_xfail) or \ (lit.Test.UNSUPPORTED == code and not opts.show_unsupported): continue elts = byCode.get(code) if not elts: continue print('*'*20) print('%s (%d):' % (title, len(elts))) for test in elts: print(' %s' % test.getFullName()) sys.stdout.write('\n') if opts.timeTests and run.tests: # Order by time. test_times = [(test.getFullName(), test.result.elapsed) for test in run.tests] lit.util.printHistogram(test_times, title='Tests') for name,code in (('Expected Passes ', lit.Test.PASS), ('Expected Failures ', lit.Test.XFAIL), ('Unsupported Tests ', lit.Test.UNSUPPORTED), ('Unresolved Tests ', lit.Test.UNRESOLVED), ('Unexpected Passes ', lit.Test.XPASS), ('Unexpected Failures', lit.Test.FAIL)): if opts.quiet and not code.isFailure: continue N = len(byCode.get(code,[])) if N: print(' %s: %d' % (name,N)) if opts.xunit_output_file: # Collect the tests, indexed by test suite by_suite = {} for result_test in run.tests: suite = result_test.suite.config.name if suite not in by_suite: by_suite[suite] = { 'passes' : 0, 'failures' : 0, 'tests' : [] } by_suite[suite]['tests'].append(result_test) if result_test.result.code.isFailure: by_suite[suite]['failures'] += 1 else: by_suite[suite]['passes'] += 1 xunit_output_file = open(opts.xunit_output_file, "w", encoding="utf-8", errors="xmlcharrefreplace") xunit_output_file.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") xunit_output_file.write("<testsuites>\n") for suite_name, suite in by_suite.items(): safe_suite_name = suite_name.replace(".", "-") xunit_output_file.write("<testsuite name='" + safe_suite_name + "'") xunit_output_file.write(" tests='" + str(suite['passes'] + suite['failures']) + "'") xunit_output_file.write(" failures='" + str(suite['failures']) + "'>\n") for result_test in suite['tests']: xunit_output_file.write(result_test.getJUnitXML(opts.xmlIncludeTestOutput) + "\n") xunit_output_file.write("</testsuite>\n") xunit_output_file.write("</testsuites>") xunit_output_file.close() # If we encountered any additional errors, exit abnormally. if litConfig.numErrors: sys.stderr.write('\n%d error(s), exiting.\n' % litConfig.numErrors) sys.exit(2) # Warn about warnings. if litConfig.numWarnings: sys.stderr.write('\n%d warning(s) in tests.\n' % litConfig.numWarnings) if hasFailures: sys.exit(1) sys.exit(0) if __name__=='__main__': main()
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/__init__.py
"""'lit' Testing Tool""" from __future__ import absolute_import from .main import main __author__ = 'Daniel Dunbar' __email__ = '[email protected]' __versioninfo__ = (0, 5, 0) __version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev' __all__ = []
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/TestingConfig.py
import os import sys import platform import itertools import lit.util OldPy = sys.version_info[0] == 2 and sys.version_info[1] < 7 def strip_dxil_validator_path(env_path): dxil_name, separator = ('dxil.dll', ';') if platform.system() == 'Windows' else ('dxil.so', ';') return separator.join([ p for p in env_path.split(separator) if not os.path.isfile(os.path.join(p, dxil_name)) ]) def _find_git_windows_unix_tools(tools_needed): assert(sys.platform == 'win32') if sys.version_info.major >= 3: import winreg else: import _winreg as winreg # Search both the 64 and 32-bit hives, as well as HKLM + HKCU masks = [0, winreg.KEY_WOW64_64KEY] hives = [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER] for mask, hive in itertools.product(masks, hives): try: with winreg.OpenKey(hive, r"SOFTWARE\GitForWindows", 0, winreg.KEY_READ | mask) as key: install_root, _ = winreg.QueryValueEx(key, 'InstallPath') if not install_root: continue candidate_path = os.path.join(install_root, 'usr', 'bin') if not lit.util.checkToolsPath( candidate_path, tools_needed): continue # We found it, stop enumerating. return lit.util.to_string(candidate_path) except: continue raise(f"fail to find {tools_needed} which are required for DXC tests") class TestingConfig: """" TestingConfig - Information on the tests inside a suite. """ @staticmethod def fromdefaults(litConfig): """ fromdefaults(litConfig) -> TestingConfig Create a TestingConfig object with default values. """ # Set the environment based on the command line arguments. # strip dxil validator dir if not need it. all_path = os.pathsep.join(litConfig.path + [os.environ.get('PATH','')]) all_path = strip_dxil_validator_path(all_path) if sys.platform == 'win32': required_tools = [ 'cmp.exe', 'grep.exe', 'sed.exe', 'diff.exe', 'echo.exe', 'ls.exe'] path = lit.util.whichTools(required_tools, all_path) if path is None: path = _find_git_windows_unix_tools(required_tools) all_path = f"{path};{all_path}" environment = { 'PATH' : all_path, 'LLVM_DISABLE_CRASH_REPORT' : '1', } pass_vars = ['LIBRARY_PATH', 'LD_LIBRARY_PATH', 'SYSTEMROOT', 'TERM', 'LD_PRELOAD', 'ASAN_OPTIONS', 'UBSAN_OPTIONS', 'LSAN_OPTIONS', 'ADB', 'ADB_SERIAL'] for var in pass_vars: val = os.environ.get(var, '') # Check for empty string as some variables such as LD_PRELOAD cannot be empty # ('') for OS's such as OpenBSD. if val: environment[var] = val if sys.platform == 'win32': environment.update({ 'INCLUDE' : os.environ.get('INCLUDE',''), 'PATHEXT' : os.environ.get('PATHEXT',''), 'PYTHONUNBUFFERED' : '1', 'USERPROFILE' : os.environ.get('USERPROFILE',''), 'TEMP' : os.environ.get('TEMP',''), 'TMP' : os.environ.get('TMP',''), }) # The option to preserve TEMP, TMP, and TMPDIR. # This is intended to check how many temporary files would be generated # (and be not cleaned up) in automated builders. if 'LIT_PRESERVES_TMP' in os.environ: environment.update({ 'TEMP' : os.environ.get('TEMP',''), 'TMP' : os.environ.get('TMP',''), 'TMPDIR' : os.environ.get('TMPDIR',''), }) # Set the default available features based on the LitConfig. available_features = [] if litConfig.useValgrind: available_features.append('valgrind') if litConfig.valgrindLeakCheck: available_features.append('vg_leak') return TestingConfig(None, name = '<unnamed>', suffixes = set(), test_format = None, environment = environment, substitutions = [], unsupported = False, test_exec_root = None, test_source_root = None, excludes = [], available_features = available_features, pipefail = True) def load_from_path(self, path, litConfig): """ load_from_path(path, litConfig) Load the configuration module at the provided path into the given config object. """ # Load the config script data. data = None if not OldPy: f = open(path) try: data = f.read() except: litConfig.fatal('unable to load config file: %r' % (path,)) f.close() # Execute the config script to initialize the object. cfg_globals = dict(globals()) cfg_globals['config'] = self cfg_globals['lit_config'] = litConfig cfg_globals['__file__'] = path try: if OldPy: execfile(path, cfg_globals) else: exec(compile(data, path, 'exec'), cfg_globals, None) if litConfig.debug: litConfig.note('... loaded config %r' % path) except SystemExit: e = sys.exc_info()[1] # We allow normal system exit inside a config file to just # return control without error. if e.args: raise except: import traceback litConfig.fatal( 'unable to parse config file %r, traceback: %s' % ( path, traceback.format_exc())) self.finish(litConfig) def __init__(self, parent, name, suffixes, test_format, environment, substitutions, unsupported, test_exec_root, test_source_root, excludes, available_features, pipefail, limit_to_features = []): self.parent = parent self.name = str(name) self.suffixes = set(suffixes) self.test_format = test_format self.environment = dict(environment) self.substitutions = list(substitutions) self.unsupported = unsupported self.test_exec_root = test_exec_root self.test_source_root = test_source_root self.excludes = set(excludes) self.available_features = set(available_features) self.pipefail = pipefail # This list is used by TestRunner.py to restrict running only tests that # require one of the features in this list if this list is non-empty. # Configurations can set this list to restrict the set of tests to run. self.limit_to_features = set(limit_to_features) def finish(self, litConfig): """finish() - Finish this config object, after loading is complete.""" self.name = str(self.name) self.suffixes = set(self.suffixes) self.environment = dict(self.environment) self.substitutions = list(self.substitutions) if self.test_exec_root is not None: # FIXME: This should really only be suite in test suite config # files. Should we distinguish them? self.test_exec_root = str(self.test_exec_root) if self.test_source_root is not None: # FIXME: This should really only be suite in test suite config # files. Should we distinguish them? self.test_source_root = str(self.test_source_root) self.excludes = set(self.excludes) @property def root(self): """root attribute - The root configuration for the test suite.""" if self.parent is None: return self else: return self.parent.root
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/run.py
import os import threading import time import traceback try: import Queue as queue except ImportError: import queue try: import win32api except ImportError: win32api = None try: import multiprocessing except ImportError: multiprocessing = None import lit.Test ### # Test Execution Implementation class LockedValue(object): def __init__(self, value): self.lock = threading.Lock() self._value = value def _get_value(self): self.lock.acquire() try: return self._value finally: self.lock.release() def _set_value(self, value): self.lock.acquire() try: self._value = value finally: self.lock.release() value = property(_get_value, _set_value) class TestProvider(object): def __init__(self, tests, num_jobs, queue_impl, canceled_flag): self.canceled_flag = canceled_flag # Create a shared queue to provide the test indices. self.queue = queue_impl() for i in range(len(tests)): self.queue.put(i) for i in range(num_jobs): self.queue.put(None) def cancel(self): self.canceled_flag.value = 1 def get(self): # Check if we are canceled. if self.canceled_flag.value: return None # Otherwise take the next test. return self.queue.get() class Tester(object): def __init__(self, run_instance, provider, consumer): self.run_instance = run_instance self.provider = provider self.consumer = consumer def run(self): while True: item = self.provider.get() if item is None: break self.run_test(item) self.consumer.task_finished() def run_test(self, test_index): test = self.run_instance.tests[test_index] try: self.run_instance.execute_test(test) except KeyboardInterrupt: # This is a sad hack. Unfortunately subprocess goes # bonkers with ctrl-c and we start forking merrily. print('\nCtrl-C detected, goodbye.') os.kill(0,9) self.consumer.update(test_index, test) class ThreadResultsConsumer(object): def __init__(self, display): self.display = display self.lock = threading.Lock() def update(self, test_index, test): self.lock.acquire() try: self.display.update(test) finally: self.lock.release() def task_finished(self): pass def handle_results(self): pass class MultiprocessResultsConsumer(object): def __init__(self, run, display, num_jobs): self.run = run self.display = display self.num_jobs = num_jobs self.queue = multiprocessing.Queue() def update(self, test_index, test): # This method is called in the child processes, and communicates the # results to the actual display implementation via an output queue. self.queue.put((test_index, test.result)) def task_finished(self): # This method is called in the child processes, and communicates that # individual tasks are complete. self.queue.put(None) def handle_results(self): # This method is called in the parent, and consumes the results from the # output queue and dispatches to the actual display. The method will # complete after each of num_jobs tasks has signalled completion. completed = 0 while completed != self.num_jobs: # Wait for a result item. item = self.queue.get() if item is None: completed += 1 continue # Update the test result in the parent process. index,result = item test = self.run.tests[index] test.result = result self.display.update(test) def run_one_tester(run, provider, display): tester = Tester(run, provider, display) tester.run() ### class Run(object): """ This class represents a concrete, configured testing run. """ def __init__(self, lit_config, tests): self.lit_config = lit_config self.tests = tests def execute_test(self, test): result = None start_time = time.time() try: result = test.config.test_format.execute(test, self.lit_config) # Support deprecated result from execute() which returned the result # code and additional output as a tuple. if isinstance(result, tuple): code, output = result result = lit.Test.Result(code, output) elif not isinstance(result, lit.Test.Result): raise ValueError("unexpected result from test execution") except KeyboardInterrupt: raise except: if self.lit_config.debug: raise output = 'Exception during script execution:\n' output += traceback.format_exc() output += '\n' result = lit.Test.Result(lit.Test.UNRESOLVED, output) result.elapsed = time.time() - start_time test.setResult(result) def execute_tests(self, display, jobs, max_time=None, use_processes=False): """ execute_tests(display, jobs, [max_time]) Execute each of the tests in the run, using up to jobs number of parallel tasks, and inform the display of each individual result. The provided tests should be a subset of the tests available in this run object. If max_time is non-None, it should be a time in seconds after which to stop executing tests. The display object will have its update method called with each test as it is completed. The calls are guaranteed to be locked with respect to one another, but are *not* guaranteed to be called on the same thread as this method was invoked on. Upon completion, each test in the run will have its result computed. Tests which were not actually executed (for any reason) will be given an UNRESOLVED result. """ # Choose the appropriate parallel execution implementation. consumer = None if jobs != 1 and use_processes and multiprocessing: try: task_impl = multiprocessing.Process queue_impl = multiprocessing.Queue canceled_flag = multiprocessing.Value('i', 0) consumer = MultiprocessResultsConsumer(self, display, jobs) except: # multiprocessing fails to initialize with certain OpenBSD and # FreeBSD Python versions: http://bugs.python.org/issue3770 # Unfortunately the error raised also varies by platform. self.lit_config.note('failed to initialize multiprocessing') consumer = None if not consumer: task_impl = threading.Thread queue_impl = queue.Queue canceled_flag = LockedValue(0) consumer = ThreadResultsConsumer(display) # Create the test provider. provider = TestProvider(self.tests, jobs, queue_impl, canceled_flag) # Install a console-control signal handler on Windows. if win32api is not None: def console_ctrl_handler(type): provider.cancel() return True win32api.SetConsoleCtrlHandler(console_ctrl_handler, True) # Install a timeout handler, if requested. if max_time is not None: def timeout_handler(): provider.cancel() timeout_timer = threading.Timer(max_time, timeout_handler) timeout_timer.start() # If not using multiple tasks, just run the tests directly. if jobs == 1: run_one_tester(self, provider, consumer) else: # Otherwise, execute the tests in parallel self._execute_tests_in_parallel(task_impl, provider, consumer, jobs) # Cancel the timeout handler. if max_time is not None: timeout_timer.cancel() # Update results for any tests which weren't run. for test in self.tests: if test.result is None: test.setResult(lit.Test.Result(lit.Test.UNRESOLVED, '', 0.0)) def _execute_tests_in_parallel(self, task_impl, provider, consumer, jobs): # Start all of the tasks. tasks = [task_impl(target=run_one_tester, args=(self, provider, consumer)) for i in range(jobs)] for t in tasks: t.start() # Allow the consumer to handle results, if necessary. consumer.handle_results() # Wait for all the tasks to complete. for t in tasks: t.join()
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/ProgressBar.py
#!/usr/bin/env python # Source: http://code.activestate.com/recipes/475116/, with # modifications by Daniel Dunbar. import sys, re, time def to_bytes(str): # Encode to UTF-8 to get binary data. return str.encode('utf-8') class TerminalController: """ A class that can be used to portably generate formatted output to a terminal. `TerminalController` defines a set of instance variables whose values are initialized to the control sequence necessary to perform a given action. These can be simply included in normal output to the terminal: >>> term = TerminalController() >>> print('This is '+term.GREEN+'green'+term.NORMAL) Alternatively, the `render()` method can used, which replaces '${action}' with the string required to perform 'action': >>> term = TerminalController() >>> print(term.render('This is ${GREEN}green${NORMAL}')) If the terminal doesn't support a given action, then the value of the corresponding instance variable will be set to ''. As a result, the above code will still work on terminals that do not support color, except that their output will not be colored. Also, this means that you can test whether the terminal supports a given action by simply testing the truth value of the corresponding instance variable: >>> term = TerminalController() >>> if term.CLEAR_SCREEN: ... print('This terminal supports clearning the screen.') Finally, if the width and height of the terminal are known, then they will be stored in the `COLS` and `LINES` attributes. """ # Cursor movement: BOL = '' #: Move the cursor to the beginning of the line UP = '' #: Move the cursor up one line DOWN = '' #: Move the cursor down one line LEFT = '' #: Move the cursor left one char RIGHT = '' #: Move the cursor right one char # Deletion: CLEAR_SCREEN = '' #: Clear the screen and move to home position CLEAR_EOL = '' #: Clear to the end of the line. CLEAR_BOL = '' #: Clear to the beginning of the line. CLEAR_EOS = '' #: Clear to the end of the screen # Output modes: BOLD = '' #: Turn on bold mode BLINK = '' #: Turn on blink mode DIM = '' #: Turn on half-bright mode REVERSE = '' #: Turn on reverse-video mode NORMAL = '' #: Turn off all modes # Cursor display: HIDE_CURSOR = '' #: Make the cursor invisible SHOW_CURSOR = '' #: Make the cursor visible # Terminal size: COLS = None #: Width of the terminal (None for unknown) LINES = None #: Height of the terminal (None for unknown) # Foreground colors: BLACK = BLUE = GREEN = CYAN = RED = MAGENTA = YELLOW = WHITE = '' # Background colors: BG_BLACK = BG_BLUE = BG_GREEN = BG_CYAN = '' BG_RED = BG_MAGENTA = BG_YELLOW = BG_WHITE = '' _STRING_CAPABILITIES = """ BOL=cr UP=cuu1 DOWN=cud1 LEFT=cub1 RIGHT=cuf1 CLEAR_SCREEN=clear CLEAR_EOL=el CLEAR_BOL=el1 CLEAR_EOS=ed BOLD=bold BLINK=blink DIM=dim REVERSE=rev UNDERLINE=smul NORMAL=sgr0 HIDE_CURSOR=cinvis SHOW_CURSOR=cnorm""".split() _COLORS = """BLACK BLUE GREEN CYAN RED MAGENTA YELLOW WHITE""".split() _ANSICOLORS = "BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE".split() def __init__(self, term_stream=sys.stdout): """ Create a `TerminalController` and initialize its attributes with appropriate values for the current terminal. `term_stream` is the stream that will be used for terminal output; if this stream is not a tty, then the terminal is assumed to be a dumb terminal (i.e., have no capabilities). """ # Curses isn't available on all platforms try: import curses except: return # If the stream isn't a tty, then assume it has no capabilities. if not term_stream.isatty(): return # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm() except: return # Look up numeric capabilities. self.COLS = curses.tigetnum('cols') self.LINES = curses.tigetnum('lines') self.XN = curses.tigetflag('xenl') # Look up string capabilities. for capability in self._STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(self, attrib, self._tigetstr(cap_name) or '') # Colors set_fg = self._tigetstr('setf') if set_fg: for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, self._tparm(set_fg, i)) set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, self._tparm(set_fg_ansi, i)) set_bg = self._tigetstr('setb') if set_bg: for i,color in zip(range(len(self._COLORS)), self._COLORS): setattr(self, 'BG_'+color, self._tparm(set_bg, i)) set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: for i,color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, 'BG_'+color, self._tparm(set_bg_ansi, i)) def _tparm(self, arg, index): import curses return curses.tparm(to_bytes(arg), index).decode('utf-8') or '' def _tigetstr(self, cap_name): # String capabilities can include "delays" of the form "$<2>". # For any modern terminal, we should be able to just ignore # these, so strip them out. import curses cap = curses.tigetstr(cap_name) if cap is None: cap = '' else: cap = cap.decode('utf-8') return re.sub(r'\$<\d+>[/*]?', '', cap) def render(self, template): """ Replace each $-substitutions in the given template string with the corresponding terminal control string (if it's defined) or '' (if it's not). """ return re.sub(r'\$\$|\${\w+}', self._render_sub, template) def _render_sub(self, match): s = match.group() if s == '$$': return s else: return getattr(self, s[2:-1]) ####################################################################### # Example use case: progress bar ####################################################################### class SimpleProgressBar: """ A simple progress bar which doesn't need any terminal support. This prints out a progress bar like: 'Header: 0 .. 10.. 20.. ...' """ def __init__(self, header): self.header = header self.atIndex = None def update(self, percent, message): if self.atIndex is None: sys.stdout.write(self.header) self.atIndex = 0 next = int(percent*50) if next == self.atIndex: return for i in range(self.atIndex, next): idx = i % 5 if idx == 0: sys.stdout.write('%-2d' % (i*2)) elif idx == 1: pass # Skip second char elif idx < 4: sys.stdout.write('.') else: sys.stdout.write(' ') sys.stdout.flush() self.atIndex = next def clear(self): if self.atIndex is not None: sys.stdout.write('\n') sys.stdout.flush() self.atIndex = None class ProgressBar: """ A 3-line progress bar, which looks like:: Header 20% [===========----------------------------------] progress message The progress bar is colored, if the terminal supports color output; and adjusts to the width of the terminal. """ BAR = '%s${GREEN}[${BOLD}%s%s${NORMAL}${GREEN}]${NORMAL}%s' HEADER = '${BOLD}${CYAN}%s${NORMAL}\n\n' def __init__(self, term, header, useETA=True): self.term = term if not (self.term.CLEAR_EOL and self.term.UP and self.term.BOL): raise ValueError("Terminal isn't capable enough -- you " "should use a simpler progress dispaly.") self.BOL = self.term.BOL # BoL from col#79 self.XNL = "\n" # Newline from col#79 if self.term.COLS: self.width = self.term.COLS if not self.term.XN: self.BOL = self.term.UP + self.term.BOL self.XNL = "" # Cursor must be fed to the next line else: self.width = 75 self.bar = term.render(self.BAR) self.header = self.term.render(self.HEADER % header.center(self.width)) self.cleared = 1 #: true if we haven't drawn the bar yet. self.useETA = useETA if self.useETA: self.startTime = time.time() self.update(0, '') def update(self, percent, message): if self.cleared: sys.stdout.write(self.header) self.cleared = 0 prefix = '%3d%% ' % (percent*100,) suffix = '' if self.useETA: elapsed = time.time() - self.startTime if percent > .0001 and elapsed > 1: total = elapsed / percent eta = int(total - elapsed) h = eta//3600. m = (eta//60) % 60 s = eta % 60 suffix = ' ETA: %02d:%02d:%02d'%(h,m,s) barWidth = self.width - len(prefix) - len(suffix) - 2 n = int(barWidth*percent) if len(message) < self.width: message = message + ' '*(self.width - len(message)) else: message = '... ' + message[-(self.width-4):] sys.stdout.write( self.BOL + self.term.UP + self.term.CLEAR_EOL + (self.bar % (prefix, '='*n, '-'*(barWidth-n), suffix)) + self.XNL + self.term.CLEAR_EOL + message) if not self.term.XN: sys.stdout.flush() def clear(self): if not self.cleared: sys.stdout.write(self.BOL + self.term.CLEAR_EOL + self.term.UP + self.term.CLEAR_EOL + self.term.UP + self.term.CLEAR_EOL) sys.stdout.flush() self.cleared = 1 def test(): tc = TerminalController() p = ProgressBar(tc, 'Tests') for i in range(101): p.update(i/100., str(i)) time.sleep(.3) if __name__=='__main__': test()
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/LitTestCase.py
from __future__ import absolute_import import unittest import lit.Test """ TestCase adaptor for providing a 'unittest' compatible interface to 'lit' tests. """ class UnresolvedError(RuntimeError): pass class LitTestCase(unittest.TestCase): def __init__(self, test, run): unittest.TestCase.__init__(self) self._test = test self._run = run def id(self): return self._test.getFullName() def shortDescription(self): return self._test.getFullName() def runTest(self): # Run the test. self._run.execute_test(self._test) # Adapt the result to unittest. result = self._test.result if result.code is lit.Test.UNRESOLVED: raise UnresolvedError(result.output) elif result.code.isFailure: self.fail(result.output)
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/TestRunner.py
from __future__ import absolute_import import os, signal, subprocess, sys import re import platform import tempfile import lit.ShUtil as ShUtil import lit.Test as Test import lit.util from lit.util import to_bytes, to_string class InternalShellError(Exception): def __init__(self, command, message): self.command = command self.message = message kIsWindows = platform.system() == 'Windows' # Don't use close_fds on Windows. kUseCloseFDs = not kIsWindows # Use temporary files to replace /dev/null on Windows. kAvoidDevNull = kIsWindows class ShellEnvironment(object): """Mutable shell environment containing things like CWD and env vars. Environment variables are not implemented, but cwd tracking is. """ def __init__(self, cwd, env): self.cwd = cwd self.env = env def executeShCmd(cmd, shenv, results): if isinstance(cmd, ShUtil.Seq): if cmd.op == ';': res = executeShCmd(cmd.lhs, shenv, results) return executeShCmd(cmd.rhs, shenv, results) if cmd.op == '&': raise InternalShellError(cmd,"unsupported shell operator: '&'") if cmd.op == '||': res = executeShCmd(cmd.lhs, shenv, results) if res != 0: res = executeShCmd(cmd.rhs, shenv, results) return res if cmd.op == '&&': res = executeShCmd(cmd.lhs, shenv, results) if res is None: return res if res == 0: res = executeShCmd(cmd.rhs, shenv, results) return res raise ValueError('Unknown shell command: %r' % cmd.op) assert isinstance(cmd, ShUtil.Pipeline) # Handle shell builtins first. if cmd.commands[0].args[0] == 'cd': # Update the cwd in the environment. if len(cmd.commands[0].args) != 2: raise ValueError('cd supports only one argument') newdir = cmd.commands[0].args[1] if os.path.isabs(newdir): shenv.cwd = newdir else: shenv.cwd = os.path.join(shenv.cwd, newdir) return 0 procs = [] input = subprocess.PIPE stderrTempFiles = [] opened_files = [] named_temp_files = [] # To avoid deadlock, we use a single stderr stream for piped # output. This is null until we have seen some output using # stderr. for i,j in enumerate(cmd.commands): # Apply the redirections, we use (N,) as a sentinel to indicate stdin, # stdout, stderr for N equal to 0, 1, or 2 respectively. Redirects to or # from a file are represented with a list [file, mode, file-object] # where file-object is initially None. redirects = [(0,), (1,), (2,)] for r in j.redirects: if r[0] == ('>',2): redirects[2] = [r[1], 'w', None] elif r[0] == ('>>',2): redirects[2] = [r[1], 'a', None] elif r[0] == ('>&',2) and r[1] in '012': redirects[2] = redirects[int(r[1])] elif r[0] == ('>&',) or r[0] == ('&>',): redirects[1] = redirects[2] = [r[1], 'w', None] elif r[0] == ('>',): redirects[1] = [r[1], 'w', None] elif r[0] == ('>>',): redirects[1] = [r[1], 'a', None] elif r[0] == ('<',): redirects[0] = [r[1], 'r', None] else: raise InternalShellError(j,"Unsupported redirect: %r" % (r,)) # Map from the final redirections to something subprocess can handle. final_redirects = [] for index,r in enumerate(redirects): if r == (0,): result = input elif r == (1,): if index == 0: raise InternalShellError(j,"Unsupported redirect for stdin") elif index == 1: result = subprocess.PIPE else: result = subprocess.STDOUT elif r == (2,): if index != 2: raise InternalShellError(j,"Unsupported redirect on stdout") result = subprocess.PIPE else: if r[2] is None: if kAvoidDevNull and r[0] == '/dev/null': r[2] = tempfile.TemporaryFile(mode=r[1]) else: # Make sure relative paths are relative to the cwd. redir_filename = os.path.join(shenv.cwd, r[0]) r[2] = open(redir_filename, r[1]) # Workaround a Win32 and/or subprocess bug when appending. # # FIXME: Actually, this is probably an instance of PR6753. if r[1] == 'a': r[2].seek(0, 2) opened_files.append(r[2]) result = r[2] final_redirects.append(result) stdin, stdout, stderr = final_redirects # If stderr wants to come from stdout, but stdout isn't a pipe, then put # stderr on a pipe and treat it as stdout. if (stderr == subprocess.STDOUT and stdout != subprocess.PIPE): stderr = subprocess.PIPE stderrIsStdout = True else: stderrIsStdout = False # Don't allow stderr on a PIPE except for the last # process, this could deadlock. # # FIXME: This is slow, but so is deadlock. if stderr == subprocess.PIPE and j != cmd.commands[-1]: stderr = tempfile.TemporaryFile(mode='w+b') stderrTempFiles.append((i, stderr)) # Resolve the executable path ourselves. args = list(j.args) executable = lit.util.which(args[0], shenv.env['PATH']) if not executable: raise InternalShellError(j, '%r: command not found' % j.args[0]) # Replace uses of /dev/null with temporary files. if kAvoidDevNull: for i,arg in enumerate(args): if arg == "/dev/null": f = tempfile.NamedTemporaryFile(delete=False) f.close() named_temp_files.append(f.name) args[i] = f.name try: procs.append(subprocess.Popen(args, cwd=shenv.cwd, executable = executable, stdin = stdin, stdout = stdout, stderr = stderr, env = shenv.env, close_fds = kUseCloseFDs)) except OSError as e: raise InternalShellError(j, 'Could not create process due to {}'.format(e)) # Immediately close stdin for any process taking stdin from us. if stdin == subprocess.PIPE: procs[-1].stdin.close() procs[-1].stdin = None # Update the current stdin source. if stdout == subprocess.PIPE: input = procs[-1].stdout elif stderrIsStdout: input = procs[-1].stderr else: input = subprocess.PIPE # Explicitly close any redirected files. We need to do this now because we # need to release any handles we may have on the temporary files (important # on Win32, for example). Since we have already spawned the subprocess, our # handles have already been transferred so we do not need them anymore. for f in opened_files: f.close() # FIXME: There is probably still deadlock potential here. Yawn. procData = [None] * len(procs) procData[-1] = procs[-1].communicate() for i in range(len(procs) - 1): if procs[i].stdout is not None: out = procs[i].stdout.read() else: out = '' if procs[i].stderr is not None: err = procs[i].stderr.read() else: err = '' procData[i] = (out,err) # Read stderr out of the temp files. for i,f in stderrTempFiles: f.seek(0, 0) procData[i] = (procData[i][0], f.read()) def to_string(bytes): if isinstance(bytes, str): return bytes return bytes.encode('utf-8') exitCode = None for i,(out,err) in enumerate(procData): res = procs[i].wait() # Detect Ctrl-C in subprocess. if res == -signal.SIGINT: raise KeyboardInterrupt # Ensure the resulting output is always of string type. try: out = to_string(out.decode('utf-8')) except: out = str(out) try: err = to_string(err.decode('utf-8')) except: err = str(err) results.append((cmd.commands[i], out, err, res)) if cmd.pipe_err: # Python treats the exit code as a signed char. if exitCode is None: exitCode = res elif res < 0: exitCode = min(exitCode, res) else: exitCode = max(exitCode, res) else: exitCode = res # Remove any named temporary files we created. for f in named_temp_files: try: os.remove(f) except OSError: pass if cmd.negate: exitCode = not exitCode return exitCode def executeScriptInternal(test, litConfig, tmpBase, commands, cwd): cmds = [] for ln in commands: try: cmds.append(ShUtil.ShParser(ln, litConfig.isWindows, test.config.pipefail).parse()) except: return lit.Test.Result(Test.FAIL, "shell parser error on: %r" % ln) cmd = cmds[0] for c in cmds[1:]: cmd = ShUtil.Seq(cmd, '&&', c) results = [] try: shenv = ShellEnvironment(cwd, test.config.environment) exitCode = executeShCmd(cmd, shenv, results) except InternalShellError: e = sys.exc_info()[1] exitCode = 127 results.append((e.command, '', e.message, exitCode)) out = err = '' for i,(cmd, cmd_out,cmd_err,res) in enumerate(results): out += 'Command %d: %s\n' % (i, ' '.join('"%s"' % s for s in cmd.args)) out += 'Command %d Result: %r\n' % (i, res) out += 'Command %d Output:\n%s\n\n' % (i, cmd_out) out += 'Command %d Stderr:\n%s\n\n' % (i, cmd_err) return out, err, exitCode def executeScript(test, litConfig, tmpBase, commands, cwd): bashPath = litConfig.getBashPath(); isWin32CMDEXE = (litConfig.isWindows and not bashPath) script = tmpBase + '.script' if isWin32CMDEXE: script += '.bat' # Write script file mode = 'w' if litConfig.isWindows and not isWin32CMDEXE: mode += 'b' # Avoid CRLFs when writing bash scripts. f = open(script, mode) if isWin32CMDEXE: f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands)) else: if test.config.pipefail: f.write('set -o pipefail;') f.write('{ ' + '; } &&\n{ '.join(commands) + '; }') f.write('\n') f.close() if isWin32CMDEXE: command = ['cmd','/c', script] else: if bashPath: command = [bashPath, script] else: command = ['/bin/sh', script] if litConfig.useValgrind: # FIXME: Running valgrind on sh is overkill. We probably could just # run on clang with no real loss. command = litConfig.valgrindArgs + command return lit.util.executeCommand(command, cwd=cwd, env=test.config.environment) def parseIntegratedTestScriptCommands(source_path): """ parseIntegratedTestScriptCommands(source_path) -> commands Parse the commands in an integrated test script file into a list of (line_number, command_type, line). """ # This code is carefully written to be dual compatible with Python 2.5+ and # Python 3 without requiring input files to always have valid codings. The # trick we use is to open the file in binary mode and use the regular # expression library to find the commands, with it scanning strings in # Python2 and bytes in Python3. # # Once we find a match, we do require each script line to be decodable to # UTF-8, so we convert the outputs to UTF-8 before returning. This way the # remaining code can work with "strings" agnostic of the executing Python # version. keywords = ['RUN:', 'XFAIL:', 'REQUIRES:', 'UNSUPPORTED:', 'END.'] keywords_re = re.compile( to_bytes("(%s)(.*)\n" % ("|".join(k for k in keywords),))) f = open(source_path, 'rb') try: # Read the entire file contents. data = f.read() # Ensure the data ends with a newline. if not data.endswith(to_bytes('\n')): data = data + to_bytes('\n') # Iterate over the matches. line_number = 1 last_match_position = 0 for match in keywords_re.finditer(data): # Compute the updated line number by counting the intervening # newlines. match_position = match.start() line_number += data.count(to_bytes('\n'), last_match_position, match_position) last_match_position = match_position # Convert the keyword and line to UTF-8 strings and yield the # command. Note that we take care to return regular strings in # Python 2, to avoid other code having to differentiate between the # str and unicode types. keyword,ln = match.groups() yield (line_number, to_string(keyword[:-1].decode('utf-8')), to_string(ln.decode('utf-8'))) finally: f.close() def parseIntegratedTestScript(test, normalize_slashes=False, extra_substitutions=[], require_script=True): """parseIntegratedTestScript - Scan an LLVM/Clang style integrated test script and extract the lines to 'RUN' as well as 'XFAIL' and 'REQUIRES' and 'UNSUPPORTED' information. The RUN lines also will have variable substitution performed. If 'require_script' is False an empty script may be returned. This can be used for test formats where the actual script is optional or ignored. """ # Get the temporary location, this is always relative to the test suite # root, not test source root. # # FIXME: This should not be here? sourcepath = test.getSourcePath() sourcedir = os.path.dirname(sourcepath) execpath = test.getExecPath() execdir,execbase = os.path.split(execpath) tmpDir = os.path.join(execdir, 'Output') tmpBase = os.path.join(tmpDir, execbase) # Normalize slashes, if requested. if normalize_slashes: sourcepath = sourcepath.replace('\\', '/') sourcedir = sourcedir.replace('\\', '/') tmpDir = tmpDir.replace('\\', '/') tmpBase = tmpBase.replace('\\', '/') # We use #_MARKER_# to hide %% while we do the other substitutions. substitutions = list(extra_substitutions) substitutions.extend([('%%', '#_MARKER_#')]) substitutions.extend(test.config.substitutions) substitutions.extend([('%s', sourcepath), ('%S', sourcedir), ('%p', sourcedir), ('%{pathsep}', os.pathsep), ('%t', tmpBase + '.tmp'), ('%T', tmpDir), ('#_MARKER_#', '%')]) # "%/[STpst]" should be normalized. substitutions.extend([ ('%/s', sourcepath.replace('\\', '/')), ('%/S', sourcedir.replace('\\', '/')), ('%/p', sourcedir.replace('\\', '/')), ('%/t', tmpBase.replace('\\', '/') + '.tmp'), ('%/T', tmpDir.replace('\\', '/')), ]) # re for %if re_cond_end = re.compile('%{') re_if = re.compile('(.*?)(?:%if)') re_nested_if = re.compile('(.*?)(?:%if|%})') re_else = re.compile('^\s*%else\s*(%{)?') # Collect the test lines from the script. script = [] requires = [] unsupported = [] for line_number, command_type, ln in \ parseIntegratedTestScriptCommands(sourcepath): if command_type == 'RUN': # Trim trailing whitespace. ln = ln.rstrip() # Substitute line number expressions ln = re.sub('%\(line\)', str(line_number), ln) def replace_line_number(match): if match.group(1) == '+': return str(line_number + int(match.group(2))) if match.group(1) == '-': return str(line_number - int(match.group(2))) ln = re.sub('%\(line *([\+-]) *(\d+)\)', replace_line_number, ln) # Collapse lines with trailing '\\'. if script and script[-1][-1] == '\\': script[-1] = script[-1][:-1] + ln else: script.append(ln) elif command_type == 'XFAIL': test.xfails.extend([s.strip() for s in ln.split(',')]) elif command_type == 'REQUIRES': requires.extend([s.strip() for s in ln.split(',')]) elif command_type == 'UNSUPPORTED': unsupported.extend([s.strip() for s in ln.split(',')]) elif command_type == 'END': # END commands are only honored if the rest of the line is empty. if not ln.strip(): break else: raise ValueError("unknown script command type: %r" % ( command_type,)) def substituteIfElse(ln): # early exit to avoid wasting time on lines without # conditional substitutions if ln.find('%if ') == -1: return ln def tryParseIfCond(ln): # space is important to not conflict with other (possible) # substitutions if not ln.startswith('%if '): return None, ln ln = ln[4:] # stop at '%{' match = re_cond_end.search(ln) if not match: raise ValueError("'%{' is missing for %if substitution") cond = ln[:match.start()] # eat '%{' as well ln = ln[match.end():] return cond, ln def tryParseElse(ln): match = re_else.search(ln) if not match: return False, ln if not match.group(1): raise ValueError("'%{' is missing for %else substitution") return True, ln[match.end():] def tryParseEnd(ln): if ln.startswith('%}'): return True, ln[2:] return False, ln def parseText(ln, isNested): # parse everything until %if, or %} if we're parsing a # nested expression. re_pat = re_nested_if if isNested else re_if match = re_pat.search(ln) if not match: # there is no terminating pattern, so treat the whole # line as text return ln, '' text_end = match.end(1) return ln[:text_end], ln[text_end:] def parseRecursive(ln, isNested): result = '' while len(ln): if isNested: found_end, _ = tryParseEnd(ln) if found_end: break # %if cond %{ branch_if %} %else %{ branch_else %} cond, ln = tryParseIfCond(ln) if cond: branch_if, ln = parseRecursive(ln, isNested=True) found_end, ln = tryParseEnd(ln) if not found_end: raise ValueError("'%}' is missing for %if substitution") branch_else = '' found_else, ln = tryParseElse(ln) if found_else: branch_else, ln = parseRecursive(ln, isNested=True) found_end, ln = tryParseEnd(ln) if not found_end: raise ValueError("'%}' is missing for %else substitution") cond = cond.strip() if cond in test.config.available_features: result += branch_if else: result += branch_else continue # The rest is handled as plain text. text, ln = parseText(ln, isNested) result += text return result, ln result, ln = parseRecursive(ln, isNested=False) assert len(ln) == 0 return result # Apply substitutions to the script. Allow full regular # expression syntax. Replace each matching occurrence of regular # expression pattern a with substitution b in line ln. def processLine(ln): # Apply substitutions ln = substituteIfElse(ln) for a,b in substitutions: if kIsWindows: b = b.replace("\\","\\\\") ln = re.sub(a, b, ln) # Strip the trailing newline and any extra whitespace. return ln.strip() script = [processLine(ln) for ln in script] # Verify the script contains a run line. if require_script and not script: return lit.Test.Result(Test.UNRESOLVED, "Test has no run line!") # Check for unterminated run lines. if script and script[-1][-1] == '\\': return lit.Test.Result(Test.UNRESOLVED, "Test has unterminated run lines (with '\\')") # Check that we have the required features: missing_required_features = [f for f in requires if f not in test.config.available_features] if missing_required_features: msg = ', '.join(missing_required_features) return lit.Test.Result(Test.UNSUPPORTED, "Test requires the following features: %s" % msg) unsupported_features = [f for f in unsupported if f in test.config.available_features] if unsupported_features: msg = ', '.join(unsupported_features) return lit.Test.Result(Test.UNSUPPORTED, "Test is unsupported with the following features: %s" % msg) if test.config.limit_to_features: # Check that we have one of the limit_to_features features in requires. limit_to_features_tests = [f for f in test.config.limit_to_features if f in requires] if not limit_to_features_tests: msg = ', '.join(test.config.limit_to_features) return lit.Test.Result(Test.UNSUPPORTED, "Test requires one of the limit_to_features features %s" % msg) return script,tmpBase,execdir def _runShTest(test, litConfig, useExternalSh, script, tmpBase, execdir): # Create the output directory if it does not already exist. lit.util.mkdir_p(os.path.dirname(tmpBase)) if useExternalSh: res = executeScript(test, litConfig, tmpBase, script, execdir) else: res = executeScriptInternal(test, litConfig, tmpBase, script, execdir) if isinstance(res, lit.Test.Result): return res out,err,exitCode = res if exitCode == 0: status = Test.PASS else: status = Test.FAIL # Form the output log. output = """Script:\n--\n%s\n--\nExit Code: %d\n\n""" % ( '\n'.join(script), exitCode) # Append the outputs, if present. if out: output += """Command Output (stdout):\n--\n%s\n--\n""" % (out,) if err: output += """Command Output (stderr):\n--\n%s\n--\n""" % (err,) return lit.Test.Result(status, output) def executeShTest(test, litConfig, useExternalSh, extra_substitutions=[]): if test.config.unsupported: return (Test.UNSUPPORTED, 'Test is unsupported') res = parseIntegratedTestScript(test, useExternalSh, extra_substitutions) if isinstance(res, lit.Test.Result): return res if litConfig.noExecute: return lit.Test.Result(Test.PASS) script, tmpBase, execdir = res return _runShTest(test, litConfig, useExternalSh, script, tmpBase, execdir)
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/discovery.py
""" Test discovery functions. """ import copy import os import sys import lit.run from lit.TestingConfig import TestingConfig from lit import LitConfig, Test def dirContainsTestSuite(path, lit_config): cfgpath = os.path.join(path, lit_config.site_config_name) if os.path.exists(cfgpath): return cfgpath cfgpath = os.path.join(path, lit_config.config_name) if os.path.exists(cfgpath): return cfgpath def getTestSuite(item, litConfig, cache): """getTestSuite(item, litConfig, cache) -> (suite, relative_path) Find the test suite containing @arg item. @retval (None, ...) - Indicates no test suite contains @arg item. @retval (suite, relative_path) - The suite that @arg item is in, and its relative path inside that suite. """ def search1(path): # Check for a site config or a lit config. cfgpath = dirContainsTestSuite(path, litConfig) # If we didn't find a config file, keep looking. if not cfgpath: parent,base = os.path.split(path) if parent == path: return (None, ()) ts, relative = search(parent) return (ts, relative + (base,)) # We found a test suite, create a new config for it and load it. if litConfig.debug: litConfig.note('loading suite config %r' % cfgpath) cfg = TestingConfig.fromdefaults(litConfig) cfg.load_from_path(cfgpath, litConfig) source_root = os.path.realpath(cfg.test_source_root or path) exec_root = os.path.realpath(cfg.test_exec_root or path) return Test.TestSuite(cfg.name, source_root, exec_root, cfg), () def search(path): # Check for an already instantiated test suite. res = cache.get(path) if res is None: cache[path] = res = search1(path) return res # Canonicalize the path. item = os.path.realpath(item) # Skip files and virtual components. components = [] while not os.path.isdir(item): parent,base = os.path.split(item) if parent == item: return (None, ()) components.append(base) item = parent components.reverse() ts, relative = search(item) return ts, tuple(relative + tuple(components)) def getLocalConfig(ts, path_in_suite, litConfig, cache): def search1(path_in_suite): # Get the parent config. if not path_in_suite: parent = ts.config else: parent = search(path_in_suite[:-1]) # Check if there is a local configuration file. source_path = ts.getSourcePath(path_in_suite) cfgpath = os.path.join(source_path, litConfig.local_config_name) # If not, just reuse the parent config. if not os.path.exists(cfgpath): return parent # Otherwise, copy the current config and load the local configuration # file into it. config = copy.deepcopy(parent) if litConfig.debug: litConfig.note('loading local config %r' % cfgpath) config.load_from_path(cfgpath, litConfig) return config def search(path_in_suite): key = (ts, path_in_suite) res = cache.get(key) if res is None: cache[key] = res = search1(path_in_suite) return res return search(path_in_suite) def getTests(path, litConfig, testSuiteCache, localConfigCache): # Find the test suite for this input and its relative path. ts,path_in_suite = getTestSuite(path, litConfig, testSuiteCache) if ts is None: litConfig.warning('unable to find test suite for %r' % path) return (),() if litConfig.debug: litConfig.note('resolved input %r to %r::%r' % (path, ts.name, path_in_suite)) return ts, getTestsInSuite(ts, path_in_suite, litConfig, testSuiteCache, localConfigCache) def getTestsInSuite(ts, path_in_suite, litConfig, testSuiteCache, localConfigCache): # Check that the source path exists (errors here are reported by the # caller). source_path = ts.getSourcePath(path_in_suite) if not os.path.exists(source_path): return # Check if the user named a test directly. if not os.path.isdir(source_path): lc = getLocalConfig(ts, path_in_suite[:-1], litConfig, localConfigCache) yield Test.Test(ts, path_in_suite, lc) return # Otherwise we have a directory to search for tests, start by getting the # local configuration. lc = getLocalConfig(ts, path_in_suite, litConfig, localConfigCache) # Search for tests. if lc.test_format is not None: for res in lc.test_format.getTestsInDirectory(ts, path_in_suite, litConfig, lc): yield res # Search subdirectories. for filename in os.listdir(source_path): # FIXME: This doesn't belong here? if filename in ('Output', '.svn', '.git') or filename in lc.excludes: continue # Ignore non-directories. file_sourcepath = os.path.join(source_path, filename) if not os.path.isdir(file_sourcepath): continue # Check for nested test suites, first in the execpath in case there is a # site configuration and then in the source path. subpath = path_in_suite + (filename,) file_execpath = ts.getExecPath(subpath) if dirContainsTestSuite(file_execpath, litConfig): sub_ts, subpath_in_suite = getTestSuite(file_execpath, litConfig, testSuiteCache) elif dirContainsTestSuite(file_sourcepath, litConfig): sub_ts, subpath_in_suite = getTestSuite(file_sourcepath, litConfig, testSuiteCache) else: sub_ts = None # If the this directory recursively maps back to the current test suite, # disregard it (this can happen if the exec root is located inside the # current test suite, for example). if sub_ts is ts: continue # Otherwise, load from the nested test suite, if present. if sub_ts is not None: subiter = getTestsInSuite(sub_ts, subpath_in_suite, litConfig, testSuiteCache, localConfigCache) else: subiter = getTestsInSuite(ts, subpath, litConfig, testSuiteCache, localConfigCache) N = 0 for res in subiter: N += 1 yield res if sub_ts and not N: litConfig.warning('test suite %r contained no tests' % sub_ts.name) def find_tests_for_inputs(lit_config, inputs): """ find_tests_for_inputs(lit_config, inputs) -> [Test] Given a configuration object and a list of input specifiers, find all the tests to execute. """ # Expand '@...' form in inputs. actual_inputs = [] for input in inputs: if input.startswith('@'): f = open(input[1:]) try: for ln in f: ln = ln.strip() if ln: actual_inputs.append(ln) finally: f.close() else: actual_inputs.append(input) # Load the tests from the inputs. tests = [] test_suite_cache = {} local_config_cache = {} for input in actual_inputs: prev = len(tests) tests.extend(getTests(input, lit_config, test_suite_cache, local_config_cache)[1]) if prev == len(tests): lit_config.warning('input %r contained no tests' % input) # If there were any errors during test discovery, exit now. if lit_config.numErrors: sys.stderr.write('%d errors, exiting.\n' % lit_config.numErrors) sys.exit(2) return tests def load_test_suite(inputs): import platform import unittest from lit.LitTestCase import LitTestCase # Create the global config object. litConfig = LitConfig.LitConfig(progname = 'lit', path = [], quiet = False, useValgrind = False, valgrindLeakCheck = False, valgrindArgs = [], noExecute = False, debug = False, isWindows = (platform.system()=='Windows'), params = {}) # Perform test discovery. run = lit.run.Run(litConfig, find_tests_for_inputs(litConfig, inputs)) # Return a unittest test suite which just runs the tests in order. return unittest.TestSuite([LitTestCase(test, run) for test in run.tests])
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/util.py
import errno import itertools import math import os import platform import signal import subprocess import sys def to_bytes(str): # Encode to UTF-8 to get binary data. return str.encode('utf-8') def to_string(bytes): if isinstance(bytes, str): return bytes return to_bytes(bytes) def convert_string(bytes): try: return to_string(bytes.decode('utf-8')) except UnicodeError: return str(bytes) def detectCPUs(): """ Detects the number of CPUs on a system. Cribbed from pp. """ # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: # Linux & Unix: ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if isinstance(ncpus, int) and ncpus > 0: return ncpus else: # OSX: return int(capture(['sysctl', '-n', 'hw.ncpu'])) # Windows: if "NUMBER_OF_PROCESSORS" in os.environ: ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]) if ncpus > 0: return ncpus return 1 # Default def mkdir_p(path): """mkdir_p(path) - Make the "path" directory, if it does not exist; this will also make directories for any missing parent directories.""" if not path or os.path.exists(path): return parent = os.path.dirname(path) if parent != path: mkdir_p(parent) try: os.mkdir(path) except OSError: e = sys.exc_info()[1] # Ignore EEXIST, which may occur during a race condition. if e.errno != errno.EEXIST: raise def capture(args, env=None): """capture(command) - Run the given command (or argv list) in a shell and return the standard output.""" p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out,_ = p.communicate() return convert_string(out) def which(command, paths = None): """which(command, [paths]) - Look up the given command in the paths string (or the PATH environment variable, if unspecified).""" if paths is None: paths = os.environ.get('PATH','') # Check for absolute match first. if os.path.isfile(command): return command # Would be nice if Python had a lib function for this. if not paths: paths = os.defpath # Get suffixes to search. # On Cygwin, 'PATHEXT' may exist but it should not be used. if os.pathsep == ';': pathext = os.environ.get('PATHEXT', '').split(';') else: pathext = [''] # Search the paths... for path in paths.split(os.pathsep): for ext in pathext: p = os.path.join(path, command + ext) if os.path.exists(p): return p return None def checkToolsPath(dir, tools): for tool in tools: if not os.path.exists(os.path.join(dir, tool)): return False; return True; def whichTools(tools, paths): for path in paths.split(os.pathsep): if checkToolsPath(path, tools): return path return None def printHistogram(items, title = 'Items'): items.sort(key = lambda item: item[1]) maxValue = max([v for _,v in items]) # Select first "nice" bar height that produces more than 10 bars. power = int(math.ceil(math.log(maxValue, 10))) for inc in itertools.cycle((5, 2, 2.5, 1)): barH = inc * 10**power N = int(math.ceil(maxValue / barH)) if N > 10: break elif inc == 1: power -= 1 histo = [set() for i in range(N)] for name,v in items: bin = min(int(N * v/maxValue), N-1) histo[bin].add(name) barW = 40 hr = '-' * (barW + 34) print('\nSlowest %s:' % title) print(hr) for name,value in items[-20:]: print('%.2fs: %s' % (value, name)) print('\n%s Times:' % title) print(hr) pDigits = int(math.ceil(math.log(maxValue, 10))) pfDigits = max(0, 3-pDigits) if pfDigits: pDigits += pfDigits + 1 cDigits = int(math.ceil(math.log(len(items), 10))) print("[%s] :: [%s] :: [%s]" % ('Range'.center((pDigits+1)*2 + 3), 'Percentage'.center(barW), 'Count'.center(cDigits*2 + 1))) print(hr) for i,row in enumerate(histo): pct = float(len(row)) / len(items) w = int(barW * pct) print("[%*.*fs,%*.*fs) :: [%s%s] :: [%*d/%*d]" % ( pDigits, pfDigits, i*barH, pDigits, pfDigits, (i+1)*barH, '*'*w, ' '*(barW-w), cDigits, len(row), cDigits, len(items))) # Close extra file handles on UNIX (on Windows this cannot be done while # also redirecting input). kUseCloseFDs = not (platform.system() == 'Windows') def executeCommand(command, cwd=None, env=None): p = subprocess.Popen(command, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, close_fds=kUseCloseFDs) out,err = p.communicate() exitCode = p.wait() # Detect Ctrl-C in subprocess. if exitCode == -signal.SIGINT: raise KeyboardInterrupt # Ensure the resulting output is always of string type. out = convert_string(out) err = convert_string(err) return out, err, exitCode def usePlatformSdkOnDarwin(config, lit_config): # On Darwin, support relocatable SDKs by providing Clang with a # default system root path. if 'darwin' in config.target_triple: try: cmd = subprocess.Popen(['xcrun', '--show-sdk-path'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = cmd.communicate() out = out.strip() res = cmd.wait() except OSError: res = -1 if res == 0 and out: sdk_path = out lit_config.note('using SDKROOT: %r' % sdk_path) config.environment['SDKROOT'] = sdk_path
0
repos/DirectXShaderCompiler/utils/lit
repos/DirectXShaderCompiler/utils/lit/lit/Test.py
import os from xml.sax.saxutils import escape from json import JSONEncoder # Test result codes. class ResultCode(object): """Test result codes.""" # We override __new__ and __getnewargs__ to ensure that pickling still # provides unique ResultCode objects in any particular instance. _instances = {} def __new__(cls, name, isFailure): res = cls._instances.get(name) if res is None: cls._instances[name] = res = super(ResultCode, cls).__new__(cls) return res def __getnewargs__(self): return (self.name, self.isFailure) def __init__(self, name, isFailure): self.name = name self.isFailure = isFailure def __repr__(self): return '%s%r' % (self.__class__.__name__, (self.name, self.isFailure)) PASS = ResultCode('PASS', False) XFAIL = ResultCode('XFAIL', False) FAIL = ResultCode('FAIL', True) XPASS = ResultCode('XPASS', True) UNRESOLVED = ResultCode('UNRESOLVED', True) UNSUPPORTED = ResultCode('UNSUPPORTED', False) # Test metric values. class MetricValue(object): def format(self): """ format() -> str Convert this metric to a string suitable for displaying as part of the console output. """ raise RuntimeError("abstract method") def todata(self): """ todata() -> json-serializable data Convert this metric to content suitable for serializing in the JSON test output. """ raise RuntimeError("abstract method") class IntMetricValue(MetricValue): def __init__(self, value): self.value = value def format(self): return str(self.value) def todata(self): return self.value class RealMetricValue(MetricValue): def __init__(self, value): self.value = value def format(self): return '%.4f' % self.value def todata(self): return self.value class JSONMetricValue(MetricValue): """ JSONMetricValue is used for types that are representable in the output but that are otherwise uninterpreted. """ def __init__(self, value): # Ensure the value is a serializable by trying to encode it. # WARNING: The value may change before it is encoded again, and may # not be encodable after the change. try: e = JSONEncoder() e.encode(value) except TypeError: raise self.value = value def format(self): e = JSONEncoder(indent=2, sort_keys=True) return e.encode(self.value) def todata(self): return self.value def toMetricValue(value): if isinstance(value, MetricValue): return value elif isinstance(value, int) or isinstance(value, long): return IntMetricValue(value) elif isinstance(value, float): return RealMetricValue(value) else: # Try to create a JSONMetricValue and let the constructor throw # if value is not a valid type. return JSONMetricValue(value) # Test results. class Result(object): """Wrapper for the results of executing an individual test.""" def __init__(self, code, output='', elapsed=None): # The result code. self.code = code # The test output. self.output = output # The wall timing to execute the test, if timing. self.elapsed = elapsed # The metrics reported by this test. self.metrics = {} def addMetric(self, name, value): """ addMetric(name, value) Attach a test metric to the test result, with the given name and list of values. It is an error to attempt to attach the metrics with the same name multiple times. Each value must be an instance of a MetricValue subclass. """ if name in self.metrics: raise ValueError("result already includes metrics for %r" % ( name,)) if not isinstance(value, MetricValue): raise TypeError("unexpected metric value: %r" % (value,)) self.metrics[name] = value # Test classes. class TestSuite: """TestSuite - Information on a group of tests. A test suite groups together a set of logically related tests. """ def __init__(self, name, source_root, exec_root, config): self.name = name self.source_root = source_root self.exec_root = exec_root # The test suite configuration. self.config = config def getSourcePath(self, components): return os.path.join(self.source_root, *components) def getExecPath(self, components): return os.path.join(self.exec_root, *components) class Test: """Test - Information on a single test instance.""" def __init__(self, suite, path_in_suite, config, file_path = None): self.suite = suite self.path_in_suite = path_in_suite self.config = config self.file_path = file_path # A list of conditions under which this test is expected to fail. These # can optionally be provided by test format handlers, and will be # honored when the test result is supplied. self.xfails = [] # The test result, once complete. self.result = None def setResult(self, result): if self.result is not None: raise ArgumentError("test result already set") if not isinstance(result, Result): raise ArgumentError("unexpected result type") self.result = result # Apply the XFAIL handling to resolve the result exit code. if self.isExpectedToFail(): if self.result.code == PASS: self.result.code = XPASS elif self.result.code == FAIL: self.result.code = XFAIL def getFullName(self): return self.suite.config.name + ' :: ' + '/'.join(self.path_in_suite) def getFilePath(self): if self.file_path: return self.file_path return self.getSourcePath() def getSourcePath(self): return self.suite.getSourcePath(self.path_in_suite) def getExecPath(self): return self.suite.getExecPath(self.path_in_suite) def isExpectedToFail(self): """ isExpectedToFail() -> bool Check whether this test is expected to fail in the current configuration. This check relies on the test xfails property which by some test formats may not be computed until the test has first been executed. """ # Check if any of the xfails match an available feature or the target. for item in self.xfails: # If this is the wildcard, it always fails. if item == '*': return True # If this is an exact match for one of the features, it fails. if item in self.config.available_features: return True # If this is a part of the target triple, it fails. if item in self.suite.config.target_triple: return True return False def getJUnitXML(self, includeAllTestOutput=False): test_name = self.path_in_suite[-1] test_path = self.path_in_suite[:-1] safe_test_path = [x.replace(".","_") for x in test_path] safe_name = self.suite.name.replace(".","-") if safe_test_path: class_name = safe_name + "." + "/".join(safe_test_path) else: class_name = safe_name + "." + safe_name xml = "<testcase classname='" + class_name + "' name='" + \ test_name + "'" xml += " time='%.2f'" % (self.result.elapsed,) if self.result.code.isFailure: xml += ">\n\t<failure >\n" + escape(self.result.output) xml += "\n\t</failure>\n</testcase>" else: if includeAllTestOutput: xml += ">" xml += "\n\t<system-out>\n" + escape(self.result.output) xml += "\n\t</system-out>\n</testcase>" else: xml += "/>" return xml
0
repos/DirectXShaderCompiler/utils/lit/lit
repos/DirectXShaderCompiler/utils/lit/lit/formats/taef.py
from __future__ import absolute_import import os import sys import signal import subprocess import lit.Test import lit.TestRunner import lit.util from .base import TestFormat # TAEF must be run with custom command line string and shell=True # because of the way it manually processes quoted arguments in a # non-standard way. def executeCommandForTaef(command, cwd=None, env=None): p = subprocess.Popen(command, cwd=cwd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, # Close extra file handles on UNIX (on Windows this cannot be done while # also redirecting input). Taef only run on windows. close_fds=False) out,err = p.communicate() exitCode = p.wait() # Detect Ctrl-C in subprocess. if exitCode == -signal.SIGINT: raise KeyboardInterrupt # Ensure the resulting output is always of string type. out = lit.util.convert_string(out) err = lit.util.convert_string(err) return out, err, exitCode class TaefTest(TestFormat): def __init__(self, te_path, test_dll, test_path, select_filter, extra_params): self.te = te_path self.test_dll = test_dll self.test_path = test_path self.select_filter = select_filter self.extra_params = extra_params # NOTE: when search test, always running on test_dll, # use test_searched to make sure only add test once. # If TaeftTest is created in directory with sub directory, # getTestsInDirectory will be called more than once. self.test_searched = False def getTaefTests(self, dll_path, litConfig, localConfig): """getTaefTests() Return the tests available in taef test dll. Args: litConfig: LitConfig instance localConfig: TestingConfig instance""" # TE:F:\repos\DxcGitHub\hlsl.bin\TAEF\x64\te.exe # test dll : F:\repos\DxcGitHub\hlsl.bin\Debug\test\ClangHLSLTests.dll # /list if litConfig.debug: litConfig.note('searching taef test in %r' % dll_path) cmd = [self.te, dll_path, "/list", "/select:", self.select_filter] try: lines,err,exitCode = executeCommandForTaef(cmd) # this is for windows lines = lines.replace('\r', '') lines = lines.split('\n') except: litConfig.error("unable to discover taef tests in %r, using %s. exeption encountered." % (dll_path, self.te)) raise StopIteration if exitCode: litConfig.error("unable to discover taef tests in %r, using %s. error: %s." % (dll_path, self.te, err)) raise StopIteration for ln in lines: # The test name is like VerifierTest::RunUnboundedResourceArrays. if ln.find('::') == -1: continue yield ln.strip() # Note: path_in_suite should not include the executable name. def getTestsInExecutable(self, testSuite, path_in_suite, execpath, litConfig, localConfig): # taef test should be dll. if not execpath.endswith('dll'): return (dirname, basename) = os.path.split(execpath) # Discover the tests in this executable. for testname in self.getTaefTests(execpath, litConfig, localConfig): testPath = path_in_suite + (basename, testname) yield lit.Test.Test(testSuite, testPath, localConfig, file_path=execpath) def getTestsInDirectory(self, testSuite, path_in_suite, litConfig, localConfig): # Make sure self.test_dll only search once. if self.test_searched: return self.test_searched = True filepath = self.test_dll for test in self.getTestsInExecutable( testSuite, path_in_suite, filepath, litConfig, localConfig): yield test def execute(self, test, litConfig): test_dll = test.getFilePath() testPath,testName = os.path.split(test.getSourcePath()) select_filter = str.format("@Name='{}'", testName) if self.select_filter != "": select_filter = str.format("{} AND {}", select_filter, self.select_filter) cmd = [self.te, test_dll, '/inproc', '/select:', select_filter, '/miniDumpOnCrash', '/unicodeOutput:false', str.format('/outputFolder:{}', self.test_path)] cmd.extend(self.extra_params) if litConfig.useValgrind: cmd = litConfig.valgrindArgs + cmd if litConfig.noExecute: return lit.Test.PASS, '' out, err, exitCode = executeCommandForTaef( cmd, env = test.config.environment) if exitCode: skipped = 'Failed=0, Blocked=0, Not Run=0, Skipped=1' if skipped in out: return lit.Test.UNSUPPORTED, '' unselected = 'The selection criteria did not match any tests.' if unselected in out: return lit.Test.UNSUPPORTED, '' return lit.Test.FAIL, out + err summary = 'Summary: Total=' if summary not in out: msg = ('Unable to find %r in taef output:\n\n%s%s' % (summary, out, err)) return lit.Test.UNRESOLVED, msg no_fail = 'Failed=0, Blocked=0, Not Run=0, Skipped=0' if no_fail not in out == -1: msg = ('Unable to find %r in taef output:\n\n%s%s' % (no_fail, out, err)) return lit.Test.UNRESOLVED, msg return lit.Test.PASS,''
0
repos/DirectXShaderCompiler/utils/lit/lit
repos/DirectXShaderCompiler/utils/lit/lit/formats/__init__.py
from __future__ import absolute_import from lit.formats.base import TestFormat, FileBasedTest, OneCommandPerFileTest from lit.formats.googletest import GoogleTest from lit.formats.taef import TaefTest from lit.formats.shtest import ShTest
0
repos/DirectXShaderCompiler/utils/lit/lit
repos/DirectXShaderCompiler/utils/lit/lit/formats/base.py
from __future__ import absolute_import import os import sys import lit.Test import lit.util class TestFormat(object): pass ### class FileBasedTest(TestFormat): def getTestsInDirectory(self, testSuite, path_in_suite, litConfig, localConfig): source_path = testSuite.getSourcePath(path_in_suite) for filename in os.listdir(source_path): # Ignore dot files and excluded tests. if (filename.startswith('.') or filename in localConfig.excludes): continue filepath = os.path.join(source_path, filename) if not os.path.isdir(filepath): base,ext = os.path.splitext(filename) if ext in localConfig.suffixes: yield lit.Test.Test(testSuite, path_in_suite + (filename,), localConfig) ### import re import tempfile class OneCommandPerFileTest(TestFormat): # FIXME: Refactor into generic test for running some command on a directory # of inputs. def __init__(self, command, dir, recursive=False, pattern=".*", useTempInput=False): if isinstance(command, str): self.command = [command] else: self.command = list(command) if dir is not None: dir = str(dir) self.dir = dir self.recursive = bool(recursive) self.pattern = re.compile(pattern) self.useTempInput = useTempInput def getTestsInDirectory(self, testSuite, path_in_suite, litConfig, localConfig): dir = self.dir if dir is None: dir = testSuite.getSourcePath(path_in_suite) for dirname,subdirs,filenames in os.walk(dir): if not self.recursive: subdirs[:] = [] subdirs[:] = [d for d in subdirs if (d != '.svn' and d not in localConfig.excludes)] for filename in filenames: if (filename.startswith('.') or not self.pattern.match(filename) or filename in localConfig.excludes): continue path = os.path.join(dirname,filename) suffix = path[len(dir):] if suffix.startswith(os.sep): suffix = suffix[1:] test = lit.Test.Test( testSuite, path_in_suite + tuple(suffix.split(os.sep)), localConfig) # FIXME: Hack? test.source_path = path yield test def createTempInput(self, tmp, test): abstract def execute(self, test, litConfig): if test.config.unsupported: return (lit.Test.UNSUPPORTED, 'Test is unsupported') cmd = list(self.command) # If using temp input, create a temporary file and hand it to the # subclass. if self.useTempInput: tmp = tempfile.NamedTemporaryFile(suffix='.cpp') self.createTempInput(tmp, test) tmp.flush() cmd.append(tmp.name) elif hasattr(test, 'source_path'): cmd.append(test.source_path) else: cmd.append(test.getSourcePath()) out, err, exitCode = lit.util.executeCommand(cmd) diags = out + err if not exitCode and not diags.strip(): return lit.Test.PASS,'' # Try to include some useful information. report = """Command: %s\n""" % ' '.join(["'%s'" % a for a in cmd]) if self.useTempInput: report += """Temporary File: %s\n""" % tmp.name report += "--\n%s--\n""" % open(tmp.name).read() report += """Output:\n--\n%s--""" % diags return lit.Test.FAIL, report
0
repos/DirectXShaderCompiler/utils/lit/lit
repos/DirectXShaderCompiler/utils/lit/lit/formats/googletest.py
from __future__ import absolute_import import os import sys import lit.Test import lit.TestRunner import lit.util from .base import TestFormat kIsWindows = sys.platform in ['win32', 'cygwin'] class GoogleTest(TestFormat): def __init__(self, test_sub_dir, test_suffix): self.test_sub_dir = os.path.normcase(str(test_sub_dir)).split(';') self.test_suffix = str(test_suffix) # On Windows, assume tests will also end in '.exe'. if kIsWindows: self.test_suffix += '.exe' def getGTestTests(self, path, litConfig, localConfig): """getGTestTests(path) - [name] Return the tests available in gtest executable. Args: path: String path to a gtest executable litConfig: LitConfig instance localConfig: TestingConfig instance""" try: lines = lit.util.capture([path, '--gtest_list_tests'], env=localConfig.environment) if kIsWindows: lines = lines.replace('\r', '') lines = lines.split('\n') except: litConfig.error("unable to discover google-tests in %r" % path) raise StopIteration nested_tests = [] for ln in lines: # The test name list includes trailing comments beginning with # a '#' on some lines, so skip those. We don't support test names # that use escaping to embed '#' into their name as the names come # from C++ class and method names where such things are hard and # uninteresting to support. ln = ln.split('#', 1)[0].rstrip() if not ln.lstrip(): continue if 'Running main() from gtest_main.cc' in ln: # Upstream googletest prints this to stdout prior to running # tests. LLVM removed that print statement in r61540, but we # handle it here in case upstream googletest is being used. continue prefix = '' index = 0 while ln[index*2:index*2+2] == ' ': index += 1 while len(nested_tests) > index: nested_tests.pop() ln = ln[index*2:] if ln.endswith('.'): nested_tests.append(ln) elif any([name.startswith('DISABLED_') for name in nested_tests + [ln]]): # Gtest will internally skip these tests. No need to launch a # child process for it. continue else: yield ''.join(nested_tests) + ln # Note: path_in_suite should not include the executable name. def getTestsInExecutable(self, testSuite, path_in_suite, execpath, litConfig, localConfig): if not execpath.endswith(self.test_suffix): return (dirname, basename) = os.path.split(execpath) # Discover the tests in this executable. for testname in self.getGTestTests(execpath, litConfig, localConfig): testPath = path_in_suite + (basename, testname) yield lit.Test.Test(testSuite, testPath, localConfig, file_path=execpath) def getTestsInDirectory(self, testSuite, path_in_suite, litConfig, localConfig): source_path = testSuite.getSourcePath(path_in_suite) for filename in os.listdir(source_path): filepath = os.path.join(source_path, filename) if os.path.isdir(filepath): # Iterate over executables in a directory. if not os.path.normcase(filename) in self.test_sub_dir: continue dirpath_in_suite = path_in_suite + (filename, ) for subfilename in os.listdir(filepath): execpath = os.path.join(filepath, subfilename) for test in self.getTestsInExecutable( testSuite, dirpath_in_suite, execpath, litConfig, localConfig): yield test elif ('.' in self.test_sub_dir): for test in self.getTestsInExecutable( testSuite, path_in_suite, filepath, litConfig, localConfig): yield test def execute(self, test, litConfig): testPath,testName = os.path.split(test.getSourcePath()) while not os.path.exists(testPath): # Handle GTest parametrized and typed tests, whose name includes # some '/'s. testPath, namePrefix = os.path.split(testPath) testName = namePrefix + '/' + testName cmd = [testPath, '--gtest_filter=' + testName] if litConfig.useValgrind: cmd = litConfig.valgrindArgs + cmd if litConfig.noExecute: return lit.Test.PASS, '' out, err, exitCode = lit.util.executeCommand( cmd, env=test.config.environment) if exitCode: return lit.Test.FAIL, out + err passing_test_line = '[ PASSED ] 1 test.' if passing_test_line not in out: msg = ('Unable to find %r in gtest output:\n\n%s%s' % (passing_test_line, out, err)) return lit.Test.UNRESOLVED, msg return lit.Test.PASS,''
0
repos/DirectXShaderCompiler/utils/lit/lit
repos/DirectXShaderCompiler/utils/lit/lit/formats/shtest.py
from __future__ import absolute_import import lit.TestRunner from .base import FileBasedTest class ShTest(FileBasedTest): def __init__(self, execute_external = False): self.execute_external = execute_external def execute(self, test, litConfig): return lit.TestRunner.executeShTest(test, litConfig, self.execute_external)
0
repos/DirectXShaderCompiler
repos/DirectXShaderCompiler/unittests/CMakeLists.txt
add_custom_target(UnitTests) set_target_properties(UnitTests PROPERTIES FOLDER "Tests") if (APPLE) set(CMAKE_INSTALL_RPATH "@executable_path/../../lib") else(UNIX) set(CMAKE_INSTALL_RPATH "\$ORIGIN/../../lib${LLVM_LIBDIR_SUFFIX}") endif() function(add_llvm_unittest test_dirname) add_unittest(UnitTests ${test_dirname} ${ARGN}) endfunction() add_subdirectory(ADT) add_subdirectory(Analysis) add_subdirectory(AsmParser) add_subdirectory(Bitcode) # add_subdirectory(CodeGen) - HLSL doesn't codegen... # add_subdirectory(DebugInfo) - HLSL doesn't generate dwarf add_subdirectory(DxcSupport) add_subdirectory(DxilHash) # add_subdirectory(ExecutionEngine) - HLSL Change - removed add_subdirectory(IR) # add_subdirectory(LineEditor) - HLSL Change - removed add_subdirectory(Linker) # add_subdirectory(MC) - HLSL doesn't codegen... add_subdirectory(Option) add_subdirectory(ProfileData) add_subdirectory(Support) add_subdirectory(Transforms)
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/MC/StringTableBuilderTest.cpp
//===----------- StringTableBuilderTest.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/StringTableBuilder.h" #include "llvm/Support/Endian.h" #include "gtest/gtest.h" #include <string> using namespace llvm; namespace { TEST(StringTableBuilderTest, BasicELF) { StringTableBuilder B; B.add("foo"); B.add("bar"); B.add("foobar"); B.finalize(StringTableBuilder::ELF); std::string Expected; Expected += '\x00'; Expected += "foobar"; Expected += '\x00'; Expected += "foo"; Expected += '\x00'; EXPECT_EQ(Expected, B.data()); EXPECT_EQ(1U, B.getOffset("foobar")); EXPECT_EQ(4U, B.getOffset("bar")); EXPECT_EQ(8U, B.getOffset("foo")); } TEST(StringTableBuilderTest, BasicWinCOFF) { StringTableBuilder B; // Strings must be 9 chars or longer to go in the table. B.add("hippopotamus"); B.add("pygmy hippopotamus"); B.add("river horse"); B.finalize(StringTableBuilder::WinCOFF); // size_field + "pygmy hippopotamus\0" + "river horse\0" uint32_t ExpectedSize = 4 + 19 + 12; EXPECT_EQ(ExpectedSize, B.data().size()); std::string Expected; ExpectedSize = support::endian::byte_swap<uint32_t, support::little>(ExpectedSize); Expected.append((const char*)&ExpectedSize, 4); Expected += "pygmy hippopotamus"; Expected += '\x00'; Expected += "river horse"; Expected += '\x00'; EXPECT_EQ(Expected, B.data()); EXPECT_EQ(4U, B.getOffset("pygmy hippopotamus")); EXPECT_EQ(10U, B.getOffset("hippopotamus")); EXPECT_EQ(23U, B.getOffset("river horse")); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/MC/Disassembler.cpp
//===- llvm/unittest/Object/Disassembler.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm-c/Disassembler.h" #include "llvm/Support/TargetSelect.h" #include "gtest/gtest.h" using namespace llvm; static const char *symbolLookupCallback(void *DisInfo, uint64_t ReferenceValue, uint64_t *ReferenceType, uint64_t ReferencePC, const char **ReferenceName) { *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; return nullptr; } TEST(Disassembler, Test1) { llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllDisassemblers(); uint8_t Bytes[] = {0x90, 0x90, 0xeb, 0xfd}; uint8_t *BytesP = Bytes; const char OutStringSize = 100; char OutString[OutStringSize]; LLVMDisasmContextRef DCR = LLVMCreateDisasm("x86_64-pc-linux", nullptr, 0, nullptr, symbolLookupCallback); if (!DCR) return; size_t InstSize; unsigned NumBytes = sizeof(Bytes); unsigned PC = 0; InstSize = LLVMDisasmInstruction(DCR, BytesP, NumBytes, PC, OutString, OutStringSize); EXPECT_EQ(InstSize, 1U); EXPECT_EQ(StringRef(OutString), "\tnop"); PC += InstSize; BytesP += InstSize; NumBytes -= InstSize; InstSize = LLVMDisasmInstruction(DCR, BytesP, NumBytes, PC, OutString, OutStringSize); EXPECT_EQ(InstSize, 1U); EXPECT_EQ(StringRef(OutString), "\tnop"); PC += InstSize; BytesP += InstSize; NumBytes -= InstSize; InstSize = LLVMDisasmInstruction(DCR, BytesP, NumBytes, PC, OutString, OutStringSize); EXPECT_EQ(InstSize, 2U); EXPECT_EQ(StringRef(OutString), "\tjmp\t0x1"); LLVMDisasmDispose(DCR); }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/MC/YAMLTest.cpp
//===- llvm/unittest/Object/YAMLTest.cpp - Tests for Object YAML ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/YAML.h" #include "llvm/Support/YAMLTraits.h" #include "gtest/gtest.h" using namespace llvm; struct BinaryHolder { yaml::BinaryRef Binary; }; namespace llvm { namespace yaml { template <> struct MappingTraits<BinaryHolder> { static void mapping(IO &IO, BinaryHolder &BH) { IO.mapRequired("Binary", BH.Binary); } }; } // end namespace yaml } // end namespace llvm TEST(ObjectYAML, BinaryRef) { BinaryHolder BH; SmallVector<char, 32> Buf; llvm::raw_svector_ostream OS(Buf); yaml::Output YOut(OS); YOut << BH; EXPECT_NE(OS.str().find("''"), StringRef::npos); }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/MC/CMakeLists.txt
set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} MC MCDisassembler Support ) add_llvm_unittest(MCTests Disassembler.cpp StringTableBuilderTest.cpp YAMLTest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Option/OptionParsingTest.cpp
//===- unittest/Support/OptionParsingTest.cpp - OptTable tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::opt; enum ID { OPT_INVALID = 0, // This is not an option ID. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR) OPT_##ID, #include "Opts.inc" LastOption #undef OPTION }; #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; #include "Opts.inc" #undef PREFIX enum OptionFlags { OptFlag1 = (1 << 4), OptFlag2 = (1 << 5), OptFlag3 = (1 << 6) }; static const OptTable::Info InfoTable[] = { #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR) \ { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \ FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS }, #include "Opts.inc" #undef OPTION }; namespace { class TestOptTable : public OptTable { public: TestOptTable(bool IgnoreCase = false) : OptTable(InfoTable, array_lengthof(InfoTable), IgnoreCase) {} }; } const char *Args[] = { "-A", "-Bhi", "--C=desu", "-C", "bye", "-D,adena", "-E", "apple", "bloom", "-Fblarg", "-F", "42", "-Gchuu", "2" }; TEST(Option, OptionParsing) { TestOptTable T; unsigned MAI, MAC; InputArgList AL = T.ParseArgs(Args, MAI, MAC); // Check they all exist. EXPECT_TRUE(AL.hasArg(OPT_A)); EXPECT_TRUE(AL.hasArg(OPT_B)); EXPECT_TRUE(AL.hasArg(OPT_C)); EXPECT_TRUE(AL.hasArg(OPT_D)); EXPECT_TRUE(AL.hasArg(OPT_E)); EXPECT_TRUE(AL.hasArg(OPT_F)); EXPECT_TRUE(AL.hasArg(OPT_G)); // Check the values. EXPECT_EQ(AL.getLastArgValue(OPT_B), "hi"); EXPECT_EQ(AL.getLastArgValue(OPT_C), "bye"); EXPECT_EQ(AL.getLastArgValue(OPT_D), "adena"); std::vector<std::string> Es = AL.getAllArgValues(OPT_E); EXPECT_EQ(Es[0], "apple"); EXPECT_EQ(Es[1], "bloom"); EXPECT_EQ(AL.getLastArgValue(OPT_F), "42"); std::vector<std::string> Gs = AL.getAllArgValues(OPT_G); EXPECT_EQ(Gs[0], "chuu"); EXPECT_EQ(Gs[1], "2"); // Check the help text. std::string Help; raw_string_ostream RSO(Help); T.PrintHelp(RSO, "test", "title!"); EXPECT_NE(Help.find("-A"), std::string::npos); // Test aliases. arg_iterator Cs = AL.filtered_begin(OPT_C); ASSERT_NE(Cs, AL.filtered_end()); EXPECT_EQ(StringRef((*Cs)->getValue()), "desu"); ArgStringList ASL; (*Cs)->render(AL, ASL); ASSERT_EQ(ASL.size(), 2u); EXPECT_EQ(StringRef(ASL[0]), "-C"); EXPECT_EQ(StringRef(ASL[1]), "desu"); } TEST(Option, ParseWithFlagExclusions) { TestOptTable T; unsigned MAI, MAC; // Exclude flag3 to avoid parsing as OPT_SLASH_C. InputArgList AL = T.ParseArgs(Args, MAI, MAC, /*FlagsToInclude=*/0, /*FlagsToExclude=*/OptFlag3); EXPECT_TRUE(AL.hasArg(OPT_A)); EXPECT_TRUE(AL.hasArg(OPT_C)); EXPECT_FALSE(AL.hasArg(OPT_SLASH_C)); // Exclude flag1 to avoid parsing as OPT_C. AL = T.ParseArgs(Args, MAI, MAC, /*FlagsToInclude=*/0, /*FlagsToExclude=*/OptFlag1); EXPECT_TRUE(AL.hasArg(OPT_B)); EXPECT_FALSE(AL.hasArg(OPT_C)); EXPECT_TRUE(AL.hasArg(OPT_SLASH_C)); const char *NewArgs[] = { "/C", "foo", "--C=bar" }; AL = T.ParseArgs(NewArgs, MAI, MAC); EXPECT_TRUE(AL.hasArg(OPT_SLASH_C)); EXPECT_TRUE(AL.hasArg(OPT_C)); EXPECT_EQ(AL.getLastArgValue(OPT_SLASH_C), "foo"); EXPECT_EQ(AL.getLastArgValue(OPT_C), "bar"); } TEST(Option, ParseAliasInGroup) { TestOptTable T; unsigned MAI, MAC; const char *MyArgs[] = { "-I" }; InputArgList AL = T.ParseArgs(MyArgs, MAI, MAC); EXPECT_TRUE(AL.hasArg(OPT_H)); } TEST(Option, AliasArgs) { TestOptTable T; unsigned MAI, MAC; const char *MyArgs[] = { "-J", "-Joo" }; InputArgList AL = T.ParseArgs(MyArgs, MAI, MAC); EXPECT_TRUE(AL.hasArg(OPT_B)); EXPECT_EQ(AL.getAllArgValues(OPT_B)[0], "foo"); EXPECT_EQ(AL.getAllArgValues(OPT_B)[1], "bar"); } TEST(Option, IgnoreCase) { TestOptTable T(true); unsigned MAI, MAC; const char *MyArgs[] = { "-a", "-joo" }; InputArgList AL = T.ParseArgs(MyArgs, MAI, MAC); EXPECT_TRUE(AL.hasArg(OPT_A)); EXPECT_TRUE(AL.hasArg(OPT_B)); } TEST(Option, DoNotIgnoreCase) { TestOptTable T; unsigned MAI, MAC; const char *MyArgs[] = { "-a", "-joo" }; InputArgList AL = T.ParseArgs(MyArgs, MAI, MAC); EXPECT_FALSE(AL.hasArg(OPT_A)); EXPECT_FALSE(AL.hasArg(OPT_B)); } TEST(Option, SlurpEmpty) { TestOptTable T; unsigned MAI, MAC; const char *MyArgs[] = { "-A", "-slurp" }; InputArgList AL = T.ParseArgs(MyArgs, MAI, MAC); EXPECT_TRUE(AL.hasArg(OPT_A)); EXPECT_TRUE(AL.hasArg(OPT_Slurp)); EXPECT_EQ(AL.getAllArgValues(OPT_Slurp).size(), 0U); } TEST(Option, Slurp) { TestOptTable T; unsigned MAI, MAC; const char *MyArgs[] = { "-A", "-slurp", "-B", "--", "foo" }; InputArgList AL = T.ParseArgs(MyArgs, MAI, MAC); EXPECT_EQ(AL.size(), 2U); EXPECT_TRUE(AL.hasArg(OPT_A)); EXPECT_FALSE(AL.hasArg(OPT_B)); EXPECT_TRUE(AL.hasArg(OPT_Slurp)); EXPECT_EQ(AL.getAllArgValues(OPT_Slurp).size(), 3U); EXPECT_EQ(AL.getAllArgValues(OPT_Slurp)[0], "-B"); EXPECT_EQ(AL.getAllArgValues(OPT_Slurp)[1], "--"); EXPECT_EQ(AL.getAllArgValues(OPT_Slurp)[2], "foo"); } TEST(Option, FlagAliasToJoined) { TestOptTable T; unsigned MAI, MAC; // Check that a flag alias provides an empty argument to a joined option. const char *MyArgs[] = { "-K" }; InputArgList AL = T.ParseArgs(MyArgs, MAI, MAC); EXPECT_EQ(AL.size(), 1U); EXPECT_TRUE(AL.hasArg(OPT_B)); EXPECT_EQ(AL.getAllArgValues(OPT_B).size(), 1U); EXPECT_EQ(AL.getAllArgValues(OPT_B)[0], ""); }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Option/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Option Support ) set(LLVM_TARGET_DEFINITIONS Opts.td) tablegen(LLVM Opts.inc -gen-opt-parser-defs) add_public_tablegen_target(OptsTestTableGen) add_llvm_unittest(OptionTests OptionParsingTest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/AsmParser/CMakeLists.txt
set(LLVM_LINK_COMPONENTS AsmParser Core Support ) add_llvm_unittest(AsmParserTests AsmParserTest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/AsmParser/AsmParserTest.cpp
//===- llvm/unittest/AsmParser/AsmParserTest.cpp - asm parser unittests ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/AsmParser/Parser.h" #include "llvm/AsmParser/SlotMapping.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(AsmParserTest, NullTerminatedInput) { LLVMContext &Ctx = getGlobalContext(); StringRef Source = "; Empty module \n"; SMDiagnostic Error; auto Mod = parseAssemblyString(Source, Error, Ctx); EXPECT_TRUE(Mod != nullptr); EXPECT_TRUE(Error.getMessage().empty()); } #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG TEST(AsmParserTest, NonNullTerminatedInput) { LLVMContext &Ctx = getGlobalContext(); StringRef Source = "; Empty module \n\1\2"; SMDiagnostic Error; std::unique_ptr<Module> Mod; EXPECT_DEATH(Mod = parseAssemblyString(Source.substr(0, Source.size() - 2), Error, Ctx), "Buffer is not null terminated!"); } #endif #endif TEST(AsmParserTest, SlotMappingTest) { LLVMContext &Ctx = getGlobalContext(); StringRef Source = "@0 = global i32 0\n !0 = !{}\n !42 = !{i32 42}"; SMDiagnostic Error; SlotMapping Mapping; auto Mod = parseAssemblyString(Source, Error, Ctx, &Mapping); EXPECT_TRUE(Mod != nullptr); EXPECT_TRUE(Error.getMessage().empty()); ASSERT_EQ(Mapping.GlobalValues.size(), 1u); EXPECT_TRUE(isa<GlobalVariable>(Mapping.GlobalValues[0])); EXPECT_EQ(Mapping.MetadataNodes.size(), 2u); EXPECT_EQ(Mapping.MetadataNodes.count(0), 1u); EXPECT_EQ(Mapping.MetadataNodes.count(42), 1u); EXPECT_EQ(Mapping.MetadataNodes.count(1), 0u); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Transforms/CMakeLists.txt
add_subdirectory(IPO) add_subdirectory(Utils)
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/IPO/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Core DXIL # HLSL Change Support IPO ) add_llvm_unittest(IPOTests LowerBitSets.cpp )
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/IPO/LowerBitSets.cpp
//===- LowerBitSets.cpp - Unit tests for bitset lowering ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO/LowerBitSets.h" #include "gtest/gtest.h" using namespace llvm; TEST(LowerBitSets, BitSetBuilder) { struct { std::vector<uint64_t> Offsets; std::set<uint64_t> Bits; uint64_t ByteOffset; uint64_t BitSize; unsigned AlignLog2; bool IsSingleOffset; bool IsAllOnes; } BSBTests[] = { {{}, std::set<uint64_t>{}, 0, 1, 0, false, false}, {{0}, {0}, 0, 1, 0, true, true}, {{4}, {0}, 4, 1, 0, true, true}, {{37}, {0}, 37, 1, 0, true, true}, {{0, 1}, {0, 1}, 0, 2, 0, false, true}, {{0, 4}, {0, 1}, 0, 2, 2, false, true}, {{0, uint64_t(1) << 33}, {0, 1}, 0, 2, 33, false, true}, {{3, 7}, {0, 1}, 3, 2, 2, false, true}, {{0, 1, 7}, {0, 1, 7}, 0, 8, 0, false, false}, {{0, 2, 14}, {0, 1, 7}, 0, 8, 1, false, false}, {{0, 1, 8}, {0, 1, 8}, 0, 9, 0, false, false}, {{0, 2, 16}, {0, 1, 8}, 0, 9, 1, false, false}, {{0, 1, 2, 3, 4, 5, 6, 7}, {0, 1, 2, 3, 4, 5, 6, 7}, 0, 8, 0, false, true}, {{0, 1, 2, 3, 4, 5, 6, 7, 8}, {0, 1, 2, 3, 4, 5, 6, 7, 8}, 0, 9, 0, false, true}, }; for (auto &&T : BSBTests) { BitSetBuilder BSB; for (auto Offset : T.Offsets) BSB.addOffset(Offset); BitSetInfo BSI = BSB.build(); EXPECT_EQ(T.Bits, BSI.Bits); EXPECT_EQ(T.ByteOffset, BSI.ByteOffset); EXPECT_EQ(T.BitSize, BSI.BitSize); EXPECT_EQ(T.AlignLog2, BSI.AlignLog2); EXPECT_EQ(T.IsSingleOffset, BSI.isSingleOffset()); EXPECT_EQ(T.IsAllOnes, BSI.isAllOnes()); for (auto Offset : T.Offsets) EXPECT_TRUE(BSI.containsGlobalOffset(Offset)); auto I = T.Offsets.begin(); for (uint64_t NonOffset = 0; NonOffset != 256; ++NonOffset) { if (I != T.Offsets.end() && *I == NonOffset) { ++I; continue; } EXPECT_FALSE(BSI.containsGlobalOffset(NonOffset)); } } } TEST(LowerBitSets, GlobalLayoutBuilder) { struct { uint64_t NumObjects; std::vector<std::set<uint64_t>> Fragments; std::vector<uint64_t> WantLayout; } GLBTests[] = { {0, {}, {}}, {4, {{0, 1}, {2, 3}}, {0, 1, 2, 3}}, {3, {{0, 1}, {1, 2}}, {0, 1, 2}}, {4, {{0, 1}, {1, 2}, {2, 3}}, {0, 1, 2, 3}}, {4, {{0, 1}, {2, 3}, {1, 2}}, {0, 1, 2, 3}}, {6, {{2, 5}, {0, 1, 2, 3, 4, 5}}, {0, 1, 2, 5, 3, 4}}, }; for (auto &&T : GLBTests) { GlobalLayoutBuilder GLB(T.NumObjects); for (auto &&F : T.Fragments) GLB.addFragment(F); std::vector<uint64_t> ComputedLayout; for (auto &&F : GLB.Fragments) ComputedLayout.insert(ComputedLayout.end(), F.begin(), F.end()); EXPECT_EQ(T.WantLayout, ComputedLayout); } } TEST(LowerBitSets, ByteArrayBuilder) { struct BABAlloc { std::set<uint64_t> Bits; uint64_t BitSize; uint64_t WantByteOffset; uint8_t WantMask; }; struct { std::vector<BABAlloc> Allocs; std::vector<uint8_t> WantBytes; } BABTests[] = { {{{{0}, 1, 0, 1}, {{0}, 1, 0, 2}}, {3}}, {{{{0}, 16, 0, 1}, {{1}, 15, 0, 2}, {{2}, 14, 0, 4}, {{3}, 13, 0, 8}, {{4}, 12, 0, 0x10}, {{5}, 11, 0, 0x20}, {{6}, 10, 0, 0x40}, {{7}, 9, 0, 0x80}, {{0}, 7, 9, 0x80}, {{0}, 6, 10, 0x40}, {{0}, 5, 11, 0x20}, {{0}, 4, 12, 0x10}, {{0}, 3, 13, 8}, {{0}, 2, 14, 4}, {{0}, 1, 15, 2}}, {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80, 0, 0x80, 0x40, 0x20, 0x10, 8, 4, 2}}, }; for (auto &&T : BABTests) { ByteArrayBuilder BABuilder; for (auto &&A : T.Allocs) { uint64_t GotByteOffset; uint8_t GotMask; BABuilder.allocate(A.Bits, A.BitSize, GotByteOffset, GotMask); EXPECT_EQ(A.WantByteOffset, GotByteOffset); EXPECT_EQ(A.WantMask, GotMask); } EXPECT_EQ(T.WantBytes, BABuilder.Bytes); } }
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/Utils/Cloning.cpp
//===- Cloning.cpp - Unit tests for the Cloner ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/IR/Argument.h" #include "llvm/IR/Constant.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "gtest/gtest.h" using namespace llvm; namespace { class CloneInstruction : public ::testing::Test { protected: void SetUp() override { V = nullptr; } template <typename T> T *clone(T *V1) { Value *V2 = V1->clone(); Orig.insert(V1); Clones.insert(V2); return cast<T>(V2); } void eraseClones() { DeleteContainerPointers(Clones); } void TearDown() override { eraseClones(); DeleteContainerPointers(Orig); delete V; } SmallPtrSet<Value *, 4> Orig; // Erase on exit SmallPtrSet<Value *, 4> Clones; // Erase in eraseClones LLVMContext context; Value *V; }; TEST_F(CloneInstruction, OverflowBits) { V = new Argument(Type::getInt32Ty(context)); BinaryOperator *Add = BinaryOperator::Create(Instruction::Add, V, V); BinaryOperator *Sub = BinaryOperator::Create(Instruction::Sub, V, V); BinaryOperator *Mul = BinaryOperator::Create(Instruction::Mul, V, V); BinaryOperator *AddClone = this->clone(Add); BinaryOperator *SubClone = this->clone(Sub); BinaryOperator *MulClone = this->clone(Mul); EXPECT_FALSE(AddClone->hasNoUnsignedWrap()); EXPECT_FALSE(AddClone->hasNoSignedWrap()); EXPECT_FALSE(SubClone->hasNoUnsignedWrap()); EXPECT_FALSE(SubClone->hasNoSignedWrap()); EXPECT_FALSE(MulClone->hasNoUnsignedWrap()); EXPECT_FALSE(MulClone->hasNoSignedWrap()); eraseClones(); Add->setHasNoUnsignedWrap(); Sub->setHasNoUnsignedWrap(); Mul->setHasNoUnsignedWrap(); AddClone = this->clone(Add); SubClone = this->clone(Sub); MulClone = this->clone(Mul); EXPECT_TRUE(AddClone->hasNoUnsignedWrap()); EXPECT_FALSE(AddClone->hasNoSignedWrap()); EXPECT_TRUE(SubClone->hasNoUnsignedWrap()); EXPECT_FALSE(SubClone->hasNoSignedWrap()); EXPECT_TRUE(MulClone->hasNoUnsignedWrap()); EXPECT_FALSE(MulClone->hasNoSignedWrap()); eraseClones(); Add->setHasNoSignedWrap(); Sub->setHasNoSignedWrap(); Mul->setHasNoSignedWrap(); AddClone = this->clone(Add); SubClone = this->clone(Sub); MulClone = this->clone(Mul); EXPECT_TRUE(AddClone->hasNoUnsignedWrap()); EXPECT_TRUE(AddClone->hasNoSignedWrap()); EXPECT_TRUE(SubClone->hasNoUnsignedWrap()); EXPECT_TRUE(SubClone->hasNoSignedWrap()); EXPECT_TRUE(MulClone->hasNoUnsignedWrap()); EXPECT_TRUE(MulClone->hasNoSignedWrap()); eraseClones(); Add->setHasNoUnsignedWrap(false); Sub->setHasNoUnsignedWrap(false); Mul->setHasNoUnsignedWrap(false); AddClone = this->clone(Add); SubClone = this->clone(Sub); MulClone = this->clone(Mul); EXPECT_FALSE(AddClone->hasNoUnsignedWrap()); EXPECT_TRUE(AddClone->hasNoSignedWrap()); EXPECT_FALSE(SubClone->hasNoUnsignedWrap()); EXPECT_TRUE(SubClone->hasNoSignedWrap()); EXPECT_FALSE(MulClone->hasNoUnsignedWrap()); EXPECT_TRUE(MulClone->hasNoSignedWrap()); } TEST_F(CloneInstruction, Inbounds) { V = new Argument(Type::getInt32PtrTy(context)); Constant *Z = Constant::getNullValue(Type::getInt32Ty(context)); std::vector<Value *> ops; ops.push_back(Z); GetElementPtrInst *GEP = GetElementPtrInst::Create(Type::getInt32Ty(context), V, ops); EXPECT_FALSE(this->clone(GEP)->isInBounds()); GEP->setIsInBounds(); EXPECT_TRUE(this->clone(GEP)->isInBounds()); } TEST_F(CloneInstruction, Exact) { V = new Argument(Type::getInt32Ty(context)); BinaryOperator *SDiv = BinaryOperator::Create(Instruction::SDiv, V, V); EXPECT_FALSE(this->clone(SDiv)->isExact()); SDiv->setIsExact(true); EXPECT_TRUE(this->clone(SDiv)->isExact()); } TEST_F(CloneInstruction, Attributes) { Type *ArgTy1[] = { Type::getInt32PtrTy(context) }; FunctionType *FT1 = FunctionType::get(Type::getVoidTy(context), ArgTy1, false); Function *F1 = Function::Create(FT1, Function::ExternalLinkage); BasicBlock *BB = BasicBlock::Create(context, "", F1); IRBuilder<> Builder(BB); Builder.CreateRetVoid(); Function *F2 = Function::Create(FT1, Function::ExternalLinkage); Attribute::AttrKind AK[] = { Attribute::NoCapture }; AttributeSet AS = AttributeSet::get(context, 0, AK); Argument *A = F1->arg_begin(); A->addAttr(AS); SmallVector<ReturnInst*, 4> Returns; ValueToValueMapTy VMap; VMap[A] = UndefValue::get(A->getType()); CloneFunctionInto(F2, F1, VMap, false, Returns); EXPECT_FALSE(F2->arg_begin()->hasNoCaptureAttr()); delete F1; delete F2; } TEST_F(CloneInstruction, CallingConvention) { Type *ArgTy1[] = { Type::getInt32PtrTy(context) }; FunctionType *FT1 = FunctionType::get(Type::getVoidTy(context), ArgTy1, false); Function *F1 = Function::Create(FT1, Function::ExternalLinkage); F1->setCallingConv(CallingConv::Cold); BasicBlock *BB = BasicBlock::Create(context, "", F1); IRBuilder<> Builder(BB); Builder.CreateRetVoid(); Function *F2 = Function::Create(FT1, Function::ExternalLinkage); SmallVector<ReturnInst*, 4> Returns; ValueToValueMapTy VMap; VMap[F1->arg_begin()] = F2->arg_begin(); CloneFunctionInto(F2, F1, VMap, false, Returns); EXPECT_EQ(CallingConv::Cold, F2->getCallingConv()); delete F1; delete F2; } class CloneFunc : public ::testing::Test { protected: void SetUp() override { SetupModule(); CreateOldFunc(); CreateNewFunc(); SetupFinder(); } void TearDown() override { delete Finder; } void SetupModule() { M = new Module("", C); } void CreateOldFunc() { FunctionType* FuncType = FunctionType::get(Type::getVoidTy(C), false); OldFunc = Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", M); CreateOldFunctionBodyAndDI(); } void CreateOldFunctionBodyAndDI() { DIBuilder DBuilder(*M); IRBuilder<> IBuilder(C); // Function DI auto *File = DBuilder.createFile("filename.c", "/file/dir/"); DITypeRefArray ParamTypes = DBuilder.getOrCreateTypeArray(None); DISubroutineType *FuncType = DBuilder.createSubroutineType(File, ParamTypes); auto *CU = DBuilder.createCompileUnit(dwarf::DW_LANG_C99, "filename.c", "/file/dir", "CloneFunc", false, "", 0); auto *Subprogram = DBuilder.createFunction( CU, "f", "f", File, 4, FuncType, true, true, 3, 0, false, OldFunc); // Function body BasicBlock* Entry = BasicBlock::Create(C, "", OldFunc); IBuilder.SetInsertPoint(Entry); DebugLoc Loc = DebugLoc::get(3, 2, Subprogram); IBuilder.SetCurrentDebugLocation(Loc); AllocaInst* Alloca = IBuilder.CreateAlloca(IntegerType::getInt32Ty(C)); IBuilder.SetCurrentDebugLocation(DebugLoc::get(4, 2, Subprogram)); Value* AllocaContent = IBuilder.getInt32(1); Instruction* Store = IBuilder.CreateStore(AllocaContent, Alloca); IBuilder.SetCurrentDebugLocation(DebugLoc::get(5, 2, Subprogram)); Instruction* Terminator = IBuilder.CreateRetVoid(); // Create a local variable around the alloca auto *IntType = DBuilder.createBasicType("int", 32, 0, dwarf::DW_ATE_signed); auto *E = DBuilder.createExpression(); auto *Variable = DBuilder.createLocalVariable( dwarf::DW_TAG_auto_variable, Subprogram, "x", File, 5, IntType, true); auto *DL = DILocation::get(Subprogram->getContext(), 5, 0, Subprogram); DBuilder.insertDeclare(Alloca, Variable, E, DL, Store); DBuilder.insertDbgValueIntrinsic(AllocaContent, 0, Variable, E, DL, Terminator); // Finalize the debug info DBuilder.finalize(); // Create another, empty, compile unit DIBuilder DBuilder2(*M); DBuilder2.createCompileUnit(dwarf::DW_LANG_C99, "extra.c", "/file/dir", "CloneFunc", false, "", 0); DBuilder2.finalize(); } void CreateNewFunc() { ValueToValueMapTy VMap; NewFunc = CloneFunction(OldFunc, VMap, true, nullptr); M->getFunctionList().push_back(NewFunc); } void SetupFinder() { Finder = new DebugInfoFinder(); Finder->processModule(*M); } LLVMContext C; Function* OldFunc; Function* NewFunc; Module* M; DebugInfoFinder* Finder; }; // Test that a new, distinct function was created. TEST_F(CloneFunc, NewFunctionCreated) { EXPECT_NE(OldFunc, NewFunc); } // Test that a new subprogram entry was added and is pointing to the new // function, while the original subprogram still points to the old one. TEST_F(CloneFunc, Subprogram) { EXPECT_FALSE(verifyModule(*M)); unsigned SubprogramCount = Finder->subprogram_count(); EXPECT_EQ(2U, SubprogramCount); auto Iter = Finder->subprograms().begin(); auto *Sub1 = cast<DISubprogram>(*Iter); Iter++; auto *Sub2 = cast<DISubprogram>(*Iter); EXPECT_TRUE( (Sub1->getFunction() == OldFunc && Sub2->getFunction() == NewFunc) || (Sub1->getFunction() == NewFunc && Sub2->getFunction() == OldFunc)); } // Test that the new subprogram entry was not added to the CU which doesn't // contain the old subprogram entry. TEST_F(CloneFunc, SubprogramInRightCU) { EXPECT_FALSE(verifyModule(*M)); EXPECT_EQ(2U, Finder->compile_unit_count()); auto Iter = Finder->compile_units().begin(); auto *CU1 = cast<DICompileUnit>(*Iter); Iter++; auto *CU2 = cast<DICompileUnit>(*Iter); EXPECT_TRUE(CU1->getSubprograms().size() == 0 || CU2->getSubprograms().size() == 0); } // Test that instructions in the old function still belong to it in the // metadata, while instruction in the new function belong to the new one. TEST_F(CloneFunc, InstructionOwnership) { EXPECT_FALSE(verifyModule(*M)); inst_iterator OldIter = inst_begin(OldFunc); inst_iterator OldEnd = inst_end(OldFunc); inst_iterator NewIter = inst_begin(NewFunc); inst_iterator NewEnd = inst_end(NewFunc); while (OldIter != OldEnd && NewIter != NewEnd) { Instruction& OldI = *OldIter; Instruction& NewI = *NewIter; EXPECT_NE(&OldI, &NewI); EXPECT_EQ(OldI.hasMetadata(), NewI.hasMetadata()); if (OldI.hasMetadata()) { const DebugLoc& OldDL = OldI.getDebugLoc(); const DebugLoc& NewDL = NewI.getDebugLoc(); // Verify that the debug location data is the same EXPECT_EQ(OldDL.getLine(), NewDL.getLine()); EXPECT_EQ(OldDL.getCol(), NewDL.getCol()); // But that they belong to different functions auto *OldSubprogram = cast<DISubprogram>(OldDL.getScope()); auto *NewSubprogram = cast<DISubprogram>(NewDL.getScope()); EXPECT_EQ(OldFunc, OldSubprogram->getFunction()); EXPECT_EQ(NewFunc, NewSubprogram->getFunction()); } ++OldIter; ++NewIter; } EXPECT_EQ(OldEnd, OldIter); EXPECT_EQ(NewEnd, NewIter); } // Test that the arguments for debug intrinsics in the new function were // properly cloned TEST_F(CloneFunc, DebugIntrinsics) { EXPECT_FALSE(verifyModule(*M)); inst_iterator OldIter = inst_begin(OldFunc); inst_iterator OldEnd = inst_end(OldFunc); inst_iterator NewIter = inst_begin(NewFunc); inst_iterator NewEnd = inst_end(NewFunc); while (OldIter != OldEnd && NewIter != NewEnd) { Instruction& OldI = *OldIter; Instruction& NewI = *NewIter; if (DbgDeclareInst* OldIntrin = dyn_cast<DbgDeclareInst>(&OldI)) { DbgDeclareInst* NewIntrin = dyn_cast<DbgDeclareInst>(&NewI); EXPECT_TRUE(NewIntrin); // Old address must belong to the old function EXPECT_EQ(OldFunc, cast<AllocaInst>(OldIntrin->getAddress())-> getParent()->getParent()); // New address must belong to the new function EXPECT_EQ(NewFunc, cast<AllocaInst>(NewIntrin->getAddress())-> getParent()->getParent()); // Old variable must belong to the old function EXPECT_EQ(OldFunc, cast<DISubprogram>(OldIntrin->getVariable()->getScope()) ->getFunction()); // New variable must belong to the New function EXPECT_EQ(NewFunc, cast<DISubprogram>(NewIntrin->getVariable()->getScope()) ->getFunction()); } else if (DbgValueInst* OldIntrin = dyn_cast<DbgValueInst>(&OldI)) { DbgValueInst* NewIntrin = dyn_cast<DbgValueInst>(&NewI); EXPECT_TRUE(NewIntrin); // Old variable must belong to the old function EXPECT_EQ(OldFunc, cast<DISubprogram>(OldIntrin->getVariable()->getScope()) ->getFunction()); // New variable must belong to the New function EXPECT_EQ(NewFunc, cast<DISubprogram>(NewIntrin->getVariable()->getScope()) ->getFunction()); } ++OldIter; ++NewIter; } } class CloneModule : public ::testing::Test { protected: void SetUp() override { SetupModule(); CreateOldModule(); CreateNewModule(); } void SetupModule() { OldM = new Module("", C); } void CreateOldModule() { IRBuilder<> IBuilder(C); auto *FuncType = FunctionType::get(Type::getVoidTy(C), false); auto *PersFn = Function::Create(FuncType, GlobalValue::ExternalLinkage, "persfn", OldM); auto *F = Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", OldM); F->setPersonalityFn(PersFn); auto *Entry = BasicBlock::Create(C, "", F); IBuilder.SetInsertPoint(Entry); IBuilder.CreateRetVoid(); } void CreateNewModule() { NewM = llvm::CloneModule(OldM); } LLVMContext C; Module *OldM; Module *NewM; }; TEST_F(CloneModule, Verify) { EXPECT_FALSE(verifyModule(*NewM)); } }
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/Utils/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Core DXIL # HLSL Change Support TransformUtils ) add_llvm_unittest(UtilsTests ASanStackFrameLayoutTest.cpp Cloning.cpp IntegerDivision.cpp Local.cpp ValueMapperTest.cpp )
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/Utils/ASanStackFrameLayoutTest.cpp
//===- ASanStackFrameLayoutTest.cpp - Tests for ComputeASanStackFrameLayout===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/ASanStackFrameLayout.h" #include "llvm/ADT/ArrayRef.h" #include "gtest/gtest.h" #include <sstream> // // /////////////////////////////////////////////////////////////////////////////// using namespace llvm; static std::string ShadowBytesToString(ArrayRef<uint8_t> ShadowBytes) { std::ostringstream os; for (size_t i = 0, n = ShadowBytes.size(); i < n; i++) { switch (ShadowBytes[i]) { case kAsanStackLeftRedzoneMagic: os << "L"; break; case kAsanStackRightRedzoneMagic: os << "R"; break; case kAsanStackMidRedzoneMagic: os << "M"; break; default: os << (unsigned)ShadowBytes[i]; } } return os.str(); } static void TestLayout(SmallVector<ASanStackVariableDescription, 10> Vars, size_t Granularity, size_t MinHeaderSize, const std::string &ExpectedDescr, const std::string &ExpectedShadow) { ASanStackFrameLayout L; ComputeASanStackFrameLayout(Vars, Granularity, MinHeaderSize, &L); EXPECT_EQ(ExpectedDescr, L.DescriptionString); EXPECT_EQ(ExpectedShadow, ShadowBytesToString(L.ShadowBytes)); } TEST(ASanStackFrameLayout, Test) { #define VEC1(a) SmallVector<ASanStackVariableDescription, 10>(1, a) #define VEC(a) \ SmallVector<ASanStackVariableDescription, 10>(a, a + sizeof(a) / sizeof(a[0])) #define VAR(name, size, alignment) \ ASanStackVariableDescription name##size##_##alignment = { \ #name #size "_" #alignment, \ size, \ alignment, \ 0, \ 0 \ } VAR(a, 1, 1); VAR(p, 1, 32); VAR(p, 1, 256); VAR(a, 2, 1); VAR(a, 3, 1); VAR(a, 4, 1); VAR(a, 7, 1); VAR(a, 8, 1); VAR(a, 9, 1); VAR(a, 16, 1); VAR(a, 41, 1); VAR(a, 105, 1); TestLayout(VEC1(a1_1), 8, 16, "1 16 1 4 a1_1", "LL1R"); TestLayout(VEC1(a1_1), 64, 64, "1 64 1 4 a1_1", "L1"); TestLayout(VEC1(p1_32), 8, 32, "1 32 1 5 p1_32", "LLLL1RRR"); TestLayout(VEC1(p1_32), 8, 64, "1 64 1 5 p1_32", "LLLLLLLL1RRRRRRR"); TestLayout(VEC1(a1_1), 8, 32, "1 32 1 4 a1_1", "LLLL1RRR"); TestLayout(VEC1(a2_1), 8, 32, "1 32 2 4 a2_1", "LLLL2RRR"); TestLayout(VEC1(a3_1), 8, 32, "1 32 3 4 a3_1", "LLLL3RRR"); TestLayout(VEC1(a4_1), 8, 32, "1 32 4 4 a4_1", "LLLL4RRR"); TestLayout(VEC1(a7_1), 8, 32, "1 32 7 4 a7_1", "LLLL7RRR"); TestLayout(VEC1(a8_1), 8, 32, "1 32 8 4 a8_1", "LLLL0RRR"); TestLayout(VEC1(a9_1), 8, 32, "1 32 9 4 a9_1", "LLLL01RR"); TestLayout(VEC1(a16_1), 8, 32, "1 32 16 5 a16_1", "LLLL00RR"); TestLayout(VEC1(p1_256), 8, 32, "1 256 1 6 p1_256", "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL1RRR"); TestLayout(VEC1(a41_1), 8, 32, "1 32 41 5 a41_1", "LLLL000001RRRRRR"); TestLayout(VEC1(a105_1), 8, 32, "1 32 105 6 a105_1", "LLLL00000000000001RRRRRR"); { ASanStackVariableDescription t[] = {a1_1, p1_256}; TestLayout(VEC(t), 8, 32, "2 256 1 6 p1_256 272 1 4 a1_1", "LLLLLLLL" "LLLLLLLL" "LLLLLLLL" "LLLLLLLL" "1M1R"); } { ASanStackVariableDescription t[] = {a1_1, a16_1, a41_1}; TestLayout(VEC(t), 8, 32, "3 32 1 4 a1_1 48 16 5 a16_1 80 41 5 a41_1", "LLLL" "1M00" "MM00" "0001" "RRRR"); } #undef VEC1 #undef VEC #undef VAR }
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/Utils/Local.cpp
//===- Local.cpp - Unit tests for Local -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/Local.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; TEST(Local, RecursivelyDeleteDeadPHINodes) { LLVMContext &C(getGlobalContext()); IRBuilder<> builder(C); // Make blocks BasicBlock *bb0 = BasicBlock::Create(C); BasicBlock *bb1 = BasicBlock::Create(C); builder.SetInsertPoint(bb0); PHINode *phi = builder.CreatePHI(Type::getInt32Ty(C), 2); BranchInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1); builder.SetInsertPoint(bb1); BranchInst *br1 = builder.CreateBr(bb0); phi->addIncoming(phi, bb0); phi->addIncoming(phi, bb1); // The PHI will be removed EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); // Make sure the blocks only contain the branches EXPECT_EQ(&bb0->front(), br0); EXPECT_EQ(&bb1->front(), br1); builder.SetInsertPoint(bb0); phi = builder.CreatePHI(Type::getInt32Ty(C), 0); EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); builder.SetInsertPoint(bb0); phi = builder.CreatePHI(Type::getInt32Ty(C), 0); builder.CreateAdd(phi, phi); EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); bb0->dropAllReferences(); bb1->dropAllReferences(); delete bb0; delete bb1; }
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/Utils/ValueMapperTest.cpp
//===- ValueMapper.cpp - Unit tests for ValueMapper -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Metadata.h" #include "llvm/Transforms/Utils/ValueMapper.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(ValueMapperTest, MapMetadataUnresolved) { LLVMContext Context; TempMDTuple T = MDTuple::getTemporary(Context, None); ValueToValueMapTy VM; EXPECT_EQ(T.get(), MapMetadata(T.get(), VM, RF_NoModuleLevelChanges)); } }
0
repos/DirectXShaderCompiler/unittests/Transforms
repos/DirectXShaderCompiler/unittests/Transforms/Utils/IntegerDivision.cpp
//===- IntegerDivision.cpp - Unit tests for the integer division code -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/IntegerDivision.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(IntegerDivision, SDiv) { LLVMContext &C(getGlobalContext()); Module M("test division", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Div = Builder.CreateSDiv(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv); Value *Ret = Builder.CreateRet(Div); expandDivision(cast<BinaryOperator>(Div)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::AShr); Instruction* Quotient = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Quotient && Quotient->getOpcode() == Instruction::Sub); } TEST(IntegerDivision, UDiv) { LLVMContext &C(getGlobalContext()); Module M("test division", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Div = Builder.CreateUDiv(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv); Value *Ret = Builder.CreateRet(Div); expandDivision(cast<BinaryOperator>(Div)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::ICmp); Instruction* Quotient = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Quotient && Quotient->getOpcode() == Instruction::PHI); } TEST(IntegerDivision, SRem) { LLVMContext &C(getGlobalContext()); Module M("test remainder", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Rem = Builder.CreateSRem(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem); Value *Ret = Builder.CreateRet(Rem); expandRemainder(cast<BinaryOperator>(Rem)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::AShr); Instruction* Remainder = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Remainder && Remainder->getOpcode() == Instruction::Sub); } TEST(IntegerDivision, URem) { LLVMContext &C(getGlobalContext()); Module M("test remainder", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt32Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt32Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Rem = Builder.CreateURem(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem); Value *Ret = Builder.CreateRet(Rem); expandRemainder(cast<BinaryOperator>(Rem)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::ICmp); Instruction* Remainder = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Remainder && Remainder->getOpcode() == Instruction::Sub); } TEST(IntegerDivision, SDiv64) { LLVMContext &C(getGlobalContext()); Module M("test division", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Div = Builder.CreateSDiv(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::SDiv); Value *Ret = Builder.CreateRet(Div); expandDivision(cast<BinaryOperator>(Div)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::AShr); Instruction* Quotient = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Quotient && Quotient->getOpcode() == Instruction::Sub); } TEST(IntegerDivision, UDiv64) { LLVMContext &C(getGlobalContext()); Module M("test division", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Div = Builder.CreateUDiv(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::UDiv); Value *Ret = Builder.CreateRet(Div); expandDivision(cast<BinaryOperator>(Div)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::ICmp); Instruction* Quotient = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Quotient && Quotient->getOpcode() == Instruction::PHI); } TEST(IntegerDivision, SRem64) { LLVMContext &C(getGlobalContext()); Module M("test remainder", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Rem = Builder.CreateSRem(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::SRem); Value *Ret = Builder.CreateRet(Rem); expandRemainder(cast<BinaryOperator>(Rem)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::AShr); Instruction* Remainder = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Remainder && Remainder->getOpcode() == Instruction::Sub); } TEST(IntegerDivision, URem64) { LLVMContext &C(getGlobalContext()); Module M("test remainder", C); IRBuilder<> Builder(C); SmallVector<Type*, 2> ArgTys(2, Builder.getInt64Ty()); Function *F = Function::Create(FunctionType::get(Builder.getInt64Ty(), ArgTys, false), GlobalValue::ExternalLinkage, "F", &M); assert(F->getArgumentList().size() == 2); BasicBlock *BB = BasicBlock::Create(C, "", F); Builder.SetInsertPoint(BB); Function::arg_iterator AI = F->arg_begin(); Value *A = AI++; Value *B = AI++; Value *Rem = Builder.CreateURem(A, B); EXPECT_TRUE(BB->front().getOpcode() == Instruction::URem); Value *Ret = Builder.CreateRet(Rem); expandRemainder(cast<BinaryOperator>(Rem)); EXPECT_TRUE(BB->front().getOpcode() == Instruction::ICmp); Instruction* Remainder = dyn_cast<Instruction>(cast<User>(Ret)->getOperand(0)); EXPECT_TRUE(Remainder && Remainder->getOpcode() == Instruction::Sub); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/ValueHandleTest.cpp
//===- ValueHandleTest.cpp - ValueHandle tests ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/ValueHandle.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" #include <memory> using namespace llvm; namespace { class ValueHandle : public testing::Test { protected: Constant *ConstantV; std::unique_ptr<BitCastInst> BitcastV; ValueHandle() : ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)), BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))) { } }; class ConcreteCallbackVH : public CallbackVH { public: ConcreteCallbackVH(Value *V) : CallbackVH(V) {} }; TEST_F(ValueHandle, WeakVH_BasicOperation) { WeakVH WVH(BitcastV.get()); EXPECT_EQ(BitcastV.get(), WVH); WVH = ConstantV; EXPECT_EQ(ConstantV, WVH); // Make sure I can call a method on the underlying Value. It // doesn't matter which method. EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), WVH->getType()); EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (*WVH).getType()); WVH = BitcastV.get(); BitcastV->replaceAllUsesWith(ConstantV); EXPECT_EQ(WVH, BitcastV.get()); BitcastV.reset(); EXPECT_EQ(WVH, nullptr); } TEST_F(ValueHandle, WeakTrackingVH_BasicOperation) { WeakTrackingVH WVH(BitcastV.get()); EXPECT_EQ(BitcastV.get(), WVH); WVH = ConstantV; EXPECT_EQ(ConstantV, WVH); // Make sure I can call a method on the underlying Value. It // doesn't matter which method. EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), WVH->getType()); EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (*WVH).getType()); } TEST_F(ValueHandle, WeakTrackingVH_Comparisons) { WeakTrackingVH BitcastWVH(BitcastV.get()); WeakTrackingVH ConstantWVH(ConstantV); EXPECT_TRUE(BitcastWVH == BitcastWVH); EXPECT_TRUE(BitcastV.get() == BitcastWVH); EXPECT_TRUE(BitcastWVH == BitcastV.get()); EXPECT_FALSE(BitcastWVH == ConstantWVH); EXPECT_TRUE(BitcastWVH != ConstantWVH); EXPECT_TRUE(BitcastV.get() != ConstantWVH); EXPECT_TRUE(BitcastWVH != ConstantV); EXPECT_FALSE(BitcastWVH != BitcastWVH); // Cast to Value* so comparisons work. Value *BV = BitcastV.get(); Value *CV = ConstantV; EXPECT_EQ(BV < CV, BitcastWVH < ConstantWVH); EXPECT_EQ(BV <= CV, BitcastWVH <= ConstantWVH); EXPECT_EQ(BV > CV, BitcastWVH > ConstantWVH); EXPECT_EQ(BV >= CV, BitcastWVH >= ConstantWVH); EXPECT_EQ(BV < CV, BitcastV.get() < ConstantWVH); EXPECT_EQ(BV <= CV, BitcastV.get() <= ConstantWVH); EXPECT_EQ(BV > CV, BitcastV.get() > ConstantWVH); EXPECT_EQ(BV >= CV, BitcastV.get() >= ConstantWVH); EXPECT_EQ(BV < CV, BitcastWVH < ConstantV); EXPECT_EQ(BV <= CV, BitcastWVH <= ConstantV); EXPECT_EQ(BV > CV, BitcastWVH > ConstantV); EXPECT_EQ(BV >= CV, BitcastWVH >= ConstantV); } TEST_F(ValueHandle, WeakTrackingVH_FollowsRAUW) { WeakTrackingVH WVH(BitcastV.get()); WeakTrackingVH WVH_Copy(WVH); WeakTrackingVH WVH_Recreated(BitcastV.get()); BitcastV->replaceAllUsesWith(ConstantV); EXPECT_EQ(ConstantV, WVH); EXPECT_EQ(ConstantV, WVH_Copy); EXPECT_EQ(ConstantV, WVH_Recreated); } TEST_F(ValueHandle, WeakTrackingVH_NullOnDeletion) { WeakTrackingVH WVH(BitcastV.get()); WeakTrackingVH WVH_Copy(WVH); WeakTrackingVH WVH_Recreated(BitcastV.get()); BitcastV.reset(); Value *null_value = nullptr; EXPECT_EQ(null_value, WVH); EXPECT_EQ(null_value, WVH_Copy); EXPECT_EQ(null_value, WVH_Recreated); } TEST_F(ValueHandle, AssertingVH_BasicOperation) { AssertingVH<CastInst> AVH(BitcastV.get()); CastInst *implicit_to_exact_type = AVH; (void)implicit_to_exact_type; // Avoid warning. AssertingVH<Value> GenericAVH(BitcastV.get()); EXPECT_EQ(BitcastV.get(), GenericAVH); GenericAVH = ConstantV; EXPECT_EQ(ConstantV, GenericAVH); // Make sure I can call a method on the underlying CastInst. It // doesn't matter which method. EXPECT_FALSE(AVH->mayWriteToMemory()); EXPECT_FALSE((*AVH).mayWriteToMemory()); } TEST_F(ValueHandle, AssertingVH_Const) { const CastInst *ConstBitcast = BitcastV.get(); AssertingVH<const CastInst> AVH(ConstBitcast); const CastInst *implicit_to_exact_type = AVH; (void)implicit_to_exact_type; // Avoid warning. } TEST_F(ValueHandle, AssertingVH_Comparisons) { AssertingVH<Value> BitcastAVH(BitcastV.get()); AssertingVH<Value> ConstantAVH(ConstantV); EXPECT_TRUE(BitcastAVH == BitcastAVH); EXPECT_TRUE(BitcastV.get() == BitcastAVH); EXPECT_TRUE(BitcastAVH == BitcastV.get()); EXPECT_FALSE(BitcastAVH == ConstantAVH); EXPECT_TRUE(BitcastAVH != ConstantAVH); EXPECT_TRUE(BitcastV.get() != ConstantAVH); EXPECT_TRUE(BitcastAVH != ConstantV); EXPECT_FALSE(BitcastAVH != BitcastAVH); // Cast to Value* so comparisons work. Value *BV = BitcastV.get(); Value *CV = ConstantV; EXPECT_EQ(BV < CV, BitcastAVH < ConstantAVH); EXPECT_EQ(BV <= CV, BitcastAVH <= ConstantAVH); EXPECT_EQ(BV > CV, BitcastAVH > ConstantAVH); EXPECT_EQ(BV >= CV, BitcastAVH >= ConstantAVH); EXPECT_EQ(BV < CV, BitcastV.get() < ConstantAVH); EXPECT_EQ(BV <= CV, BitcastV.get() <= ConstantAVH); EXPECT_EQ(BV > CV, BitcastV.get() > ConstantAVH); EXPECT_EQ(BV >= CV, BitcastV.get() >= ConstantAVH); EXPECT_EQ(BV < CV, BitcastAVH < ConstantV); EXPECT_EQ(BV <= CV, BitcastAVH <= ConstantV); EXPECT_EQ(BV > CV, BitcastAVH > ConstantV); EXPECT_EQ(BV >= CV, BitcastAVH >= ConstantV); } TEST_F(ValueHandle, AssertingVH_DoesNotFollowRAUW) { AssertingVH<Value> AVH(BitcastV.get()); BitcastV->replaceAllUsesWith(ConstantV); EXPECT_EQ(BitcastV.get(), AVH); } #ifdef NDEBUG TEST_F(ValueHandle, AssertingVH_ReducesToPointer) { EXPECT_EQ(sizeof(CastInst *), sizeof(AssertingVH<CastInst>)); } #else // !NDEBUG TEST_F(ValueHandle, TrackingVH_Tracks) { { // HLSL Change TrackingVH<Value> VH(BitcastV.get()); BitcastV->replaceAllUsesWith(ConstantV); EXPECT_EQ(VH, ConstantV); } // HLSL Change // HLSL Change begin // This test is a DEATH_TEST in the original upstream change. It will // assert when accessing a TrackingVH is deleted. // However, DXC should follow the original TrackingVH implementation. // return Null is always ok instead of assert it. // Check the comment in TrackingVH::getValPtr() for more detail. { TrackingVH<Value> VH(BitcastV.get()); // The tracking handle shouldn't assert when the value is deleted. BitcastV.reset( new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))); // The handle should be nullptr after it's deleted. EXPECT_EQ(VH, nullptr); } // HLSL Change end } #ifdef GTEST_HAS_DEATH_TEST TEST_F(ValueHandle, AssertingVH_Asserts) { AssertingVH<Value> AVH(BitcastV.get()); EXPECT_DEATH({BitcastV.reset();}, "An asserting value handle still pointed to this value!"); AssertingVH<Value> Copy(AVH); AVH = nullptr; EXPECT_DEATH({BitcastV.reset();}, "An asserting value handle still pointed to this value!"); Copy = nullptr; BitcastV.reset(); } TEST_F(ValueHandle, TrackingVH_Asserts) { TrackingVH<Instruction> VH(BitcastV.get()); BitcastV->replaceAllUsesWith(ConstantV); EXPECT_DEATH((void)*VH, "Tracked Value was replaced by one with an invalid type!"); } #endif // GTEST_HAS_DEATH_TEST #endif // NDEBUG TEST_F(ValueHandle, CallbackVH_BasicOperation) { ConcreteCallbackVH CVH(BitcastV.get()); EXPECT_EQ(BitcastV.get(), CVH); CVH = ConstantV; EXPECT_EQ(ConstantV, CVH); // Make sure I can call a method on the underlying Value. It // doesn't matter which method. EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), CVH->getType()); EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (*CVH).getType()); } TEST_F(ValueHandle, CallbackVH_Comparisons) { ConcreteCallbackVH BitcastCVH(BitcastV.get()); ConcreteCallbackVH ConstantCVH(ConstantV); EXPECT_TRUE(BitcastCVH == BitcastCVH); EXPECT_TRUE(BitcastV.get() == BitcastCVH); EXPECT_TRUE(BitcastCVH == BitcastV.get()); EXPECT_FALSE(BitcastCVH == ConstantCVH); EXPECT_TRUE(BitcastCVH != ConstantCVH); EXPECT_TRUE(BitcastV.get() != ConstantCVH); EXPECT_TRUE(BitcastCVH != ConstantV); EXPECT_FALSE(BitcastCVH != BitcastCVH); // Cast to Value* so comparisons work. Value *BV = BitcastV.get(); Value *CV = ConstantV; EXPECT_EQ(BV < CV, BitcastCVH < ConstantCVH); EXPECT_EQ(BV <= CV, BitcastCVH <= ConstantCVH); EXPECT_EQ(BV > CV, BitcastCVH > ConstantCVH); EXPECT_EQ(BV >= CV, BitcastCVH >= ConstantCVH); EXPECT_EQ(BV < CV, BitcastV.get() < ConstantCVH); EXPECT_EQ(BV <= CV, BitcastV.get() <= ConstantCVH); EXPECT_EQ(BV > CV, BitcastV.get() > ConstantCVH); EXPECT_EQ(BV >= CV, BitcastV.get() >= ConstantCVH); EXPECT_EQ(BV < CV, BitcastCVH < ConstantV); EXPECT_EQ(BV <= CV, BitcastCVH <= ConstantV); EXPECT_EQ(BV > CV, BitcastCVH > ConstantV); EXPECT_EQ(BV >= CV, BitcastCVH >= ConstantV); } TEST_F(ValueHandle, CallbackVH_CallbackOnDeletion) { class RecordingVH : public CallbackVH { public: int DeletedCalls; int AURWCalls; RecordingVH() : DeletedCalls(0), AURWCalls(0) {} RecordingVH(Value *V) : CallbackVH(V), DeletedCalls(0), AURWCalls(0) {} private: void deleted() override { DeletedCalls++; CallbackVH::deleted(); } void allUsesReplacedWith(Value *) override { AURWCalls++; } }; RecordingVH RVH; RVH = BitcastV.get(); EXPECT_EQ(0, RVH.DeletedCalls); EXPECT_EQ(0, RVH.AURWCalls); BitcastV.reset(); EXPECT_EQ(1, RVH.DeletedCalls); EXPECT_EQ(0, RVH.AURWCalls); } TEST_F(ValueHandle, CallbackVH_CallbackOnRAUW) { class RecordingVH : public CallbackVH { public: int DeletedCalls; Value *AURWArgument; RecordingVH() : DeletedCalls(0), AURWArgument(nullptr) {} RecordingVH(Value *V) : CallbackVH(V), DeletedCalls(0), AURWArgument(nullptr) {} private: void deleted() override { DeletedCalls++; CallbackVH::deleted(); } void allUsesReplacedWith(Value *new_value) override { EXPECT_EQ(nullptr, AURWArgument); AURWArgument = new_value; } }; RecordingVH RVH; RVH = BitcastV.get(); EXPECT_EQ(0, RVH.DeletedCalls); EXPECT_EQ(nullptr, RVH.AURWArgument); BitcastV->replaceAllUsesWith(ConstantV); EXPECT_EQ(0, RVH.DeletedCalls); EXPECT_EQ(ConstantV, RVH.AURWArgument); } TEST_F(ValueHandle, CallbackVH_DeletionCanRAUW) { class RecoveringVH : public CallbackVH { public: int DeletedCalls; Value *AURWArgument; LLVMContext *Context; RecoveringVH() : DeletedCalls(0), AURWArgument(nullptr), Context(&getGlobalContext()) {} RecoveringVH(Value *V) : CallbackVH(V), DeletedCalls(0), AURWArgument(nullptr), Context(&getGlobalContext()) {} private: void deleted() override { getValPtr()->replaceAllUsesWith(Constant::getNullValue(Type::getInt32Ty(getGlobalContext()))); setValPtr(nullptr); } void allUsesReplacedWith(Value *new_value) override { ASSERT_TRUE(nullptr != getValPtr()); EXPECT_EQ(1U, getValPtr()->getNumUses()); EXPECT_EQ(nullptr, AURWArgument); AURWArgument = new_value; } }; // Normally, if a value has uses, deleting it will crash. However, we can use // a CallbackVH to remove the uses before the check for no uses. RecoveringVH RVH; RVH = BitcastV.get(); std::unique_ptr<BinaryOperator> BitcastUser( BinaryOperator::CreateAdd(RVH, Constant::getNullValue(Type::getInt32Ty(getGlobalContext())))); EXPECT_EQ(BitcastV.get(), BitcastUser->getOperand(0)); BitcastV.reset(); // Would crash without the ValueHandler. EXPECT_EQ(Constant::getNullValue(Type::getInt32Ty(getGlobalContext())), RVH.AURWArgument); EXPECT_EQ(Constant::getNullValue(Type::getInt32Ty(getGlobalContext())), BitcastUser->getOperand(0)); } TEST_F(ValueHandle, DestroyingOtherVHOnSameValueDoesntBreakIteration) { // When a CallbackVH modifies other ValueHandles in its callbacks, // that shouldn't interfere with non-modified ValueHandles receiving // their appropriate callbacks. // // We create the active CallbackVH in the middle of a palindromic // arrangement of other VHs so that the bad behavior would be // triggered in whichever order callbacks run. class DestroyingVH : public CallbackVH { public: std::unique_ptr<WeakTrackingVH> ToClear[2]; DestroyingVH(Value *V) { ToClear[0].reset(new WeakTrackingVH(V)); setValPtr(V); ToClear[1].reset(new WeakTrackingVH(V)); } void deleted() override { ToClear[0].reset(); ToClear[1].reset(); CallbackVH::deleted(); } void allUsesReplacedWith(Value *) override { ToClear[0].reset(); ToClear[1].reset(); } }; { WeakTrackingVH ShouldBeVisited1(BitcastV.get()); DestroyingVH C(BitcastV.get()); WeakTrackingVH ShouldBeVisited2(BitcastV.get()); BitcastV->replaceAllUsesWith(ConstantV); EXPECT_EQ(ConstantV, static_cast<Value*>(ShouldBeVisited1)); EXPECT_EQ(ConstantV, static_cast<Value*>(ShouldBeVisited2)); } { WeakTrackingVH ShouldBeVisited1(BitcastV.get()); DestroyingVH C(BitcastV.get()); WeakTrackingVH ShouldBeVisited2(BitcastV.get()); BitcastV.reset(); EXPECT_EQ(nullptr, static_cast<Value*>(ShouldBeVisited1)); EXPECT_EQ(nullptr, static_cast<Value*>(ShouldBeVisited2)); } } TEST_F(ValueHandle, AssertingVHCheckedLast) { // If a CallbackVH exists to clear out a group of AssertingVHs on // Value deletion, the CallbackVH should get a chance to do so // before the AssertingVHs assert. class ClearingVH : public CallbackVH { public: AssertingVH<Value> *ToClear[2]; ClearingVH(Value *V, AssertingVH<Value> &A0, AssertingVH<Value> &A1) : CallbackVH(V) { ToClear[0] = &A0; ToClear[1] = &A1; } void deleted() override { *ToClear[0] = nullptr; *ToClear[1] = nullptr; CallbackVH::deleted(); } }; AssertingVH<Value> A1, A2; A1 = BitcastV.get(); ClearingVH C(BitcastV.get(), A1, A2); A2 = BitcastV.get(); // C.deleted() should run first, clearing the two AssertingVHs, // which should prevent them from asserting. BitcastV.reset(); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/UseTest.cpp
//===- llvm/unittest/IR/UseTest.cpp - Use unit tests ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/User.h" #include "llvm/Support/Format.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(UseTest, sort) { LLVMContext C; const char *ModuleString = "define void @f(i32 %x) {\n" "entry:\n" " %v0 = add i32 %x, 0\n" " %v2 = add i32 %x, 2\n" " %v5 = add i32 %x, 5\n" " %v1 = add i32 %x, 1\n" " %v3 = add i32 %x, 3\n" " %v7 = add i32 %x, 7\n" " %v6 = add i32 %x, 6\n" " %v4 = add i32 %x, 4\n" " ret void\n" "}\n"; SMDiagnostic Err; char vnbuf[8]; std::unique_ptr<Module> M = parseAssemblyString(ModuleString, Err, C); Function *F = M->getFunction("f"); ASSERT_TRUE(F); ASSERT_TRUE(F->arg_begin() != F->arg_end()); Argument &X = *F->arg_begin(); ASSERT_EQ("x", X.getName()); X.sortUseList([](const Use &L, const Use &R) { return L.getUser()->getName() < R.getUser()->getName(); }); unsigned I = 0; for (User *U : X.users()) { format("v%u", I++).snprint(vnbuf, sizeof(vnbuf)); EXPECT_EQ(vnbuf, U->getName()); } ASSERT_EQ(8u, I); X.sortUseList([](const Use &L, const Use &R) { return L.getUser()->getName() > R.getUser()->getName(); }); I = 0; for (User *U : X.users()) { format("v%u", (7 - I++)).snprint(vnbuf, sizeof(vnbuf)); EXPECT_EQ(vnbuf, U->getName()); } ASSERT_EQ(8u, I); } TEST(UseTest, reverse) { LLVMContext C; const char *ModuleString = "define void @f(i32 %x) {\n" "entry:\n" " %v0 = add i32 %x, 0\n" " %v2 = add i32 %x, 2\n" " %v5 = add i32 %x, 5\n" " %v1 = add i32 %x, 1\n" " %v3 = add i32 %x, 3\n" " %v7 = add i32 %x, 7\n" " %v6 = add i32 %x, 6\n" " %v4 = add i32 %x, 4\n" " ret void\n" "}\n"; SMDiagnostic Err; char vnbuf[8]; std::unique_ptr<Module> M = parseAssemblyString(ModuleString, Err, C); Function *F = M->getFunction("f"); ASSERT_TRUE(F); ASSERT_TRUE(F->arg_begin() != F->arg_end()); Argument &X = *F->arg_begin(); ASSERT_EQ("x", X.getName()); X.sortUseList([](const Use &L, const Use &R) { return L.getUser()->getName() < R.getUser()->getName(); }); unsigned I = 0; for (User *U : X.users()) { format("v%u", I++).snprint(vnbuf, sizeof(vnbuf)); EXPECT_EQ(vnbuf, U->getName()); } ASSERT_EQ(8u, I); X.reverseUseList(); I = 0; for (User *U : X.users()) { format("v%u", (7 - I++)).snprint(vnbuf, sizeof(vnbuf)); EXPECT_EQ(vnbuf, U->getName()); } ASSERT_EQ(8u, I); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/PatternMatch.cpp
//===---- llvm/unittest/IR/PatternMatch.cpp - PatternMatch unit tests ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/NoFolder.h" #include "llvm/IR/Operator.h" #include "llvm/IR/PatternMatch.h" #include "llvm/IR/Type.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::PatternMatch; namespace { struct PatternMatchTest : ::testing::Test { LLVMContext Ctx; std::unique_ptr<Module> M; Function *F; BasicBlock *BB; IRBuilder<true, NoFolder> IRB; PatternMatchTest() : M(new Module("PatternMatchTestModule", Ctx)), F(Function::Create( FunctionType::get(Type::getVoidTy(Ctx), /* IsVarArg */ false), Function::ExternalLinkage, "f", M.get())), BB(BasicBlock::Create(Ctx, "entry", F)), IRB(BB) {} }; TEST_F(PatternMatchTest, OneUse) { // Build up a little tree of values: // // One = (1 + 2) + 42 // Two = One + 42 // Leaf = (Two + 8) + (Two + 13) Value *One = IRB.CreateAdd(IRB.CreateAdd(IRB.getInt32(1), IRB.getInt32(2)), IRB.getInt32(42)); Value *Two = IRB.CreateAdd(One, IRB.getInt32(42)); Value *Leaf = IRB.CreateAdd(IRB.CreateAdd(Two, IRB.getInt32(8)), IRB.CreateAdd(Two, IRB.getInt32(13))); Value *V; EXPECT_TRUE(m_OneUse(m_Value(V)).match(One)); EXPECT_EQ(One, V); EXPECT_FALSE(m_OneUse(m_Value()).match(Two)); EXPECT_FALSE(m_OneUse(m_Value()).match(Leaf)); } TEST_F(PatternMatchTest, FloatingPointOrderedMin) { Type *FltTy = IRB.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test OLT. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOLT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test OLE. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOLE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on OGE. EXPECT_FALSE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOGE(L, R), L, R))); // Test no match on OGT. EXPECT_FALSE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOGT(L, R), L, R))); // Test match on OGE with inverted select. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOGE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on OGT with inverted select. EXPECT_TRUE(m_OrdFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOGT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } TEST_F(PatternMatchTest, FloatingPointOrderedMax) { Type *FltTy = IRB.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test OGT. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOGT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test OGE. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOGE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on OLE. EXPECT_FALSE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOLE(L, R), L, R))); // Test no match on OLT. EXPECT_FALSE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOLT(L, R), L, R))); // Test match on OLE with inverted select. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOLE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on OLT with inverted select. EXPECT_TRUE(m_OrdFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpOLT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } TEST_F(PatternMatchTest, FloatingPointUnorderedMin) { Type *FltTy = IRB.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test ULT. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpULT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test ULE. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpULE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on UGE. EXPECT_FALSE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpUGE(L, R), L, R))); // Test no match on UGT. EXPECT_FALSE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpUGT(L, R), L, R))); // Test match on UGE with inverted select. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpUGE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on UGT with inverted select. EXPECT_TRUE(m_UnordFMin(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpUGT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } TEST_F(PatternMatchTest, FloatingPointUnorderedMax) { Type *FltTy = IRB.getFloatTy(); Value *L = ConstantFP::get(FltTy, 1.0); Value *R = ConstantFP::get(FltTy, 2.0); Value *MatchL, *MatchR; // Test UGT. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpUGT(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test UGE. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpUGE(L, R), L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test no match on ULE. EXPECT_FALSE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpULE(L, R), L, R))); // Test no match on ULT. EXPECT_FALSE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpULT(L, R), L, R))); // Test match on ULE with inverted select. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpULE(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); // Test match on ULT with inverted select. EXPECT_TRUE(m_UnordFMax(m_Value(MatchL), m_Value(MatchR)) .match(IRB.CreateSelect(IRB.CreateFCmpULT(L, R), R, L))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); } TEST_F(PatternMatchTest, OverflowingBinOps) { Value *L = IRB.getInt32(1); Value *R = IRB.getInt32(2); Value *MatchL, *MatchR; EXPECT_TRUE( m_NSWAdd(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNSWAdd(L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); MatchL = MatchR = nullptr; EXPECT_TRUE( m_NSWSub(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNSWSub(L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); MatchL = MatchR = nullptr; EXPECT_TRUE( m_NSWMul(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNSWMul(L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); MatchL = MatchR = nullptr; EXPECT_TRUE(m_NSWShl(m_Value(MatchL), m_Value(MatchR)).match( IRB.CreateShl(L, R, "", /* NUW */ false, /* NSW */ true))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); EXPECT_TRUE( m_NUWAdd(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNUWAdd(L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); MatchL = MatchR = nullptr; EXPECT_TRUE( m_NUWSub(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNUWSub(L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); MatchL = MatchR = nullptr; EXPECT_TRUE( m_NUWMul(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNUWMul(L, R))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); MatchL = MatchR = nullptr; EXPECT_TRUE(m_NUWShl(m_Value(MatchL), m_Value(MatchR)).match( IRB.CreateShl(L, R, "", /* NUW */ true, /* NSW */ false))); EXPECT_EQ(L, MatchL); EXPECT_EQ(R, MatchR); EXPECT_FALSE(m_NSWAdd(m_Value(), m_Value()).match(IRB.CreateAdd(L, R))); EXPECT_FALSE(m_NSWAdd(m_Value(), m_Value()).match(IRB.CreateNUWAdd(L, R))); EXPECT_FALSE(m_NSWAdd(m_Value(), m_Value()).match(IRB.CreateNSWSub(L, R))); EXPECT_FALSE(m_NSWSub(m_Value(), m_Value()).match(IRB.CreateSub(L, R))); EXPECT_FALSE(m_NSWSub(m_Value(), m_Value()).match(IRB.CreateNUWSub(L, R))); EXPECT_FALSE(m_NSWSub(m_Value(), m_Value()).match(IRB.CreateNSWAdd(L, R))); EXPECT_FALSE(m_NSWMul(m_Value(), m_Value()).match(IRB.CreateMul(L, R))); EXPECT_FALSE(m_NSWMul(m_Value(), m_Value()).match(IRB.CreateNUWMul(L, R))); EXPECT_FALSE(m_NSWMul(m_Value(), m_Value()).match(IRB.CreateNSWAdd(L, R))); EXPECT_FALSE(m_NSWShl(m_Value(), m_Value()).match(IRB.CreateShl(L, R))); EXPECT_FALSE(m_NSWShl(m_Value(), m_Value()).match( IRB.CreateShl(L, R, "", /* NUW */ true, /* NSW */ false))); EXPECT_FALSE(m_NSWShl(m_Value(), m_Value()).match(IRB.CreateNSWAdd(L, R))); EXPECT_FALSE(m_NUWAdd(m_Value(), m_Value()).match(IRB.CreateAdd(L, R))); EXPECT_FALSE(m_NUWAdd(m_Value(), m_Value()).match(IRB.CreateNSWAdd(L, R))); EXPECT_FALSE(m_NUWAdd(m_Value(), m_Value()).match(IRB.CreateNUWSub(L, R))); EXPECT_FALSE(m_NUWSub(m_Value(), m_Value()).match(IRB.CreateSub(L, R))); EXPECT_FALSE(m_NUWSub(m_Value(), m_Value()).match(IRB.CreateNSWSub(L, R))); EXPECT_FALSE(m_NUWSub(m_Value(), m_Value()).match(IRB.CreateNUWAdd(L, R))); EXPECT_FALSE(m_NUWMul(m_Value(), m_Value()).match(IRB.CreateMul(L, R))); EXPECT_FALSE(m_NUWMul(m_Value(), m_Value()).match(IRB.CreateNSWMul(L, R))); EXPECT_FALSE(m_NUWMul(m_Value(), m_Value()).match(IRB.CreateNUWAdd(L, R))); EXPECT_FALSE(m_NUWShl(m_Value(), m_Value()).match(IRB.CreateShl(L, R))); EXPECT_FALSE(m_NUWShl(m_Value(), m_Value()).match( IRB.CreateShl(L, R, "", /* NUW */ false, /* NSW */ true))); EXPECT_FALSE(m_NUWShl(m_Value(), m_Value()).match(IRB.CreateNUWAdd(L, R))); } } // anonymous namespace.
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/DebugInfoTest.cpp
//===- llvm/unittest/IR/DebugInfo.cpp - DebugInfo tests -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/DebugInfoMetadata.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(DINodeTest, getFlag) { // Some valid flags. EXPECT_EQ(DINode::FlagPublic, DINode::getFlag("DIFlagPublic")); EXPECT_EQ(DINode::FlagProtected, DINode::getFlag("DIFlagProtected")); EXPECT_EQ(DINode::FlagPrivate, DINode::getFlag("DIFlagPrivate")); EXPECT_EQ(DINode::FlagVector, DINode::getFlag("DIFlagVector")); EXPECT_EQ(DINode::FlagRValueReference, DINode::getFlag("DIFlagRValueReference")); // FlagAccessibility shouldn't work. EXPECT_EQ(0u, DINode::getFlag("DIFlagAccessibility")); // Some other invalid strings. EXPECT_EQ(0u, DINode::getFlag("FlagVector")); EXPECT_EQ(0u, DINode::getFlag("Vector")); EXPECT_EQ(0u, DINode::getFlag("other things")); EXPECT_EQ(0u, DINode::getFlag("DIFlagOther")); } TEST(DINodeTest, getFlagString) { // Some valid flags. EXPECT_EQ(StringRef("DIFlagPublic"), DINode::getFlagString(DINode::FlagPublic)); EXPECT_EQ(StringRef("DIFlagProtected"), DINode::getFlagString(DINode::FlagProtected)); EXPECT_EQ(StringRef("DIFlagPrivate"), DINode::getFlagString(DINode::FlagPrivate)); EXPECT_EQ(StringRef("DIFlagVector"), DINode::getFlagString(DINode::FlagVector)); EXPECT_EQ(StringRef("DIFlagRValueReference"), DINode::getFlagString(DINode::FlagRValueReference)); // FlagAccessibility actually equals FlagPublic. EXPECT_EQ(StringRef("DIFlagPublic"), DINode::getFlagString(DINode::FlagAccessibility)); // Some other invalid flags. EXPECT_EQ(StringRef(), DINode::getFlagString(DINode::FlagPublic | DINode::FlagVector)); EXPECT_EQ(StringRef(), DINode::getFlagString(DINode::FlagFwdDecl | DINode::FlagArtificial)); EXPECT_EQ(StringRef(), DINode::getFlagString(0xffff)); } TEST(DINodeTest, splitFlags) { // Some valid flags. #define CHECK_SPLIT(FLAGS, VECTOR, REMAINDER) \ { \ SmallVector<unsigned, 8> V; \ EXPECT_EQ(REMAINDER, DINode::splitFlags(FLAGS, V)); \ EXPECT_TRUE(makeArrayRef(V).equals(VECTOR)); \ } CHECK_SPLIT(DINode::FlagPublic, {DINode::FlagPublic}, 0u); CHECK_SPLIT(DINode::FlagProtected, {DINode::FlagProtected}, 0u); CHECK_SPLIT(DINode::FlagPrivate, {DINode::FlagPrivate}, 0u); CHECK_SPLIT(DINode::FlagVector, {DINode::FlagVector}, 0u); CHECK_SPLIT(DINode::FlagRValueReference, {DINode::FlagRValueReference}, 0u); unsigned Flags[] = {DINode::FlagFwdDecl, DINode::FlagVector}; CHECK_SPLIT(DINode::FlagFwdDecl | DINode::FlagVector, Flags, 0u); CHECK_SPLIT(0x100000u, {}, 0x100000u); CHECK_SPLIT(0x100000u | DINode::FlagVector, {DINode::FlagVector}, 0x100000u); #undef CHECK_SPLIT } } // end namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/IRBuilderTest.cpp
//===- llvm/unittest/IR/IRBuilderTest.cpp - IRBuilder tests ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/IRBuilder.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/Function.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/NoFolder.h" #include "llvm/IR/Verifier.h" #include "gtest/gtest.h" using namespace llvm; namespace { class IRBuilderTest : public testing::Test { protected: void SetUp() override { M.reset(new Module("MyModule", Ctx)); FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), /*isVarArg=*/false); F = Function::Create(FTy, Function::ExternalLinkage, "", M.get()); BB = BasicBlock::Create(Ctx, "", F); GV = new GlobalVariable(*M, Type::getFloatTy(Ctx), true, GlobalValue::ExternalLinkage, nullptr); } void TearDown() override { BB = nullptr; M.reset(); } LLVMContext Ctx; std::unique_ptr<Module> M; Function *F; BasicBlock *BB; GlobalVariable *GV; }; TEST_F(IRBuilderTest, Lifetime) { IRBuilder<> Builder(BB); AllocaInst *Var1 = Builder.CreateAlloca(Builder.getInt8Ty()); AllocaInst *Var2 = Builder.CreateAlloca(Builder.getInt32Ty()); AllocaInst *Var3 = Builder.CreateAlloca(Builder.getInt8Ty(), Builder.getInt32(123)); CallInst *Start1 = Builder.CreateLifetimeStart(Var1); CallInst *Start2 = Builder.CreateLifetimeStart(Var2); CallInst *Start3 = Builder.CreateLifetimeStart(Var3, Builder.getInt64(100)); EXPECT_EQ(Start1->getArgOperand(0), Builder.getInt64(-1)); EXPECT_EQ(Start2->getArgOperand(0), Builder.getInt64(-1)); EXPECT_EQ(Start3->getArgOperand(0), Builder.getInt64(100)); EXPECT_EQ(Start1->getArgOperand(1), Var1); EXPECT_NE(Start2->getArgOperand(1), Var2); EXPECT_EQ(Start3->getArgOperand(1), Var3); Value *End1 = Builder.CreateLifetimeEnd(Var1); Builder.CreateLifetimeEnd(Var2); Builder.CreateLifetimeEnd(Var3); IntrinsicInst *II_Start1 = dyn_cast<IntrinsicInst>(Start1); IntrinsicInst *II_End1 = dyn_cast<IntrinsicInst>(End1); ASSERT_TRUE(II_Start1 != nullptr); EXPECT_EQ(II_Start1->getIntrinsicID(), Intrinsic::lifetime_start); ASSERT_TRUE(II_End1 != nullptr); EXPECT_EQ(II_End1->getIntrinsicID(), Intrinsic::lifetime_end); } TEST_F(IRBuilderTest, CreateCondBr) { IRBuilder<> Builder(BB); BasicBlock *TBB = BasicBlock::Create(Ctx, "", F); BasicBlock *FBB = BasicBlock::Create(Ctx, "", F); BranchInst *BI = Builder.CreateCondBr(Builder.getTrue(), TBB, FBB); TerminatorInst *TI = BB->getTerminator(); EXPECT_EQ(BI, TI); EXPECT_EQ(2u, TI->getNumSuccessors()); EXPECT_EQ(TBB, TI->getSuccessor(0)); EXPECT_EQ(FBB, TI->getSuccessor(1)); BI->eraseFromParent(); MDNode *Weights = MDBuilder(Ctx).createBranchWeights(42, 13); BI = Builder.CreateCondBr(Builder.getTrue(), TBB, FBB, Weights); TI = BB->getTerminator(); EXPECT_EQ(BI, TI); EXPECT_EQ(2u, TI->getNumSuccessors()); EXPECT_EQ(TBB, TI->getSuccessor(0)); EXPECT_EQ(FBB, TI->getSuccessor(1)); EXPECT_EQ(Weights, TI->getMetadata(LLVMContext::MD_prof)); } TEST_F(IRBuilderTest, LandingPadName) { IRBuilder<> Builder(BB); LandingPadInst *LP = Builder.CreateLandingPad(Builder.getInt32Ty(), 0, "LP"); EXPECT_EQ(LP->getName(), "LP"); } TEST_F(IRBuilderTest, DataLayout) { std::unique_ptr<Module> M(new Module("test", Ctx)); M->setDataLayout("e-n32"); EXPECT_TRUE(M->getDataLayout().isLegalInteger(32)); M->setDataLayout("e"); EXPECT_FALSE(M->getDataLayout().isLegalInteger(32)); } TEST_F(IRBuilderTest, GetIntTy) { IRBuilder<> Builder(BB); IntegerType *Ty1 = Builder.getInt1Ty(); EXPECT_EQ(Ty1, IntegerType::get(Ctx, 1)); DataLayout* DL = new DataLayout(M.get()); IntegerType *IntPtrTy = Builder.getIntPtrTy(*DL); unsigned IntPtrBitSize = DL->getPointerSizeInBits(0); EXPECT_EQ(IntPtrTy, IntegerType::get(Ctx, IntPtrBitSize)); delete DL; } TEST_F(IRBuilderTest, FastMathFlags) { IRBuilder<> Builder(BB); Value *F, *FC; Instruction *FDiv, *FAdd, *FCmp; F = Builder.CreateLoad(GV); F = Builder.CreateFAdd(F, F); EXPECT_FALSE(Builder.getFastMathFlags().any()); ASSERT_TRUE(isa<Instruction>(F)); FAdd = cast<Instruction>(F); EXPECT_FALSE(FAdd->hasNoNaNs()); FastMathFlags FMF; Builder.SetFastMathFlags(FMF); F = Builder.CreateFAdd(F, F); EXPECT_FALSE(Builder.getFastMathFlags().any()); FMF.setUnsafeAlgebra(); Builder.SetFastMathFlags(FMF); F = Builder.CreateFAdd(F, F); EXPECT_TRUE(Builder.getFastMathFlags().any()); ASSERT_TRUE(isa<Instruction>(F)); FAdd = cast<Instruction>(F); EXPECT_TRUE(FAdd->hasNoNaNs()); // Now, try it with CreateBinOp F = Builder.CreateBinOp(Instruction::FAdd, F, F); EXPECT_TRUE(Builder.getFastMathFlags().any()); ASSERT_TRUE(isa<Instruction>(F)); FAdd = cast<Instruction>(F); EXPECT_TRUE(FAdd->hasNoNaNs()); F = Builder.CreateFDiv(F, F); EXPECT_TRUE(Builder.getFastMathFlags().any()); EXPECT_TRUE(Builder.getFastMathFlags().UnsafeAlgebra); ASSERT_TRUE(isa<Instruction>(F)); FDiv = cast<Instruction>(F); EXPECT_TRUE(FDiv->hasAllowReciprocal()); Builder.clearFastMathFlags(); F = Builder.CreateFDiv(F, F); ASSERT_TRUE(isa<Instruction>(F)); FDiv = cast<Instruction>(F); EXPECT_FALSE(FDiv->hasAllowReciprocal()); FMF.clear(); FMF.setAllowReciprocal(); Builder.SetFastMathFlags(FMF); F = Builder.CreateFDiv(F, F); EXPECT_TRUE(Builder.getFastMathFlags().any()); EXPECT_TRUE(Builder.getFastMathFlags().AllowReciprocal); ASSERT_TRUE(isa<Instruction>(F)); FDiv = cast<Instruction>(F); EXPECT_TRUE(FDiv->hasAllowReciprocal()); Builder.clearFastMathFlags(); FC = Builder.CreateFCmpOEQ(F, F); ASSERT_TRUE(isa<Instruction>(FC)); FCmp = cast<Instruction>(FC); EXPECT_FALSE(FCmp->hasAllowReciprocal()); FMF.clear(); FMF.setAllowReciprocal(); Builder.SetFastMathFlags(FMF); FC = Builder.CreateFCmpOEQ(F, F); EXPECT_TRUE(Builder.getFastMathFlags().any()); EXPECT_TRUE(Builder.getFastMathFlags().AllowReciprocal); ASSERT_TRUE(isa<Instruction>(FC)); FCmp = cast<Instruction>(FC); EXPECT_TRUE(FCmp->hasAllowReciprocal()); Builder.clearFastMathFlags(); // To test a copy, make sure that a '0' and a '1' change state. F = Builder.CreateFDiv(F, F); ASSERT_TRUE(isa<Instruction>(F)); FDiv = cast<Instruction>(F); EXPECT_FALSE(FDiv->getFastMathFlags().any()); FDiv->setHasAllowReciprocal(true); FAdd->setHasAllowReciprocal(false); FDiv->copyFastMathFlags(FAdd); EXPECT_TRUE(FDiv->hasNoNaNs()); EXPECT_FALSE(FDiv->hasAllowReciprocal()); } TEST_F(IRBuilderTest, WrapFlags) { IRBuilder<true, NoFolder> Builder(BB); // Test instructions. GlobalVariable *G = new GlobalVariable(*M, Builder.getInt32Ty(), true, GlobalValue::ExternalLinkage, nullptr); Value *V = Builder.CreateLoad(G); EXPECT_TRUE( cast<BinaryOperator>(Builder.CreateNSWAdd(V, V))->hasNoSignedWrap()); EXPECT_TRUE( cast<BinaryOperator>(Builder.CreateNSWMul(V, V))->hasNoSignedWrap()); EXPECT_TRUE( cast<BinaryOperator>(Builder.CreateNSWSub(V, V))->hasNoSignedWrap()); EXPECT_TRUE(cast<BinaryOperator>( Builder.CreateShl(V, V, "", /* NUW */ false, /* NSW */ true)) ->hasNoSignedWrap()); EXPECT_TRUE( cast<BinaryOperator>(Builder.CreateNUWAdd(V, V))->hasNoUnsignedWrap()); EXPECT_TRUE( cast<BinaryOperator>(Builder.CreateNUWMul(V, V))->hasNoUnsignedWrap()); EXPECT_TRUE( cast<BinaryOperator>(Builder.CreateNUWSub(V, V))->hasNoUnsignedWrap()); EXPECT_TRUE(cast<BinaryOperator>( Builder.CreateShl(V, V, "", /* NUW */ true, /* NSW */ false)) ->hasNoUnsignedWrap()); // Test operators created with constants. Constant *C = Builder.getInt32(42); EXPECT_TRUE(cast<OverflowingBinaryOperator>(Builder.CreateNSWAdd(C, C)) ->hasNoSignedWrap()); EXPECT_TRUE(cast<OverflowingBinaryOperator>(Builder.CreateNSWSub(C, C)) ->hasNoSignedWrap()); EXPECT_TRUE(cast<OverflowingBinaryOperator>(Builder.CreateNSWMul(C, C)) ->hasNoSignedWrap()); EXPECT_TRUE(cast<OverflowingBinaryOperator>( Builder.CreateShl(C, C, "", /* NUW */ false, /* NSW */ true)) ->hasNoSignedWrap()); EXPECT_TRUE(cast<OverflowingBinaryOperator>(Builder.CreateNUWAdd(C, C)) ->hasNoUnsignedWrap()); EXPECT_TRUE(cast<OverflowingBinaryOperator>(Builder.CreateNUWSub(C, C)) ->hasNoUnsignedWrap()); EXPECT_TRUE(cast<OverflowingBinaryOperator>(Builder.CreateNUWMul(C, C)) ->hasNoUnsignedWrap()); EXPECT_TRUE(cast<OverflowingBinaryOperator>( Builder.CreateShl(C, C, "", /* NUW */ true, /* NSW */ false)) ->hasNoUnsignedWrap()); } TEST_F(IRBuilderTest, RAIIHelpersTest) { IRBuilder<> Builder(BB); EXPECT_FALSE(Builder.getFastMathFlags().allowReciprocal()); MDBuilder MDB(M->getContext()); MDNode *FPMathA = MDB.createFPMath(0.01f); MDNode *FPMathB = MDB.createFPMath(0.1f); Builder.SetDefaultFPMathTag(FPMathA); { IRBuilder<>::FastMathFlagGuard Guard(Builder); FastMathFlags FMF; FMF.setAllowReciprocal(); Builder.SetFastMathFlags(FMF); Builder.SetDefaultFPMathTag(FPMathB); EXPECT_TRUE(Builder.getFastMathFlags().allowReciprocal()); EXPECT_EQ(FPMathB, Builder.getDefaultFPMathTag()); } EXPECT_FALSE(Builder.getFastMathFlags().allowReciprocal()); EXPECT_EQ(FPMathA, Builder.getDefaultFPMathTag()); Value *F = Builder.CreateLoad(GV); { IRBuilder<>::InsertPointGuard Guard(Builder); Builder.SetInsertPoint(cast<Instruction>(F)); EXPECT_EQ(F, Builder.GetInsertPoint()); } EXPECT_EQ(BB->end(), Builder.GetInsertPoint()); EXPECT_EQ(BB, Builder.GetInsertBlock()); } TEST_F(IRBuilderTest, DIBuilder) { IRBuilder<> Builder(BB); DIBuilder DIB(*M); auto File = DIB.createFile("F.CBL", "/"); auto CU = DIB.createCompileUnit(dwarf::DW_LANG_Cobol74, "F.CBL", "/", "llvm-cobol74", true, "", 0); auto Type = DIB.createSubroutineType(File, DIB.getOrCreateTypeArray(None)); DIB.createFunction(CU, "foo", "", File, 1, Type, false, true, 1, 0, true, F); AllocaInst *I = Builder.CreateAlloca(Builder.getInt8Ty()); auto BarSP = DIB.createFunction(CU, "bar", "", File, 1, Type, false, true, 1, 0, true, nullptr); auto BadScope = DIB.createLexicalBlockFile(BarSP, File, 0); I->setDebugLoc(DebugLoc::get(2, 0, BadScope)); DIB.finalize(); EXPECT_TRUE(verifyModule(*M)); } TEST_F(IRBuilderTest, InsertExtractElement) { IRBuilder<> Builder(BB); auto VecTy = VectorType::get(Builder.getInt64Ty(), 4); auto Elt1 = Builder.getInt64(-1); auto Elt2 = Builder.getInt64(-2); Value *Vec = UndefValue::get(VecTy); Vec = Builder.CreateInsertElement(Vec, Elt1, Builder.getInt8(1)); Vec = Builder.CreateInsertElement(Vec, Elt2, 2); auto X1 = Builder.CreateExtractElement(Vec, 1); auto X2 = Builder.CreateExtractElement(Vec, Builder.getInt32(2)); EXPECT_EQ(Elt1, X1); EXPECT_EQ(Elt2, X2); } TEST_F(IRBuilderTest, CreateGlobalStringPtr) { IRBuilder<> Builder(BB); auto String1a = Builder.CreateGlobalStringPtr("TestString", "String1a"); auto String1b = Builder.CreateGlobalStringPtr("TestString", "String1b", 0); auto String2 = Builder.CreateGlobalStringPtr("TestString", "String2", 1); auto String3 = Builder.CreateGlobalString("TestString", "String3", 2); EXPECT_TRUE(String1a->getType()->getPointerAddressSpace() == 0); EXPECT_TRUE(String1b->getType()->getPointerAddressSpace() == 0); EXPECT_TRUE(String2->getType()->getPointerAddressSpace() == 1); EXPECT_TRUE(String3->getType()->getPointerAddressSpace() == 2); } TEST_F(IRBuilderTest, DebugLoc) { auto CalleeTy = FunctionType::get(Type::getVoidTy(Ctx), /*isVarArg=*/false); auto Callee = Function::Create(CalleeTy, Function::ExternalLinkage, "", M.get()); DIBuilder DIB(*M); auto File = DIB.createFile("tmp.cpp", "/"); auto CU = DIB.createCompileUnit(dwarf::DW_LANG_C_plus_plus_11, "tmp.cpp", "/", "", true, "", 0); auto SPType = DIB.createSubroutineType(File, DIB.getOrCreateTypeArray(None)); auto SP = DIB.createFunction(CU, "foo", "foo", File, 1, SPType, false, true, 1); DebugLoc DL1 = DILocation::get(Ctx, 2, 0, SP); DebugLoc DL2 = DILocation::get(Ctx, 3, 0, SP); auto BB2 = BasicBlock::Create(Ctx, "bb2", F); auto Br = BranchInst::Create(BB2, BB); Br->setDebugLoc(DL1); IRBuilder<> Builder(Ctx); Builder.SetInsertPoint(Br); EXPECT_EQ(DL1, Builder.getCurrentDebugLocation()); auto Call1 = Builder.CreateCall(Callee, None); EXPECT_EQ(DL1, Call1->getDebugLoc()); Call1->setDebugLoc(DL2); Builder.SetInsertPoint(Call1->getParent(), Call1); EXPECT_EQ(DL2, Builder.getCurrentDebugLocation()); auto Call2 = Builder.CreateCall(Callee, None); EXPECT_EQ(DL2, Call2->getDebugLoc()); DIB.finalize(); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/VerifierTest.cpp
//===- llvm/unittest/IR/VerifierTest.cpp - Verifier unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Verifier.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "gtest/gtest.h" namespace llvm { namespace { TEST(VerifierTest, Branch_i1) { LLVMContext &C = getGlobalContext(); Module M("M", C); FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg=*/false); Function *F = cast<Function>(M.getOrInsertFunction("foo", FTy)); BasicBlock *Entry = BasicBlock::Create(C, "entry", F); BasicBlock *Exit = BasicBlock::Create(C, "exit", F); ReturnInst::Create(C, Exit); // To avoid triggering an assertion in BranchInst::Create, we first create // a branch with an 'i1' condition ... Constant *False = ConstantInt::getFalse(C); BranchInst *BI = BranchInst::Create(Exit, Exit, False, Entry); // ... then use setOperand to redirect it to a value of different type. Constant *Zero32 = ConstantInt::get(IntegerType::get(C, 32), 0); BI->setOperand(0, Zero32); EXPECT_TRUE(verifyFunction(*F)); } TEST(VerifierTest, InvalidRetAttribute) { LLVMContext &C = getGlobalContext(); Module M("M", C); FunctionType *FTy = FunctionType::get(Type::getInt32Ty(C), /*isVarArg=*/false); Function *F = cast<Function>(M.getOrInsertFunction("foo", FTy)); AttributeSet AS = F->getAttributes(); F->setAttributes(AS.addAttribute(C, AttributeSet::ReturnIndex, Attribute::UWTable)); std::string Error; raw_string_ostream ErrorOS(Error); EXPECT_TRUE(verifyModule(M, &ErrorOS)); EXPECT_TRUE(StringRef(ErrorOS.str()).startswith( "Attribute 'uwtable' only applies to functions!")); } } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/MetadataTest.cpp
//===- unittests/IR/MetadataTest.cpp - Metadata unit tests ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/IR/ModuleSlotTracker.h" #include "llvm/IR/Type.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(ContextAndReplaceableUsesTest, FromContext) { LLVMContext Context; ContextAndReplaceableUses CRU(Context); EXPECT_EQ(&Context, &CRU.getContext()); EXPECT_FALSE(CRU.hasReplaceableUses()); EXPECT_FALSE(CRU.getReplaceableUses()); } TEST(ContextAndReplaceableUsesTest, FromReplaceableUses) { LLVMContext Context; ContextAndReplaceableUses CRU(make_unique<ReplaceableMetadataImpl>(Context)); EXPECT_EQ(&Context, &CRU.getContext()); EXPECT_TRUE(CRU.hasReplaceableUses()); EXPECT_TRUE(CRU.getReplaceableUses()); } TEST(ContextAndReplaceableUsesTest, makeReplaceable) { LLVMContext Context; ContextAndReplaceableUses CRU(Context); CRU.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context)); EXPECT_EQ(&Context, &CRU.getContext()); EXPECT_TRUE(CRU.hasReplaceableUses()); EXPECT_TRUE(CRU.getReplaceableUses()); } TEST(ContextAndReplaceableUsesTest, takeReplaceableUses) { LLVMContext Context; auto ReplaceableUses = make_unique<ReplaceableMetadataImpl>(Context); auto *Ptr = ReplaceableUses.get(); ContextAndReplaceableUses CRU(std::move(ReplaceableUses)); ReplaceableUses = CRU.takeReplaceableUses(); EXPECT_EQ(&Context, &CRU.getContext()); EXPECT_FALSE(CRU.hasReplaceableUses()); EXPECT_FALSE(CRU.getReplaceableUses()); EXPECT_EQ(Ptr, ReplaceableUses.get()); } class MetadataTest : public testing::Test { public: MetadataTest() : M("test", Context), Counter(0) {} protected: LLVMContext Context; Module M; int Counter; MDNode *getNode() { return MDNode::get(Context, None); } MDNode *getNode(Metadata *MD) { return MDNode::get(Context, MD); } MDNode *getNode(Metadata *MD1, Metadata *MD2) { Metadata *MDs[] = {MD1, MD2}; return MDNode::get(Context, MDs); } MDTuple *getTuple() { return MDTuple::getDistinct(Context, None); } DISubroutineType *getSubroutineType() { return DISubroutineType::getDistinct(Context, 0, getNode(nullptr)); } DISubprogram *getSubprogram() { return DISubprogram::getDistinct(Context, nullptr, "", "", nullptr, 0, nullptr, false, false, 0, nullptr, 0, 0, 0, 0); } DIScopeRef getSubprogramRef() { return getSubprogram()->getRef(); } DIFile *getFile() { return DIFile::getDistinct(Context, "file.c", "/path/to/dir"); } DITypeRef getBasicType(StringRef Name) { return DIBasicType::get(Context, dwarf::DW_TAG_unspecified_type, Name) ->getRef(); } DITypeRef getDerivedType() { return DIDerivedType::getDistinct(Context, dwarf::DW_TAG_pointer_type, "", nullptr, 0, nullptr, getBasicType("basictype"), 1, 2, 0, 0) ->getRef(); } Constant *getConstant() { return ConstantInt::get(Type::getInt32Ty(Context), Counter++); } ConstantAsMetadata *getConstantAsMetadata() { return ConstantAsMetadata::get(getConstant()); } DITypeRef getCompositeType() { return DICompositeType::getDistinct( Context, dwarf::DW_TAG_structure_type, "", nullptr, 0, nullptr, nullptr, 32, 32, 0, 0, nullptr, 0, nullptr, nullptr, "") ->getRef(); } Function *getFunction(StringRef Name) { return cast<Function>(M.getOrInsertFunction( Name, FunctionType::get(Type::getVoidTy(Context), None, false))); } }; typedef MetadataTest MDStringTest; // Test that construction of MDString with different value produces different // MDString objects, even with the same string pointer and nulls in the string. TEST_F(MDStringTest, CreateDifferent) { char x[3] = { 'f', 0, 'A' }; MDString *s1 = MDString::get(Context, StringRef(&x[0], 3)); x[2] = 'B'; MDString *s2 = MDString::get(Context, StringRef(&x[0], 3)); EXPECT_NE(s1, s2); } // Test that creation of MDStrings with the same string contents produces the // same MDString object, even with different pointers. TEST_F(MDStringTest, CreateSame) { char x[4] = { 'a', 'b', 'c', 'X' }; char y[4] = { 'a', 'b', 'c', 'Y' }; MDString *s1 = MDString::get(Context, StringRef(&x[0], 3)); MDString *s2 = MDString::get(Context, StringRef(&y[0], 3)); EXPECT_EQ(s1, s2); } // Test that MDString prints out the string we fed it. TEST_F(MDStringTest, PrintingSimple) { char *str = new char[13]; strncpy(str, "testing 1 2 3", 13); MDString *s = MDString::get(Context, StringRef(str, 13)); strncpy(str, "aaaaaaaaaaaaa", 13); delete[] str; std::string Str; raw_string_ostream oss(Str); s->print(oss); EXPECT_STREQ("!\"testing 1 2 3\"", oss.str().c_str()); } // Test printing of MDString with non-printable characters. TEST_F(MDStringTest, PrintingComplex) { char str[5] = {0, '\n', '"', '\\', (char)-1}; MDString *s = MDString::get(Context, StringRef(str+0, 5)); std::string Str; raw_string_ostream oss(Str); s->print(oss); EXPECT_STREQ("!\"\\00\\0A\\22\\5C\\FF\"", oss.str().c_str()); } typedef MetadataTest MDNodeTest; // Test the two constructors, and containing other Constants. TEST_F(MDNodeTest, Simple) { char x[3] = { 'a', 'b', 'c' }; char y[3] = { '1', '2', '3' }; MDString *s1 = MDString::get(Context, StringRef(&x[0], 3)); MDString *s2 = MDString::get(Context, StringRef(&y[0], 3)); ConstantAsMetadata *CI = ConstantAsMetadata::get( ConstantInt::get(getGlobalContext(), APInt(8, 0))); std::vector<Metadata *> V; V.push_back(s1); V.push_back(CI); V.push_back(s2); MDNode *n1 = MDNode::get(Context, V); Metadata *const c1 = n1; MDNode *n2 = MDNode::get(Context, c1); Metadata *const c2 = n2; MDNode *n3 = MDNode::get(Context, V); MDNode *n4 = MDNode::getIfExists(Context, V); MDNode *n5 = MDNode::getIfExists(Context, c1); MDNode *n6 = MDNode::getIfExists(Context, c2); EXPECT_NE(n1, n2); EXPECT_EQ(n1, n3); EXPECT_EQ(n4, n1); EXPECT_EQ(n5, n2); EXPECT_EQ(n6, (Metadata *)nullptr); EXPECT_EQ(3u, n1->getNumOperands()); EXPECT_EQ(s1, n1->getOperand(0)); EXPECT_EQ(CI, n1->getOperand(1)); EXPECT_EQ(s2, n1->getOperand(2)); EXPECT_EQ(1u, n2->getNumOperands()); EXPECT_EQ(n1, n2->getOperand(0)); } TEST_F(MDNodeTest, Delete) { Constant *C = ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 1); Instruction *I = new BitCastInst(C, Type::getInt32Ty(getGlobalContext())); Metadata *const V = LocalAsMetadata::get(I); MDNode *n = MDNode::get(Context, V); TrackingMDRef wvh(n); EXPECT_EQ(n, wvh); delete I; } TEST_F(MDNodeTest, SelfReference) { // !0 = !{!0} // !1 = !{!0} { auto Temp = MDNode::getTemporary(Context, None); Metadata *Args[] = {Temp.get()}; MDNode *Self = MDNode::get(Context, Args); Self->replaceOperandWith(0, Self); ASSERT_EQ(Self, Self->getOperand(0)); // Self-references should be distinct, so MDNode::get() should grab a // uniqued node that references Self, not Self. Args[0] = Self; MDNode *Ref1 = MDNode::get(Context, Args); MDNode *Ref2 = MDNode::get(Context, Args); EXPECT_NE(Self, Ref1); EXPECT_EQ(Ref1, Ref2); } // !0 = !{!0, !{}} // !1 = !{!0, !{}} { auto Temp = MDNode::getTemporary(Context, None); Metadata *Args[] = {Temp.get(), MDNode::get(Context, None)}; MDNode *Self = MDNode::get(Context, Args); Self->replaceOperandWith(0, Self); ASSERT_EQ(Self, Self->getOperand(0)); // Self-references should be distinct, so MDNode::get() should grab a // uniqued node that references Self, not Self itself. Args[0] = Self; MDNode *Ref1 = MDNode::get(Context, Args); MDNode *Ref2 = MDNode::get(Context, Args); EXPECT_NE(Self, Ref1); EXPECT_EQ(Ref1, Ref2); } } TEST_F(MDNodeTest, Print) { Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 7); MDString *S = MDString::get(Context, "foo"); MDNode *N0 = getNode(); MDNode *N1 = getNode(N0); MDNode *N2 = getNode(N0, N1); Metadata *Args[] = {ConstantAsMetadata::get(C), S, nullptr, N0, N1, N2}; MDNode *N = MDNode::get(Context, Args); std::string Expected; { raw_string_ostream OS(Expected); OS << "<" << (void *)N << "> = !{"; C->printAsOperand(OS); OS << ", "; S->printAsOperand(OS); OS << ", null"; MDNode *Nodes[] = {N0, N1, N2}; for (auto *Node : Nodes) OS << ", <" << (void *)Node << ">"; OS << "}"; } std::string Actual; { raw_string_ostream OS(Actual); N->print(OS); } EXPECT_EQ(Expected, Actual); } #define EXPECT_PRINTER_EQ(EXPECTED, PRINT) \ do { \ std::string Actual_; \ raw_string_ostream OS(Actual_); \ PRINT; \ OS.flush(); \ std::string Expected_(EXPECTED); \ EXPECT_EQ(Expected_, Actual_); \ } while (false) TEST_F(MDNodeTest, PrintTemporary) { MDNode *Arg = getNode(); TempMDNode Temp = MDNode::getTemporary(Context, Arg); MDNode *N = getNode(Temp.get()); Module M("test", Context); NamedMDNode *NMD = M.getOrInsertNamedMetadata("named"); NMD->addOperand(N); EXPECT_PRINTER_EQ("!0 = !{!1}", N->print(OS, &M)); EXPECT_PRINTER_EQ("!1 = <temporary!> !{!2}", Temp->print(OS, &M)); EXPECT_PRINTER_EQ("!2 = !{}", Arg->print(OS, &M)); // Cleanup. Temp->replaceAllUsesWith(Arg); } TEST_F(MDNodeTest, PrintFromModule) { Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 7); MDString *S = MDString::get(Context, "foo"); MDNode *N0 = getNode(); MDNode *N1 = getNode(N0); MDNode *N2 = getNode(N0, N1); Metadata *Args[] = {ConstantAsMetadata::get(C), S, nullptr, N0, N1, N2}; MDNode *N = MDNode::get(Context, Args); Module M("test", Context); NamedMDNode *NMD = M.getOrInsertNamedMetadata("named"); NMD->addOperand(N); std::string Expected; { raw_string_ostream OS(Expected); OS << "!0 = !{"; C->printAsOperand(OS); OS << ", "; S->printAsOperand(OS); OS << ", null, !1, !2, !3}"; } EXPECT_PRINTER_EQ(Expected, N->print(OS, &M)); } TEST_F(MDNodeTest, PrintFromFunction) { Module M("test", Context); auto *FTy = FunctionType::get(Type::getVoidTy(Context), false); auto *F0 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F0", &M); auto *F1 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F1", &M); auto *BB0 = BasicBlock::Create(Context, "entry", F0); auto *BB1 = BasicBlock::Create(Context, "entry", F1); auto *R0 = ReturnInst::Create(Context, BB0); auto *R1 = ReturnInst::Create(Context, BB1); auto *N0 = MDNode::getDistinct(Context, None); auto *N1 = MDNode::getDistinct(Context, None); R0->setMetadata("md", N0); R1->setMetadata("md", N1); EXPECT_PRINTER_EQ("!0 = distinct !{}", N0->print(OS, &M)); EXPECT_PRINTER_EQ("!1 = distinct !{}", N1->print(OS, &M)); ModuleSlotTracker MST(&M); EXPECT_PRINTER_EQ("!0 = distinct !{}", N0->print(OS, MST)); EXPECT_PRINTER_EQ("!1 = distinct !{}", N1->print(OS, MST)); } TEST_F(MDNodeTest, PrintFromMetadataAsValue) { Module M("test", Context); auto *Intrinsic = Function::Create(FunctionType::get(Type::getVoidTy(Context), Type::getMetadataTy(Context), false), GlobalValue::ExternalLinkage, "llvm.intrinsic", &M); auto *FTy = FunctionType::get(Type::getVoidTy(Context), false); auto *F0 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F0", &M); auto *F1 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F1", &M); auto *BB0 = BasicBlock::Create(Context, "entry", F0); auto *BB1 = BasicBlock::Create(Context, "entry", F1); auto *N0 = MDNode::getDistinct(Context, None); auto *N1 = MDNode::getDistinct(Context, None); auto *MAV0 = MetadataAsValue::get(Context, N0); auto *MAV1 = MetadataAsValue::get(Context, N1); CallInst::Create(Intrinsic, MAV0, "", BB0); CallInst::Create(Intrinsic, MAV1, "", BB1); EXPECT_PRINTER_EQ("!0 = distinct !{}", MAV0->print(OS)); EXPECT_PRINTER_EQ("!1 = distinct !{}", MAV1->print(OS)); EXPECT_PRINTER_EQ("!0", MAV0->printAsOperand(OS, false)); EXPECT_PRINTER_EQ("!1", MAV1->printAsOperand(OS, false)); EXPECT_PRINTER_EQ("metadata !0", MAV0->printAsOperand(OS, true)); EXPECT_PRINTER_EQ("metadata !1", MAV1->printAsOperand(OS, true)); ModuleSlotTracker MST(&M); EXPECT_PRINTER_EQ("!0 = distinct !{}", MAV0->print(OS, MST)); EXPECT_PRINTER_EQ("!1 = distinct !{}", MAV1->print(OS, MST)); EXPECT_PRINTER_EQ("!0", MAV0->printAsOperand(OS, false, MST)); EXPECT_PRINTER_EQ("!1", MAV1->printAsOperand(OS, false, MST)); EXPECT_PRINTER_EQ("metadata !0", MAV0->printAsOperand(OS, true, MST)); EXPECT_PRINTER_EQ("metadata !1", MAV1->printAsOperand(OS, true, MST)); } #undef EXPECT_PRINTER_EQ TEST_F(MDNodeTest, NullOperand) { // metadata !{} MDNode *Empty = MDNode::get(Context, None); // metadata !{metadata !{}} Metadata *Ops[] = {Empty}; MDNode *N = MDNode::get(Context, Ops); ASSERT_EQ(Empty, N->getOperand(0)); // metadata !{metadata !{}} => metadata !{null} N->replaceOperandWith(0, nullptr); ASSERT_EQ(nullptr, N->getOperand(0)); // metadata !{null} Ops[0] = nullptr; MDNode *NullOp = MDNode::get(Context, Ops); ASSERT_EQ(nullptr, NullOp->getOperand(0)); EXPECT_EQ(N, NullOp); } TEST_F(MDNodeTest, DistinctOnUniquingCollision) { // !{} MDNode *Empty = MDNode::get(Context, None); ASSERT_TRUE(Empty->isResolved()); EXPECT_FALSE(Empty->isDistinct()); // !{!{}} Metadata *Wrapped1Ops[] = {Empty}; MDNode *Wrapped1 = MDNode::get(Context, Wrapped1Ops); ASSERT_EQ(Empty, Wrapped1->getOperand(0)); ASSERT_TRUE(Wrapped1->isResolved()); EXPECT_FALSE(Wrapped1->isDistinct()); // !{!{!{}}} Metadata *Wrapped2Ops[] = {Wrapped1}; MDNode *Wrapped2 = MDNode::get(Context, Wrapped2Ops); ASSERT_EQ(Wrapped1, Wrapped2->getOperand(0)); ASSERT_TRUE(Wrapped2->isResolved()); EXPECT_FALSE(Wrapped2->isDistinct()); // !{!{!{}}} => !{!{}} Wrapped2->replaceOperandWith(0, Empty); ASSERT_EQ(Empty, Wrapped2->getOperand(0)); EXPECT_TRUE(Wrapped2->isDistinct()); EXPECT_FALSE(Wrapped1->isDistinct()); } TEST_F(MDNodeTest, getDistinct) { // !{} MDNode *Empty = MDNode::get(Context, None); ASSERT_TRUE(Empty->isResolved()); ASSERT_FALSE(Empty->isDistinct()); ASSERT_EQ(Empty, MDNode::get(Context, None)); // distinct !{} MDNode *Distinct1 = MDNode::getDistinct(Context, None); MDNode *Distinct2 = MDNode::getDistinct(Context, None); EXPECT_TRUE(Distinct1->isResolved()); EXPECT_TRUE(Distinct2->isDistinct()); EXPECT_NE(Empty, Distinct1); EXPECT_NE(Empty, Distinct2); EXPECT_NE(Distinct1, Distinct2); // !{} ASSERT_EQ(Empty, MDNode::get(Context, None)); } TEST_F(MDNodeTest, isUniqued) { MDNode *U = MDTuple::get(Context, None); MDNode *D = MDTuple::getDistinct(Context, None); auto T = MDTuple::getTemporary(Context, None); EXPECT_TRUE(U->isUniqued()); EXPECT_FALSE(D->isUniqued()); EXPECT_FALSE(T->isUniqued()); } TEST_F(MDNodeTest, isDistinct) { MDNode *U = MDTuple::get(Context, None); MDNode *D = MDTuple::getDistinct(Context, None); auto T = MDTuple::getTemporary(Context, None); EXPECT_FALSE(U->isDistinct()); EXPECT_TRUE(D->isDistinct()); EXPECT_FALSE(T->isDistinct()); } TEST_F(MDNodeTest, isTemporary) { MDNode *U = MDTuple::get(Context, None); MDNode *D = MDTuple::getDistinct(Context, None); auto T = MDTuple::getTemporary(Context, None); EXPECT_FALSE(U->isTemporary()); EXPECT_FALSE(D->isTemporary()); EXPECT_TRUE(T->isTemporary()); } TEST_F(MDNodeTest, getDistinctWithUnresolvedOperands) { // temporary !{} auto Temp = MDTuple::getTemporary(Context, None); ASSERT_FALSE(Temp->isResolved()); // distinct !{temporary !{}} Metadata *Ops[] = {Temp.get()}; MDNode *Distinct = MDNode::getDistinct(Context, Ops); EXPECT_TRUE(Distinct->isResolved()); EXPECT_EQ(Temp.get(), Distinct->getOperand(0)); // temporary !{} => !{} MDNode *Empty = MDNode::get(Context, None); Temp->replaceAllUsesWith(Empty); EXPECT_EQ(Empty, Distinct->getOperand(0)); } TEST_F(MDNodeTest, handleChangedOperandRecursion) { // !0 = !{} MDNode *N0 = MDNode::get(Context, None); // !1 = !{!3, null} auto Temp3 = MDTuple::getTemporary(Context, None); Metadata *Ops1[] = {Temp3.get(), nullptr}; MDNode *N1 = MDNode::get(Context, Ops1); // !2 = !{!3, !0} Metadata *Ops2[] = {Temp3.get(), N0}; MDNode *N2 = MDNode::get(Context, Ops2); // !3 = !{!2} Metadata *Ops3[] = {N2}; MDNode *N3 = MDNode::get(Context, Ops3); Temp3->replaceAllUsesWith(N3); // !4 = !{!1} Metadata *Ops4[] = {N1}; MDNode *N4 = MDNode::get(Context, Ops4); // Confirm that the cycle prevented RAUW from getting dropped. EXPECT_TRUE(N0->isResolved()); EXPECT_FALSE(N1->isResolved()); EXPECT_FALSE(N2->isResolved()); EXPECT_FALSE(N3->isResolved()); EXPECT_FALSE(N4->isResolved()); // Create a couple of distinct nodes to observe what's going on. // // !5 = distinct !{!2} // !6 = distinct !{!3} Metadata *Ops5[] = {N2}; MDNode *N5 = MDNode::getDistinct(Context, Ops5); Metadata *Ops6[] = {N3}; MDNode *N6 = MDNode::getDistinct(Context, Ops6); // Mutate !2 to look like !1, causing a uniquing collision (and an RAUW). // This will ripple up, with !3 colliding with !4, and RAUWing. Since !2 // references !3, this can cause a re-entry of handleChangedOperand() when !3 // is not ready for it. // // !2->replaceOperandWith(1, nullptr) // !2: !{!3, !0} => !{!3, null} // !2->replaceAllUsesWith(!1) // !3: !{!2] => !{!1} // !3->replaceAllUsesWith(!4) N2->replaceOperandWith(1, nullptr); // If all has gone well, N2 and N3 will have been RAUW'ed and deleted from // under us. Just check that the other nodes are sane. // // !1 = !{!4, null} // !4 = !{!1} // !5 = distinct !{!1} // !6 = distinct !{!4} EXPECT_EQ(N4, N1->getOperand(0)); EXPECT_EQ(N1, N4->getOperand(0)); EXPECT_EQ(N1, N5->getOperand(0)); EXPECT_EQ(N4, N6->getOperand(0)); } TEST_F(MDNodeTest, replaceResolvedOperand) { // Check code for replacing one resolved operand with another. If doing this // directly (via replaceOperandWith()) becomes illegal, change the operand to // a global value that gets RAUW'ed. // // Use a temporary node to keep N from being resolved. auto Temp = MDTuple::getTemporary(Context, None); Metadata *Ops[] = {nullptr, Temp.get()}; MDNode *Empty = MDTuple::get(Context, ArrayRef<Metadata *>()); MDNode *N = MDTuple::get(Context, Ops); EXPECT_EQ(nullptr, N->getOperand(0)); ASSERT_FALSE(N->isResolved()); // Check code for replacing resolved nodes. N->replaceOperandWith(0, Empty); EXPECT_EQ(Empty, N->getOperand(0)); // Check code for adding another unresolved operand. N->replaceOperandWith(0, Temp.get()); EXPECT_EQ(Temp.get(), N->getOperand(0)); // Remove the references to Temp; required for teardown. Temp->replaceAllUsesWith(nullptr); } TEST_F(MDNodeTest, replaceWithUniqued) { auto *Empty = MDTuple::get(Context, None); MDTuple *FirstUniqued; { Metadata *Ops[] = {Empty}; auto Temp = MDTuple::getTemporary(Context, Ops); EXPECT_TRUE(Temp->isTemporary()); // Don't expect a collision. auto *Current = Temp.get(); FirstUniqued = MDNode::replaceWithUniqued(std::move(Temp)); EXPECT_TRUE(FirstUniqued->isUniqued()); EXPECT_TRUE(FirstUniqued->isResolved()); EXPECT_EQ(Current, FirstUniqued); } { Metadata *Ops[] = {Empty}; auto Temp = MDTuple::getTemporary(Context, Ops); EXPECT_TRUE(Temp->isTemporary()); // Should collide with Uniqued above this time. auto *Uniqued = MDNode::replaceWithUniqued(std::move(Temp)); EXPECT_TRUE(Uniqued->isUniqued()); EXPECT_TRUE(Uniqued->isResolved()); EXPECT_EQ(FirstUniqued, Uniqued); } { auto Unresolved = MDTuple::getTemporary(Context, None); Metadata *Ops[] = {Unresolved.get()}; auto Temp = MDTuple::getTemporary(Context, Ops); EXPECT_TRUE(Temp->isTemporary()); // Shouldn't be resolved. auto *Uniqued = MDNode::replaceWithUniqued(std::move(Temp)); EXPECT_TRUE(Uniqued->isUniqued()); EXPECT_FALSE(Uniqued->isResolved()); // Should be a different node. EXPECT_NE(FirstUniqued, Uniqued); // Should resolve when we update its node (note: be careful to avoid a // collision with any other nodes above). Uniqued->replaceOperandWith(0, nullptr); EXPECT_TRUE(Uniqued->isResolved()); } } TEST_F(MDNodeTest, replaceWithUniquedResolvingOperand) { // temp !{} MDTuple *Op = MDTuple::getTemporary(Context, None).release(); EXPECT_FALSE(Op->isResolved()); // temp !{temp !{}} Metadata *Ops[] = {Op}; MDTuple *N = MDTuple::getTemporary(Context, Ops).release(); EXPECT_FALSE(N->isResolved()); // temp !{temp !{}} => !{temp !{}} ASSERT_EQ(N, MDNode::replaceWithUniqued(TempMDTuple(N))); EXPECT_FALSE(N->isResolved()); // !{temp !{}} => !{!{}} ASSERT_EQ(Op, MDNode::replaceWithUniqued(TempMDTuple(Op))); EXPECT_TRUE(Op->isResolved()); EXPECT_TRUE(N->isResolved()); } TEST_F(MDNodeTest, replaceWithUniquedChangingOperand) { // i1* @GV Type *Ty = Type::getInt1PtrTy(Context); std::unique_ptr<GlobalVariable> GV( new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage)); ConstantAsMetadata *Op = ConstantAsMetadata::get(GV.get()); // temp !{i1* @GV} Metadata *Ops[] = {Op}; MDTuple *N = MDTuple::getTemporary(Context, Ops).release(); // temp !{i1* @GV} => !{i1* @GV} ASSERT_EQ(N, MDNode::replaceWithUniqued(TempMDTuple(N))); ASSERT_TRUE(N->isUniqued()); // !{i1* @GV} => !{null} GV.reset(); ASSERT_TRUE(N->isUniqued()); Metadata *NullOps[] = {nullptr}; ASSERT_EQ(N, MDTuple::get(Context, NullOps)); } TEST_F(MDNodeTest, replaceWithDistinct) { { auto *Empty = MDTuple::get(Context, None); Metadata *Ops[] = {Empty}; auto Temp = MDTuple::getTemporary(Context, Ops); EXPECT_TRUE(Temp->isTemporary()); // Don't expect a collision. auto *Current = Temp.get(); auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp)); EXPECT_TRUE(Distinct->isDistinct()); EXPECT_TRUE(Distinct->isResolved()); EXPECT_EQ(Current, Distinct); } { auto Unresolved = MDTuple::getTemporary(Context, None); Metadata *Ops[] = {Unresolved.get()}; auto Temp = MDTuple::getTemporary(Context, Ops); EXPECT_TRUE(Temp->isTemporary()); // Don't expect a collision. auto *Current = Temp.get(); auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp)); EXPECT_TRUE(Distinct->isDistinct()); EXPECT_TRUE(Distinct->isResolved()); EXPECT_EQ(Current, Distinct); // Cleanup; required for teardown. Unresolved->replaceAllUsesWith(nullptr); } } TEST_F(MDNodeTest, replaceWithPermanent) { Metadata *Ops[] = {nullptr}; auto Temp = MDTuple::getTemporary(Context, Ops); auto *T = Temp.get(); // U is a normal, uniqued node that references T. auto *U = MDTuple::get(Context, T); EXPECT_TRUE(U->isUniqued()); // Make Temp self-referencing. Temp->replaceOperandWith(0, T); // Try to uniquify Temp. This should, despite the name in the API, give a // 'distinct' node, since self-references aren't allowed to be uniqued. // // Since it's distinct, N should have the same address as when it was a // temporary (i.e., be equal to T not U). auto *N = MDNode::replaceWithPermanent(std::move(Temp)); EXPECT_EQ(N, T); EXPECT_TRUE(N->isDistinct()); // U should be the canonical unique node with N as the argument. EXPECT_EQ(U, MDTuple::get(Context, N)); EXPECT_TRUE(U->isUniqued()); // This temporary should collide with U when replaced, but it should still be // uniqued. EXPECT_EQ(U, MDNode::replaceWithPermanent(MDTuple::getTemporary(Context, N))); EXPECT_TRUE(U->isUniqued()); // This temporary should become a new uniqued node. auto Temp2 = MDTuple::getTemporary(Context, U); auto *V = Temp2.get(); EXPECT_EQ(V, MDNode::replaceWithPermanent(std::move(Temp2))); EXPECT_TRUE(V->isUniqued()); EXPECT_EQ(U, V->getOperand(0)); } TEST_F(MDNodeTest, deleteTemporaryWithTrackingRef) { TrackingMDRef Ref; EXPECT_EQ(nullptr, Ref.get()); { auto Temp = MDTuple::getTemporary(Context, None); Ref.reset(Temp.get()); EXPECT_EQ(Temp.get(), Ref.get()); } EXPECT_EQ(nullptr, Ref.get()); } typedef MetadataTest DILocationTest; TEST_F(DILocationTest, Overflow) { DISubprogram *N = getSubprogram(); { DILocation *L = DILocation::get(Context, 2, 7, N); EXPECT_EQ(2u, L->getLine()); EXPECT_EQ(7u, L->getColumn()); } unsigned U16 = 1u << 16; { DILocation *L = DILocation::get(Context, UINT32_MAX, U16 - 1, N); EXPECT_EQ(UINT32_MAX, L->getLine()); EXPECT_EQ(U16 - 1, L->getColumn()); } { DILocation *L = DILocation::get(Context, UINT32_MAX, U16, N); EXPECT_EQ(UINT32_MAX, L->getLine()); EXPECT_EQ(0u, L->getColumn()); } { DILocation *L = DILocation::get(Context, UINT32_MAX, U16 + 1, N); EXPECT_EQ(UINT32_MAX, L->getLine()); EXPECT_EQ(0u, L->getColumn()); } } TEST_F(DILocationTest, getDistinct) { MDNode *N = getSubprogram(); DILocation *L0 = DILocation::getDistinct(Context, 2, 7, N); EXPECT_TRUE(L0->isDistinct()); DILocation *L1 = DILocation::get(Context, 2, 7, N); EXPECT_FALSE(L1->isDistinct()); EXPECT_EQ(L1, DILocation::get(Context, 2, 7, N)); } TEST_F(DILocationTest, getTemporary) { MDNode *N = MDNode::get(Context, None); auto L = DILocation::getTemporary(Context, 2, 7, N); EXPECT_TRUE(L->isTemporary()); EXPECT_FALSE(L->isResolved()); } typedef MetadataTest GenericDINodeTest; TEST_F(GenericDINodeTest, get) { StringRef Header = "header"; auto *Empty = MDNode::get(Context, None); Metadata *Ops1[] = {Empty}; auto *N = GenericDINode::get(Context, 15, Header, Ops1); EXPECT_EQ(15u, N->getTag()); EXPECT_EQ(2u, N->getNumOperands()); EXPECT_EQ(Header, N->getHeader()); EXPECT_EQ(MDString::get(Context, Header), N->getOperand(0)); EXPECT_EQ(1u, N->getNumDwarfOperands()); EXPECT_EQ(Empty, N->getDwarfOperand(0)); EXPECT_EQ(Empty, N->getOperand(1)); ASSERT_TRUE(N->isUniqued()); EXPECT_EQ(N, GenericDINode::get(Context, 15, Header, Ops1)); N->replaceOperandWith(1, nullptr); EXPECT_EQ(15u, N->getTag()); EXPECT_EQ(Header, N->getHeader()); EXPECT_EQ(nullptr, N->getDwarfOperand(0)); ASSERT_TRUE(N->isUniqued()); Metadata *Ops2[] = {nullptr}; EXPECT_EQ(N, GenericDINode::get(Context, 15, Header, Ops2)); N->replaceDwarfOperandWith(0, Empty); EXPECT_EQ(15u, N->getTag()); EXPECT_EQ(Header, N->getHeader()); EXPECT_EQ(Empty, N->getDwarfOperand(0)); ASSERT_TRUE(N->isUniqued()); EXPECT_EQ(N, GenericDINode::get(Context, 15, Header, Ops1)); TempGenericDINode Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(GenericDINodeTest, getEmptyHeader) { // Canonicalize !"" to null. auto *N = GenericDINode::get(Context, 15, StringRef(), None); EXPECT_EQ(StringRef(), N->getHeader()); EXPECT_EQ(nullptr, N->getOperand(0)); } typedef MetadataTest DISubrangeTest; TEST_F(DISubrangeTest, get) { auto *N = DISubrange::get(Context, 5, 7); EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag()); EXPECT_EQ(5, N->getCount()); EXPECT_EQ(7, N->getLowerBound()); EXPECT_EQ(N, DISubrange::get(Context, 5, 7)); EXPECT_EQ(DISubrange::get(Context, 5, 0), DISubrange::get(Context, 5)); TempDISubrange Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DISubrangeTest, getEmptyArray) { auto *N = DISubrange::get(Context, -1, 0); EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag()); EXPECT_EQ(-1, N->getCount()); EXPECT_EQ(0, N->getLowerBound()); EXPECT_EQ(N, DISubrange::get(Context, -1, 0)); } typedef MetadataTest DIEnumeratorTest; TEST_F(DIEnumeratorTest, get) { auto *N = DIEnumerator::get(Context, 7, "name"); EXPECT_EQ(dwarf::DW_TAG_enumerator, N->getTag()); EXPECT_EQ(7, N->getValue()); EXPECT_EQ("name", N->getName()); EXPECT_EQ(N, DIEnumerator::get(Context, 7, "name")); EXPECT_NE(N, DIEnumerator::get(Context, 8, "name")); EXPECT_NE(N, DIEnumerator::get(Context, 7, "nam")); TempDIEnumerator Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DIBasicTypeTest; TEST_F(DIBasicTypeTest, get) { auto *N = DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33, 26, 7); EXPECT_EQ(dwarf::DW_TAG_base_type, N->getTag()); EXPECT_EQ("special", N->getName()); EXPECT_EQ(33u, N->getSizeInBits()); EXPECT_EQ(26u, N->getAlignInBits()); EXPECT_EQ(7u, N->getEncoding()); EXPECT_EQ(0u, N->getLine()); EXPECT_EQ(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33, 26, 7)); EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_unspecified_type, "special", 33, 26, 7)); EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "s", 33, 26, 7)); EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 32, 26, 7)); EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33, 25, 7)); EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33, 26, 6)); TempDIBasicType Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DIBasicTypeTest, getWithLargeValues) { auto *N = DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", UINT64_MAX, UINT64_MAX - 1, 7); EXPECT_EQ(UINT64_MAX, N->getSizeInBits()); EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits()); } TEST_F(DIBasicTypeTest, getUnspecified) { auto *N = DIBasicType::get(Context, dwarf::DW_TAG_unspecified_type, "unspecified"); EXPECT_EQ(dwarf::DW_TAG_unspecified_type, N->getTag()); EXPECT_EQ("unspecified", N->getName()); EXPECT_EQ(0u, N->getSizeInBits()); EXPECT_EQ(0u, N->getAlignInBits()); EXPECT_EQ(0u, N->getEncoding()); EXPECT_EQ(0u, N->getLine()); } typedef MetadataTest DITypeTest; TEST_F(DITypeTest, clone) { // Check that DIType has a specialized clone that returns TempDIType. DIType *N = DIBasicType::get(Context, dwarf::DW_TAG_base_type, "int", 32, 32, dwarf::DW_ATE_signed); TempDIType Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DITypeTest, setFlags) { // void (void) Metadata *TypesOps[] = {nullptr}; Metadata *Types = MDTuple::get(Context, TypesOps); DIType *D = DISubroutineType::getDistinct(Context, 0u, Types); EXPECT_EQ(0u, D->getFlags()); D->setFlags(DINode::FlagRValueReference); EXPECT_EQ(DINode::FlagRValueReference, D->getFlags()); D->setFlags(0u); EXPECT_EQ(0u, D->getFlags()); TempDIType T = DISubroutineType::getTemporary(Context, 0u, Types); EXPECT_EQ(0u, T->getFlags()); T->setFlags(DINode::FlagRValueReference); EXPECT_EQ(DINode::FlagRValueReference, T->getFlags()); T->setFlags(0u); EXPECT_EQ(0u, T->getFlags()); } typedef MetadataTest DIDerivedTypeTest; TEST_F(DIDerivedTypeTest, get) { DIFile *File = getFile(); DIScopeRef Scope = getSubprogramRef(); DITypeRef BaseType = getBasicType("basic"); MDTuple *ExtraData = getTuple(); auto *N = DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, 2, 3, 4, 5, ExtraData); EXPECT_EQ(dwarf::DW_TAG_pointer_type, N->getTag()); EXPECT_EQ("something", N->getName()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(1u, N->getLine()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(BaseType, N->getBaseType()); EXPECT_EQ(2u, N->getSizeInBits()); EXPECT_EQ(3u, N->getAlignInBits()); EXPECT_EQ(4u, N->getOffsetInBits()); EXPECT_EQ(5u, N->getFlags()); EXPECT_EQ(ExtraData, N->getExtraData()); EXPECT_EQ(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, 2, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_reference_type, "something", File, 1, Scope, BaseType, 2, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "else", File, 1, Scope, BaseType, 2, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", getFile(), 1, Scope, BaseType, 2, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 2, Scope, BaseType, 2, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, getSubprogramRef(), BaseType, 2, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get( Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, getBasicType("basic2"), 2, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, 3, 3, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, 2, 2, 4, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, 2, 3, 5, 5, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, 2, 3, 4, 4, ExtraData)); EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, 2, 3, 4, 5, getTuple())); TempDIDerivedType Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DIDerivedTypeTest, getWithLargeValues) { DIFile *File = getFile(); DIScopeRef Scope = getSubprogramRef(); DITypeRef BaseType = getBasicType("basic"); MDTuple *ExtraData = getTuple(); auto *N = DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something", File, 1, Scope, BaseType, UINT64_MAX, UINT64_MAX - 1, UINT64_MAX - 2, 5, ExtraData); EXPECT_EQ(UINT64_MAX, N->getSizeInBits()); EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits()); EXPECT_EQ(UINT64_MAX - 2, N->getOffsetInBits()); } typedef MetadataTest DICompositeTypeTest; TEST_F(DICompositeTypeTest, get) { unsigned Tag = dwarf::DW_TAG_structure_type; StringRef Name = "some name"; DIFile *File = getFile(); unsigned Line = 1; DIScopeRef Scope = getSubprogramRef(); DITypeRef BaseType = getCompositeType(); uint64_t SizeInBits = 2; uint64_t AlignInBits = 3; uint64_t OffsetInBits = 4; unsigned Flags = 5; MDTuple *Elements = getTuple(); unsigned RuntimeLang = 6; DITypeRef VTableHolder = getCompositeType(); MDTuple *TemplateParams = getTuple(); StringRef Identifier = "some id"; auto *N = DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier); EXPECT_EQ(Tag, N->getTag()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(BaseType, N->getBaseType()); EXPECT_EQ(SizeInBits, N->getSizeInBits()); EXPECT_EQ(AlignInBits, N->getAlignInBits()); EXPECT_EQ(OffsetInBits, N->getOffsetInBits()); EXPECT_EQ(Flags, N->getFlags()); EXPECT_EQ(Elements, N->getElements().get()); EXPECT_EQ(RuntimeLang, N->getRuntimeLang()); EXPECT_EQ(VTableHolder, N->getVTableHolder()); EXPECT_EQ(TemplateParams, N->getTemplateParams().get()); EXPECT_EQ(Identifier, N->getIdentifier()); EXPECT_EQ(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag + 1, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag, "abc", File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, getFile(), Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line + 1, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get( Context, Tag, Name, File, Line, getSubprogramRef(), BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get( Context, Tag, Name, File, Line, Scope, getBasicType("other"), SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits + 1, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits + 1, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get( Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits + 1, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get( Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags + 1, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get( Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, getTuple(), RuntimeLang, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get( Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang + 1, VTableHolder, TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get( Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, getCompositeType(), TemplateParams, Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, getTuple(), Identifier)); EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, "other")); // Be sure that missing identifiers get null pointers. EXPECT_FALSE(DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, "") ->getRawIdentifier()); EXPECT_FALSE(DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams) ->getRawIdentifier()); TempDICompositeType Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DICompositeTypeTest, getWithLargeValues) { unsigned Tag = dwarf::DW_TAG_structure_type; StringRef Name = "some name"; DIFile *File = getFile(); unsigned Line = 1; DIScopeRef Scope = getSubprogramRef(); DITypeRef BaseType = getCompositeType(); uint64_t SizeInBits = UINT64_MAX; uint64_t AlignInBits = UINT64_MAX - 1; uint64_t OffsetInBits = UINT64_MAX - 2; unsigned Flags = 5; MDTuple *Elements = getTuple(); unsigned RuntimeLang = 6; DITypeRef VTableHolder = getCompositeType(); MDTuple *TemplateParams = getTuple(); StringRef Identifier = "some id"; auto *N = DICompositeType::get(Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams, Identifier); EXPECT_EQ(SizeInBits, N->getSizeInBits()); EXPECT_EQ(AlignInBits, N->getAlignInBits()); EXPECT_EQ(OffsetInBits, N->getOffsetInBits()); } TEST_F(DICompositeTypeTest, replaceOperands) { unsigned Tag = dwarf::DW_TAG_structure_type; StringRef Name = "some name"; DIFile *File = getFile(); unsigned Line = 1; DIScopeRef Scope = getSubprogramRef(); DITypeRef BaseType = getCompositeType(); uint64_t SizeInBits = 2; uint64_t AlignInBits = 3; uint64_t OffsetInBits = 4; unsigned Flags = 5; unsigned RuntimeLang = 6; StringRef Identifier = "some id"; auto *N = DICompositeType::get( Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, nullptr, RuntimeLang, nullptr, nullptr, Identifier); auto *Elements = MDTuple::getDistinct(Context, None); EXPECT_EQ(nullptr, N->getElements().get()); N->replaceElements(Elements); EXPECT_EQ(Elements, N->getElements().get()); N->replaceElements(nullptr); EXPECT_EQ(nullptr, N->getElements().get()); DITypeRef VTableHolder = getCompositeType(); EXPECT_EQ(nullptr, N->getVTableHolder()); N->replaceVTableHolder(VTableHolder); EXPECT_EQ(VTableHolder, N->getVTableHolder()); N->replaceVTableHolder(nullptr); EXPECT_EQ(nullptr, N->getVTableHolder()); auto *TemplateParams = MDTuple::getDistinct(Context, None); EXPECT_EQ(nullptr, N->getTemplateParams().get()); N->replaceTemplateParams(TemplateParams); EXPECT_EQ(TemplateParams, N->getTemplateParams().get()); N->replaceTemplateParams(nullptr); EXPECT_EQ(nullptr, N->getTemplateParams().get()); } typedef MetadataTest DISubroutineTypeTest; TEST_F(DISubroutineTypeTest, get) { unsigned Flags = 1; MDTuple *TypeArray = getTuple(); auto *N = DISubroutineType::get(Context, Flags, TypeArray); EXPECT_EQ(dwarf::DW_TAG_subroutine_type, N->getTag()); EXPECT_EQ(Flags, N->getFlags()); EXPECT_EQ(TypeArray, N->getTypeArray().get()); EXPECT_EQ(N, DISubroutineType::get(Context, Flags, TypeArray)); EXPECT_NE(N, DISubroutineType::get(Context, Flags + 1, TypeArray)); EXPECT_NE(N, DISubroutineType::get(Context, Flags, getTuple())); TempDISubroutineType Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); // Test always-empty operands. EXPECT_EQ(nullptr, N->getScope()); EXPECT_EQ(nullptr, N->getFile()); EXPECT_EQ("", N->getName()); EXPECT_EQ(nullptr, N->getBaseType()); EXPECT_EQ(nullptr, N->getVTableHolder()); EXPECT_EQ(nullptr, N->getTemplateParams().get()); EXPECT_EQ("", N->getIdentifier()); } typedef MetadataTest DIFileTest; TEST_F(DIFileTest, get) { StringRef Filename = "file"; StringRef Directory = "dir"; auto *N = DIFile::get(Context, Filename, Directory); EXPECT_EQ(dwarf::DW_TAG_file_type, N->getTag()); EXPECT_EQ(Filename, N->getFilename()); EXPECT_EQ(Directory, N->getDirectory()); EXPECT_EQ(N, DIFile::get(Context, Filename, Directory)); EXPECT_NE(N, DIFile::get(Context, "other", Directory)); EXPECT_NE(N, DIFile::get(Context, Filename, "other")); TempDIFile Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DIFileTest, ScopeGetFile) { // Ensure that DIScope::getFile() returns itself. DIScope *N = DIFile::get(Context, "file", "dir"); EXPECT_EQ(N, N->getFile()); } typedef MetadataTest DICompileUnitTest; TEST_F(DICompileUnitTest, get) { unsigned SourceLanguage = 1; DIFile *File = getFile(); StringRef Producer = "some producer"; bool IsOptimized = false; StringRef Flags = "flag after flag"; unsigned RuntimeVersion = 2; StringRef SplitDebugFilename = "another/file"; unsigned EmissionKind = 3; MDTuple *EnumTypes = getTuple(); MDTuple *RetainedTypes = getTuple(); MDTuple *Subprograms = getTuple(); MDTuple *GlobalVariables = getTuple(); MDTuple *ImportedEntities = getTuple(); uint64_t DWOId = 0xc0ffee; auto *N = DICompileUnit::get( Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId); EXPECT_EQ(dwarf::DW_TAG_compile_unit, N->getTag()); EXPECT_EQ(SourceLanguage, N->getSourceLanguage()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Producer, N->getProducer()); EXPECT_EQ(IsOptimized, N->isOptimized()); EXPECT_EQ(Flags, N->getFlags()); EXPECT_EQ(RuntimeVersion, N->getRuntimeVersion()); EXPECT_EQ(SplitDebugFilename, N->getSplitDebugFilename()); EXPECT_EQ(EmissionKind, N->getEmissionKind()); EXPECT_EQ(EnumTypes, N->getEnumTypes().get()); EXPECT_EQ(RetainedTypes, N->getRetainedTypes().get()); EXPECT_EQ(Subprograms, N->getSubprograms().get()); EXPECT_EQ(GlobalVariables, N->getGlobalVariables().get()); EXPECT_EQ(ImportedEntities, N->getImportedEntities().get()); EXPECT_EQ(DWOId, N->getDWOId()); EXPECT_EQ(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage + 1, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, getFile(), Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, "other", IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, !IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, "other", RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion + 1, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, "other", EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind + 1, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, getTuple(), RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, getTuple(), Subprograms, GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, getTuple(), GlobalVariables, ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, getTuple(), ImportedEntities, DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, getTuple(), DWOId)); EXPECT_NE(N, DICompileUnit::get(Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId + 1)); TempDICompileUnit Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DICompileUnitTest, replaceArrays) { unsigned SourceLanguage = 1; DIFile *File = getFile(); StringRef Producer = "some producer"; bool IsOptimized = false; StringRef Flags = "flag after flag"; unsigned RuntimeVersion = 2; StringRef SplitDebugFilename = "another/file"; unsigned EmissionKind = 3; MDTuple *EnumTypes = MDTuple::getDistinct(Context, None); MDTuple *RetainedTypes = MDTuple::getDistinct(Context, None); MDTuple *ImportedEntities = MDTuple::getDistinct(Context, None); uint64_t DWOId = 0xc0ffee; auto *N = DICompileUnit::get( Context, SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes, nullptr, nullptr, ImportedEntities, DWOId); auto *Subprograms = MDTuple::getDistinct(Context, None); EXPECT_EQ(nullptr, N->getSubprograms().get()); N->replaceSubprograms(Subprograms); EXPECT_EQ(Subprograms, N->getSubprograms().get()); N->replaceSubprograms(nullptr); EXPECT_EQ(nullptr, N->getSubprograms().get()); auto *GlobalVariables = MDTuple::getDistinct(Context, None); EXPECT_EQ(nullptr, N->getGlobalVariables().get()); N->replaceGlobalVariables(GlobalVariables); EXPECT_EQ(GlobalVariables, N->getGlobalVariables().get()); N->replaceGlobalVariables(nullptr); EXPECT_EQ(nullptr, N->getGlobalVariables().get()); } typedef MetadataTest DISubprogramTest; TEST_F(DISubprogramTest, get) { DIScopeRef Scope = getCompositeType(); StringRef Name = "name"; StringRef LinkageName = "linkage"; DIFile *File = getFile(); unsigned Line = 2; DISubroutineType *Type = getSubroutineType(); bool IsLocalToUnit = false; bool IsDefinition = true; unsigned ScopeLine = 3; DITypeRef ContainingType = getCompositeType(); unsigned Virtuality = 4; unsigned VirtualIndex = 5; unsigned Flags = 6; bool IsOptimized = false; llvm::Function *Function = getFunction("foo"); MDTuple *TemplateParams = getTuple(); DISubprogram *Declaration = getSubprogram(); MDTuple *Variables = getTuple(); auto *N = DISubprogram::get( Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables); EXPECT_EQ(dwarf::DW_TAG_subprogram, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(LinkageName, N->getLinkageName()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(Type, N->getType()); EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit()); EXPECT_EQ(IsDefinition, N->isDefinition()); EXPECT_EQ(ScopeLine, N->getScopeLine()); EXPECT_EQ(ContainingType, N->getContainingType()); EXPECT_EQ(Virtuality, N->getVirtuality()); EXPECT_EQ(VirtualIndex, N->getVirtualIndex()); EXPECT_EQ(Flags, N->getFlags()); EXPECT_EQ(IsOptimized, N->isOptimized()); EXPECT_EQ(Function, N->getFunction()); EXPECT_EQ(TemplateParams, N->getTemplateParams().get()); EXPECT_EQ(Declaration, N->getDeclaration()); EXPECT_EQ(Variables, N->getVariables().get()); EXPECT_EQ(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, getCompositeType(), Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, "other", LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, "other", File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, getFile(), Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line + 1, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get( Context, Scope, Name, LinkageName, File, Line, getSubroutineType(), IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, !IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, !IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine + 1, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, getCompositeType(), Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality + 1, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex + 1, Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, ~Flags, IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, !IsOptimized, Function, TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, getFunction("bar"), TemplateParams, Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, getTuple(), Declaration, Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, getSubprogram(), Variables)); EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, Function, TemplateParams, Declaration, getTuple())); TempDISubprogram Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DISubprogramTest, replaceFunction) { DIScopeRef Scope = getCompositeType(); StringRef Name = "name"; StringRef LinkageName = "linkage"; DIFile *File = getFile(); unsigned Line = 2; DISubroutineType *Type = getSubroutineType(); bool IsLocalToUnit = false; bool IsDefinition = true; unsigned ScopeLine = 3; DITypeRef ContainingType = getCompositeType(); unsigned Virtuality = 4; unsigned VirtualIndex = 5; unsigned Flags = 6; bool IsOptimized = false; MDTuple *TemplateParams = getTuple(); DISubprogram *Declaration = getSubprogram(); MDTuple *Variables = getTuple(); auto *N = DISubprogram::get( Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized, nullptr, TemplateParams, Declaration, Variables); EXPECT_EQ(nullptr, N->getFunction()); std::unique_ptr<Function> F( Function::Create(FunctionType::get(Type::getVoidTy(Context), false), GlobalValue::ExternalLinkage)); N->replaceFunction(F.get()); EXPECT_EQ(F.get(), N->getFunction()); N->replaceFunction(nullptr); EXPECT_EQ(nullptr, N->getFunction()); } typedef MetadataTest DILexicalBlockTest; TEST_F(DILexicalBlockTest, get) { DILocalScope *Scope = getSubprogram(); DIFile *File = getFile(); unsigned Line = 5; unsigned Column = 8; auto *N = DILexicalBlock::get(Context, Scope, File, Line, Column); EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(Column, N->getColumn()); EXPECT_EQ(N, DILexicalBlock::get(Context, Scope, File, Line, Column)); EXPECT_NE(N, DILexicalBlock::get(Context, getSubprogram(), File, Line, Column)); EXPECT_NE(N, DILexicalBlock::get(Context, Scope, getFile(), Line, Column)); EXPECT_NE(N, DILexicalBlock::get(Context, Scope, File, Line + 1, Column)); EXPECT_NE(N, DILexicalBlock::get(Context, Scope, File, Line, Column + 1)); TempDILexicalBlock Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DILexicalBlockFileTest; TEST_F(DILexicalBlockFileTest, get) { DILocalScope *Scope = getSubprogram(); DIFile *File = getFile(); unsigned Discriminator = 5; auto *N = DILexicalBlockFile::get(Context, Scope, File, Discriminator); EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Discriminator, N->getDiscriminator()); EXPECT_EQ(N, DILexicalBlockFile::get(Context, Scope, File, Discriminator)); EXPECT_NE(N, DILexicalBlockFile::get(Context, getSubprogram(), File, Discriminator)); EXPECT_NE(N, DILexicalBlockFile::get(Context, Scope, getFile(), Discriminator)); EXPECT_NE(N, DILexicalBlockFile::get(Context, Scope, File, Discriminator + 1)); TempDILexicalBlockFile Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DINamespaceTest; TEST_F(DINamespaceTest, get) { DIScope *Scope = getFile(); DIFile *File = getFile(); StringRef Name = "namespace"; unsigned Line = 5; auto *N = DINamespace::get(Context, Scope, File, Name, Line); EXPECT_EQ(dwarf::DW_TAG_namespace, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(N, DINamespace::get(Context, Scope, File, Name, Line)); EXPECT_NE(N, DINamespace::get(Context, getFile(), File, Name, Line)); EXPECT_NE(N, DINamespace::get(Context, Scope, getFile(), Name, Line)); EXPECT_NE(N, DINamespace::get(Context, Scope, File, "other", Line)); EXPECT_NE(N, DINamespace::get(Context, Scope, File, Name, Line + 1)); TempDINamespace Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DIModuleTest; TEST_F(DIModuleTest, get) { DIScope *Scope = getFile(); StringRef Name = "module"; StringRef ConfigMacro = "-DNDEBUG"; StringRef Includes = "-I."; StringRef Sysroot = "/"; auto *N = DIModule::get(Context, Scope, Name, ConfigMacro, Includes, Sysroot); EXPECT_EQ(dwarf::DW_TAG_module, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(ConfigMacro, N->getConfigurationMacros()); EXPECT_EQ(Includes, N->getIncludePath()); EXPECT_EQ(Sysroot, N->getISysRoot()); EXPECT_EQ(N, DIModule::get(Context, Scope, Name, ConfigMacro, Includes, Sysroot)); EXPECT_NE(N, DIModule::get(Context, getFile(), Name, ConfigMacro, Includes, Sysroot)); EXPECT_NE(N, DIModule::get(Context, Scope, "other", ConfigMacro, Includes, Sysroot)); EXPECT_NE(N, DIModule::get(Context, Scope, Name, "other", Includes, Sysroot)); EXPECT_NE(N, DIModule::get(Context, Scope, Name, ConfigMacro, "other", Sysroot)); EXPECT_NE(N, DIModule::get(Context, Scope, Name, ConfigMacro, Includes, "other")); TempDIModule Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DITemplateTypeParameterTest; TEST_F(DITemplateTypeParameterTest, get) { StringRef Name = "template"; DITypeRef Type = getBasicType("basic"); auto *N = DITemplateTypeParameter::get(Context, Name, Type); EXPECT_EQ(dwarf::DW_TAG_template_type_parameter, N->getTag()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(Type, N->getType()); EXPECT_EQ(N, DITemplateTypeParameter::get(Context, Name, Type)); EXPECT_NE(N, DITemplateTypeParameter::get(Context, "other", Type)); EXPECT_NE(N, DITemplateTypeParameter::get(Context, Name, getBasicType("other"))); TempDITemplateTypeParameter Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DITemplateValueParameterTest; TEST_F(DITemplateValueParameterTest, get) { unsigned Tag = dwarf::DW_TAG_template_value_parameter; StringRef Name = "template"; DITypeRef Type = getBasicType("basic"); Metadata *Value = getConstantAsMetadata(); auto *N = DITemplateValueParameter::get(Context, Tag, Name, Type, Value); EXPECT_EQ(Tag, N->getTag()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(Type, N->getType()); EXPECT_EQ(Value, N->getValue()); EXPECT_EQ(N, DITemplateValueParameter::get(Context, Tag, Name, Type, Value)); EXPECT_NE(N, DITemplateValueParameter::get( Context, dwarf::DW_TAG_GNU_template_template_param, Name, Type, Value)); EXPECT_NE(N, DITemplateValueParameter::get(Context, Tag, "other", Type, Value)); EXPECT_NE(N, DITemplateValueParameter::get(Context, Tag, Name, getBasicType("other"), Value)); EXPECT_NE(N, DITemplateValueParameter::get(Context, Tag, Name, Type, getConstantAsMetadata())); TempDITemplateValueParameter Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DIGlobalVariableTest; TEST_F(DIGlobalVariableTest, get) { DIScope *Scope = getSubprogram(); StringRef Name = "name"; StringRef LinkageName = "linkage"; DIFile *File = getFile(); unsigned Line = 5; DITypeRef Type = getDerivedType(); bool IsLocalToUnit = false; bool IsDefinition = true; Constant *Variable = getConstant(); DIDerivedType *StaticDataMemberDeclaration = cast<DIDerivedType>(getDerivedType()); auto *N = DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration); EXPECT_EQ(dwarf::DW_TAG_variable, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(LinkageName, N->getLinkageName()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(Type, N->getType()); EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit()); EXPECT_EQ(IsDefinition, N->isDefinition()); EXPECT_EQ(Variable, N->getVariable()); EXPECT_EQ(StaticDataMemberDeclaration, N->getStaticDataMemberDeclaration()); EXPECT_EQ(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, getSubprogram(), Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, "other", LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, "other", File, Line, Type, IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, getFile(), Line, Type, IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line + 1, Type, IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line, getDerivedType(), IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line, Type, !IsLocalToUnit, IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, !IsDefinition, Variable, StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, getConstant(), StaticDataMemberDeclaration)); EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition, Variable, cast<DIDerivedType>(getDerivedType()))); TempDIGlobalVariable Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DILocalVariableTest; TEST_F(DILocalVariableTest, get) { unsigned Tag = dwarf::DW_TAG_arg_variable; DILocalScope *Scope = getSubprogram(); StringRef Name = "name"; DIFile *File = getFile(); unsigned Line = 5; DITypeRef Type = getDerivedType(); unsigned Arg = 6; unsigned Flags = 7; auto *N = DILocalVariable::get(Context, Tag, Scope, Name, File, Line, Type, Arg, Flags); EXPECT_EQ(Tag, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(Type, N->getType()); EXPECT_EQ(Arg, N->getArg()); EXPECT_EQ(Flags, N->getFlags()); EXPECT_EQ(N, DILocalVariable::get(Context, Tag, Scope, Name, File, Line, Type, Arg, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, dwarf::DW_TAG_auto_variable, Scope, Name, File, Line, Type, Arg, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, Tag, getSubprogram(), Name, File, Line, Type, Arg, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, Tag, Scope, "other", File, Line, Type, Arg, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, Tag, Scope, Name, getFile(), Line, Type, Arg, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, Tag, Scope, Name, File, Line + 1, Type, Arg, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, Tag, Scope, Name, File, Line, getDerivedType(), Arg, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, Tag, Scope, Name, File, Line, Type, Arg + 1, Flags)); EXPECT_NE(N, DILocalVariable::get(Context, Tag, Scope, Name, File, Line, Type, Arg, ~Flags)); TempDILocalVariable Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DILocalVariableTest, getArg256) { EXPECT_EQ(255u, DILocalVariable::get(Context, dwarf::DW_TAG_arg_variable, getSubprogram(), "", getFile(), 0, nullptr, 255, 0) ->getArg()); EXPECT_EQ(256u, DILocalVariable::get(Context, dwarf::DW_TAG_arg_variable, getSubprogram(), "", getFile(), 0, nullptr, 256, 0) ->getArg()); EXPECT_EQ(257u, DILocalVariable::get(Context, dwarf::DW_TAG_arg_variable, getSubprogram(), "", getFile(), 0, nullptr, 257, 0) ->getArg()); unsigned Max = UINT16_MAX; EXPECT_EQ(Max, DILocalVariable::get(Context, dwarf::DW_TAG_arg_variable, getSubprogram(), "", getFile(), 0, nullptr, Max, 0) ->getArg()); } typedef MetadataTest DIExpressionTest; TEST_F(DIExpressionTest, get) { uint64_t Elements[] = {2, 6, 9, 78, 0}; auto *N = DIExpression::get(Context, Elements); EXPECT_EQ(makeArrayRef(Elements), N->getElements()); EXPECT_EQ(N, DIExpression::get(Context, Elements)); EXPECT_EQ(5u, N->getNumElements()); EXPECT_EQ(2u, N->getElement(0)); EXPECT_EQ(6u, N->getElement(1)); EXPECT_EQ(9u, N->getElement(2)); EXPECT_EQ(78u, N->getElement(3)); EXPECT_EQ(0u, N->getElement(4)); TempDIExpression Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } TEST_F(DIExpressionTest, isValid) { #define EXPECT_VALID(...) \ do { \ uint64_t Elements[] = {__VA_ARGS__}; \ EXPECT_TRUE(DIExpression::get(Context, Elements)->isValid()); \ } while (false) #define EXPECT_INVALID(...) \ do { \ uint64_t Elements[] = {__VA_ARGS__}; \ EXPECT_FALSE(DIExpression::get(Context, Elements)->isValid()); \ } while (false) // Empty expression should be valid. EXPECT_TRUE(DIExpression::get(Context, None)); // Valid constructions. EXPECT_VALID(dwarf::DW_OP_plus, 6); EXPECT_VALID(dwarf::DW_OP_deref); EXPECT_VALID(dwarf::DW_OP_bit_piece, 3, 7); EXPECT_VALID(dwarf::DW_OP_plus, 6, dwarf::DW_OP_deref); EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6); EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_bit_piece, 3, 7); EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6, dwarf::DW_OP_bit_piece, 3, 7); // Invalid constructions. EXPECT_INVALID(~0u); EXPECT_INVALID(dwarf::DW_OP_plus); EXPECT_INVALID(dwarf::DW_OP_bit_piece); EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3); EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_plus, 3); EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_deref); #undef EXPECT_VALID #undef EXPECT_INVALID } typedef MetadataTest DIObjCPropertyTest; TEST_F(DIObjCPropertyTest, get) { StringRef Name = "name"; DIFile *File = getFile(); unsigned Line = 5; StringRef GetterName = "getter"; StringRef SetterName = "setter"; unsigned Attributes = 7; DITypeRef Type = getBasicType("basic"); auto *N = DIObjCProperty::get(Context, Name, File, Line, GetterName, SetterName, Attributes, Type); EXPECT_EQ(dwarf::DW_TAG_APPLE_property, N->getTag()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(File, N->getFile()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(GetterName, N->getGetterName()); EXPECT_EQ(SetterName, N->getSetterName()); EXPECT_EQ(Attributes, N->getAttributes()); EXPECT_EQ(Type, N->getType()); EXPECT_EQ(N, DIObjCProperty::get(Context, Name, File, Line, GetterName, SetterName, Attributes, Type)); EXPECT_NE(N, DIObjCProperty::get(Context, "other", File, Line, GetterName, SetterName, Attributes, Type)); EXPECT_NE(N, DIObjCProperty::get(Context, Name, getFile(), Line, GetterName, SetterName, Attributes, Type)); EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line + 1, GetterName, SetterName, Attributes, Type)); EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, "other", SetterName, Attributes, Type)); EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, GetterName, "other", Attributes, Type)); EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, GetterName, SetterName, Attributes + 1, Type)); EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, GetterName, SetterName, Attributes, getBasicType("other"))); TempDIObjCProperty Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest DIImportedEntityTest; TEST_F(DIImportedEntityTest, get) { unsigned Tag = dwarf::DW_TAG_imported_module; DIScope *Scope = getSubprogram(); DINodeRef Entity = getCompositeType(); unsigned Line = 5; StringRef Name = "name"; auto *N = DIImportedEntity::get(Context, Tag, Scope, Entity, Line, Name); EXPECT_EQ(Tag, N->getTag()); EXPECT_EQ(Scope, N->getScope()); EXPECT_EQ(Entity, N->getEntity()); EXPECT_EQ(Line, N->getLine()); EXPECT_EQ(Name, N->getName()); EXPECT_EQ(N, DIImportedEntity::get(Context, Tag, Scope, Entity, Line, Name)); EXPECT_NE(N, DIImportedEntity::get(Context, dwarf::DW_TAG_imported_declaration, Scope, Entity, Line, Name)); EXPECT_NE(N, DIImportedEntity::get(Context, Tag, getSubprogram(), Entity, Line, Name)); EXPECT_NE(N, DIImportedEntity::get(Context, Tag, Scope, getCompositeType(), Line, Name)); EXPECT_NE(N, DIImportedEntity::get(Context, Tag, Scope, Entity, Line + 1, Name)); EXPECT_NE(N, DIImportedEntity::get(Context, Tag, Scope, Entity, Line, "other")); TempDIImportedEntity Temp = N->clone(); EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp))); } typedef MetadataTest MetadataAsValueTest; TEST_F(MetadataAsValueTest, MDNode) { MDNode *N = MDNode::get(Context, None); auto *V = MetadataAsValue::get(Context, N); EXPECT_TRUE(V->getType()->isMetadataTy()); EXPECT_EQ(N, V->getMetadata()); auto *V2 = MetadataAsValue::get(Context, N); EXPECT_EQ(V, V2); } TEST_F(MetadataAsValueTest, MDNodeMDNode) { MDNode *N = MDNode::get(Context, None); Metadata *Ops[] = {N}; MDNode *N2 = MDNode::get(Context, Ops); auto *V = MetadataAsValue::get(Context, N2); EXPECT_TRUE(V->getType()->isMetadataTy()); EXPECT_EQ(N2, V->getMetadata()); auto *V2 = MetadataAsValue::get(Context, N2); EXPECT_EQ(V, V2); auto *V3 = MetadataAsValue::get(Context, N); EXPECT_TRUE(V3->getType()->isMetadataTy()); EXPECT_NE(V, V3); EXPECT_EQ(N, V3->getMetadata()); } TEST_F(MetadataAsValueTest, MDNodeConstant) { auto *C = ConstantInt::getTrue(Context); auto *MD = ConstantAsMetadata::get(C); Metadata *Ops[] = {MD}; auto *N = MDNode::get(Context, Ops); auto *V = MetadataAsValue::get(Context, MD); EXPECT_TRUE(V->getType()->isMetadataTy()); EXPECT_EQ(MD, V->getMetadata()); auto *V2 = MetadataAsValue::get(Context, N); EXPECT_EQ(MD, V2->getMetadata()); EXPECT_EQ(V, V2); } typedef MetadataTest ValueAsMetadataTest; TEST_F(ValueAsMetadataTest, UpdatesOnRAUW) { Type *Ty = Type::getInt1PtrTy(Context); std::unique_ptr<GlobalVariable> GV0( new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage)); auto *MD = ValueAsMetadata::get(GV0.get()); EXPECT_TRUE(MD->getValue() == GV0.get()); ASSERT_TRUE(GV0->use_empty()); std::unique_ptr<GlobalVariable> GV1( new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage)); GV0->replaceAllUsesWith(GV1.get()); EXPECT_TRUE(MD->getValue() == GV1.get()); } TEST_F(ValueAsMetadataTest, CollidingDoubleUpdates) { // Create a constant. ConstantAsMetadata *CI = ConstantAsMetadata::get( ConstantInt::get(getGlobalContext(), APInt(8, 0))); // Create a temporary to prevent nodes from resolving. auto Temp = MDTuple::getTemporary(Context, None); // When the first operand of N1 gets reset to nullptr, it'll collide with N2. Metadata *Ops1[] = {CI, CI, Temp.get()}; Metadata *Ops2[] = {nullptr, CI, Temp.get()}; auto *N1 = MDTuple::get(Context, Ops1); auto *N2 = MDTuple::get(Context, Ops2); ASSERT_NE(N1, N2); // Tell metadata that the constant is getting deleted. // // After this, N1 will be invalid, so don't touch it. ValueAsMetadata::handleDeletion(CI->getValue()); EXPECT_EQ(nullptr, N2->getOperand(0)); EXPECT_EQ(nullptr, N2->getOperand(1)); EXPECT_EQ(Temp.get(), N2->getOperand(2)); // Clean up Temp for teardown. Temp->replaceAllUsesWith(nullptr); } typedef MetadataTest TrackingMDRefTest; TEST_F(TrackingMDRefTest, UpdatesOnRAUW) { Type *Ty = Type::getInt1PtrTy(Context); std::unique_ptr<GlobalVariable> GV0( new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage)); TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV0.get())); EXPECT_TRUE(MD->getValue() == GV0.get()); ASSERT_TRUE(GV0->use_empty()); std::unique_ptr<GlobalVariable> GV1( new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage)); GV0->replaceAllUsesWith(GV1.get()); EXPECT_TRUE(MD->getValue() == GV1.get()); // Reset it, so we don't inadvertently test deletion. MD.reset(); } TEST_F(TrackingMDRefTest, UpdatesOnDeletion) { Type *Ty = Type::getInt1PtrTy(Context); std::unique_ptr<GlobalVariable> GV( new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage)); TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV.get())); EXPECT_TRUE(MD->getValue() == GV.get()); ASSERT_TRUE(GV->use_empty()); GV.reset(); EXPECT_TRUE(!MD); } TEST(NamedMDNodeTest, Search) { LLVMContext Context; ConstantAsMetadata *C = ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 1)); ConstantAsMetadata *C2 = ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 2)); Metadata *const V = C; Metadata *const V2 = C2; MDNode *n = MDNode::get(Context, V); MDNode *n2 = MDNode::get(Context, V2); Module M("MyModule", Context); const char *Name = "llvm.NMD1"; NamedMDNode *NMD = M.getOrInsertNamedMetadata(Name); NMD->addOperand(n); NMD->addOperand(n2); std::string Str; raw_string_ostream oss(Str); NMD->print(oss); EXPECT_STREQ("!llvm.NMD1 = !{!0, !1}\n", oss.str().c_str()); } typedef MetadataTest FunctionAttachmentTest; TEST_F(FunctionAttachmentTest, setMetadata) { Function *F = getFunction("foo"); ASSERT_FALSE(F->hasMetadata()); EXPECT_EQ(nullptr, F->getMetadata(LLVMContext::MD_dbg)); EXPECT_EQ(nullptr, F->getMetadata("dbg")); EXPECT_EQ(nullptr, F->getMetadata("other")); DISubprogram *SP1 = getSubprogram(); DISubprogram *SP2 = getSubprogram(); ASSERT_NE(SP1, SP2); F->setMetadata("dbg", SP1); EXPECT_TRUE(F->hasMetadata()); EXPECT_EQ(SP1, F->getMetadata(LLVMContext::MD_dbg)); EXPECT_EQ(SP1, F->getMetadata("dbg")); EXPECT_EQ(nullptr, F->getMetadata("other")); F->setMetadata(LLVMContext::MD_dbg, SP2); EXPECT_TRUE(F->hasMetadata()); EXPECT_EQ(SP2, F->getMetadata(LLVMContext::MD_dbg)); EXPECT_EQ(SP2, F->getMetadata("dbg")); EXPECT_EQ(nullptr, F->getMetadata("other")); F->setMetadata("dbg", nullptr); EXPECT_FALSE(F->hasMetadata()); EXPECT_EQ(nullptr, F->getMetadata(LLVMContext::MD_dbg)); EXPECT_EQ(nullptr, F->getMetadata("dbg")); EXPECT_EQ(nullptr, F->getMetadata("other")); MDTuple *T1 = getTuple(); MDTuple *T2 = getTuple(); ASSERT_NE(T1, T2); F->setMetadata("other1", T1); F->setMetadata("other2", T2); EXPECT_TRUE(F->hasMetadata()); EXPECT_EQ(T1, F->getMetadata("other1")); EXPECT_EQ(T2, F->getMetadata("other2")); EXPECT_EQ(nullptr, F->getMetadata("dbg")); F->setMetadata("other1", T2); F->setMetadata("other2", T1); EXPECT_EQ(T2, F->getMetadata("other1")); EXPECT_EQ(T1, F->getMetadata("other2")); F->setMetadata("other1", nullptr); F->setMetadata("other2", nullptr); EXPECT_FALSE(F->hasMetadata()); EXPECT_EQ(nullptr, F->getMetadata("other1")); EXPECT_EQ(nullptr, F->getMetadata("other2")); } TEST_F(FunctionAttachmentTest, getAll) { Function *F = getFunction("foo"); MDTuple *T1 = getTuple(); MDTuple *T2 = getTuple(); MDTuple *P = getTuple(); DISubprogram *SP = getSubprogram(); F->setMetadata("other1", T2); F->setMetadata(LLVMContext::MD_dbg, SP); F->setMetadata("other2", T1); F->setMetadata(LLVMContext::MD_prof, P); F->setMetadata("other2", T2); F->setMetadata("other1", T1); SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; F->getAllMetadata(MDs); ASSERT_EQ(4u, MDs.size()); EXPECT_EQ(LLVMContext::MD_dbg, MDs[0].first); EXPECT_EQ(LLVMContext::MD_prof, MDs[1].first); EXPECT_EQ(Context.getMDKindID("other1"), MDs[2].first); EXPECT_EQ(Context.getMDKindID("other2"), MDs[3].first); EXPECT_EQ(SP, MDs[0].second); EXPECT_EQ(P, MDs[1].second); EXPECT_EQ(T1, MDs[2].second); EXPECT_EQ(T2, MDs[3].second); } TEST_F(FunctionAttachmentTest, dropUnknownMetadata) { Function *F = getFunction("foo"); MDTuple *T1 = getTuple(); MDTuple *T2 = getTuple(); MDTuple *P = getTuple(); DISubprogram *SP = getSubprogram(); F->setMetadata("other1", T1); F->setMetadata(LLVMContext::MD_dbg, SP); F->setMetadata("other2", T2); F->setMetadata(LLVMContext::MD_prof, P); unsigned Known[] = {Context.getMDKindID("other2"), LLVMContext::MD_prof}; F->dropUnknownMetadata(Known); EXPECT_EQ(T2, F->getMetadata("other2")); EXPECT_EQ(P, F->getMetadata(LLVMContext::MD_prof)); EXPECT_EQ(nullptr, F->getMetadata("other1")); EXPECT_EQ(nullptr, F->getMetadata(LLVMContext::MD_dbg)); F->setMetadata("other2", nullptr); F->setMetadata(LLVMContext::MD_prof, nullptr); EXPECT_FALSE(F->hasMetadata()); } TEST_F(FunctionAttachmentTest, Verifier) { Function *F = getFunction("foo"); F->setMetadata("attach", getTuple()); // Confirm this has no body. ASSERT_TRUE(F->empty()); // Functions without a body cannot have metadata attachments (they also can't // be verified directly, so check that the module fails to verify). EXPECT_TRUE(verifyModule(*F->getParent())); // Functions with a body can. (void)new UnreachableInst(Context, BasicBlock::Create(Context, "bb", F)); EXPECT_FALSE(verifyModule(*F->getParent())); EXPECT_FALSE(verifyFunction(*F)); } TEST_F(FunctionAttachmentTest, EntryCount) { Function *F = getFunction("foo"); EXPECT_FALSE(F->getEntryCount().hasValue()); F->setEntryCount(12304); EXPECT_TRUE(F->getEntryCount().hasValue()); EXPECT_EQ(12304u, *F->getEntryCount()); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/InstructionsTest.cpp
//===- llvm/unittest/IR/InstructionsTest.cpp - Instructions unit tests ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Instructions.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Operator.h" #include "gtest/gtest.h" #include <memory> namespace llvm { namespace { TEST(InstructionsTest, ReturnInst) { LLVMContext &C(getGlobalContext()); // test for PR6589 const ReturnInst* r0 = ReturnInst::Create(C); EXPECT_EQ(r0->getNumOperands(), 0U); EXPECT_EQ(r0->op_begin(), r0->op_end()); IntegerType* Int1 = IntegerType::get(C, 1); Constant* One = ConstantInt::get(Int1, 1, true); const ReturnInst* r1 = ReturnInst::Create(C, One); EXPECT_EQ(1U, r1->getNumOperands()); User::const_op_iterator b(r1->op_begin()); EXPECT_NE(r1->op_end(), b); EXPECT_EQ(One, *b); EXPECT_EQ(One, r1->getOperand(0)); ++b; EXPECT_EQ(r1->op_end(), b); // clean up delete r0; delete r1; } // Test fixture that provides a module and a single function within it. Useful // for tests that need to refer to the function in some way. class ModuleWithFunctionTest : public testing::Test { protected: ModuleWithFunctionTest() : M(new Module("MyModule", Ctx)) { FArgTypes.push_back(Type::getInt8Ty(Ctx)); FArgTypes.push_back(Type::getInt32Ty(Ctx)); FArgTypes.push_back(Type::getInt64Ty(Ctx)); FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), FArgTypes, false); F = Function::Create(FTy, Function::ExternalLinkage, "", M.get()); } LLVMContext Ctx; std::unique_ptr<Module> M; SmallVector<Type *, 3> FArgTypes; Function *F; }; TEST_F(ModuleWithFunctionTest, CallInst) { Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20), ConstantInt::get(Type::getInt32Ty(Ctx), 9999), ConstantInt::get(Type::getInt64Ty(Ctx), 42)}; std::unique_ptr<CallInst> Call(CallInst::Create(F, Args)); // Make sure iteration over a call's arguments works as expected. unsigned Idx = 0; for (Value *Arg : Call->arg_operands()) { EXPECT_EQ(FArgTypes[Idx], Arg->getType()); EXPECT_EQ(Call->getArgOperand(Idx)->getType(), Arg->getType()); Idx++; } } TEST_F(ModuleWithFunctionTest, InvokeInst) { BasicBlock *BB1 = BasicBlock::Create(Ctx, "", F); BasicBlock *BB2 = BasicBlock::Create(Ctx, "", F); Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20), ConstantInt::get(Type::getInt32Ty(Ctx), 9999), ConstantInt::get(Type::getInt64Ty(Ctx), 42)}; std::unique_ptr<InvokeInst> Invoke(InvokeInst::Create(F, BB1, BB2, Args)); // Make sure iteration over invoke's arguments works as expected. unsigned Idx = 0; for (Value *Arg : Invoke->arg_operands()) { EXPECT_EQ(FArgTypes[Idx], Arg->getType()); EXPECT_EQ(Invoke->getArgOperand(Idx)->getType(), Arg->getType()); Idx++; } } TEST(InstructionsTest, BranchInst) { LLVMContext &C(getGlobalContext()); // Make a BasicBlocks BasicBlock* bb0 = BasicBlock::Create(C); BasicBlock* bb1 = BasicBlock::Create(C); // Mandatory BranchInst const BranchInst* b0 = BranchInst::Create(bb0); EXPECT_TRUE(b0->isUnconditional()); EXPECT_FALSE(b0->isConditional()); EXPECT_EQ(1U, b0->getNumSuccessors()); // check num operands EXPECT_EQ(1U, b0->getNumOperands()); EXPECT_NE(b0->op_begin(), b0->op_end()); EXPECT_EQ(b0->op_end(), std::next(b0->op_begin())); EXPECT_EQ(b0->op_end(), std::next(b0->op_begin())); IntegerType* Int1 = IntegerType::get(C, 1); Constant* One = ConstantInt::get(Int1, 1, true); // Conditional BranchInst BranchInst* b1 = BranchInst::Create(bb0, bb1, One); EXPECT_FALSE(b1->isUnconditional()); EXPECT_TRUE(b1->isConditional()); EXPECT_EQ(2U, b1->getNumSuccessors()); // check num operands EXPECT_EQ(3U, b1->getNumOperands()); User::const_op_iterator b(b1->op_begin()); // check COND EXPECT_NE(b, b1->op_end()); EXPECT_EQ(One, *b); EXPECT_EQ(One, b1->getOperand(0)); EXPECT_EQ(One, b1->getCondition()); ++b; // check ELSE EXPECT_EQ(bb1, *b); EXPECT_EQ(bb1, b1->getOperand(1)); EXPECT_EQ(bb1, b1->getSuccessor(1)); ++b; // check THEN EXPECT_EQ(bb0, *b); EXPECT_EQ(bb0, b1->getOperand(2)); EXPECT_EQ(bb0, b1->getSuccessor(0)); ++b; EXPECT_EQ(b1->op_end(), b); // clean up delete b0; delete b1; delete bb0; delete bb1; } TEST(InstructionsTest, CastInst) { LLVMContext &C(getGlobalContext()); Type *Int8Ty = Type::getInt8Ty(C); Type *Int16Ty = Type::getInt16Ty(C); Type *Int32Ty = Type::getInt32Ty(C); Type *Int64Ty = Type::getInt64Ty(C); Type *V8x8Ty = VectorType::get(Int8Ty, 8); Type *V8x64Ty = VectorType::get(Int64Ty, 8); Type *X86MMXTy = Type::getX86_MMXTy(C); Type *HalfTy = Type::getHalfTy(C); Type *FloatTy = Type::getFloatTy(C); Type *DoubleTy = Type::getDoubleTy(C); Type *V2Int32Ty = VectorType::get(Int32Ty, 2); Type *V2Int64Ty = VectorType::get(Int64Ty, 2); Type *V4Int16Ty = VectorType::get(Int16Ty, 4); Type *Int32PtrTy = PointerType::get(Int32Ty, 0); Type *Int64PtrTy = PointerType::get(Int64Ty, 0); Type *Int32PtrAS1Ty = PointerType::get(Int32Ty, 1); Type *Int64PtrAS1Ty = PointerType::get(Int64Ty, 1); Type *V2Int32PtrAS1Ty = VectorType::get(Int32PtrAS1Ty, 2); Type *V2Int64PtrAS1Ty = VectorType::get(Int64PtrAS1Ty, 2); Type *V4Int32PtrAS1Ty = VectorType::get(Int32PtrAS1Ty, 4); Type *V4Int64PtrAS1Ty = VectorType::get(Int64PtrAS1Ty, 4); Type *V2Int64PtrTy = VectorType::get(Int64PtrTy, 2); Type *V2Int32PtrTy = VectorType::get(Int32PtrTy, 2); Type *V4Int32PtrTy = VectorType::get(Int32PtrTy, 4); const Constant* c8 = Constant::getNullValue(V8x8Ty); const Constant* c64 = Constant::getNullValue(V8x64Ty); const Constant *v2ptr32 = Constant::getNullValue(V2Int32PtrTy); EXPECT_TRUE(CastInst::isCastable(V8x8Ty, X86MMXTy)); EXPECT_TRUE(CastInst::isCastable(X86MMXTy, V8x8Ty)); EXPECT_FALSE(CastInst::isCastable(Int64Ty, X86MMXTy)); EXPECT_TRUE(CastInst::isCastable(V8x64Ty, V8x8Ty)); EXPECT_TRUE(CastInst::isCastable(V8x8Ty, V8x64Ty)); EXPECT_EQ(CastInst::Trunc, CastInst::getCastOpcode(c64, true, V8x8Ty, true)); EXPECT_EQ(CastInst::SExt, CastInst::getCastOpcode(c8, true, V8x64Ty, true)); EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, X86MMXTy)); EXPECT_FALSE(CastInst::isBitCastable(X86MMXTy, V8x8Ty)); EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, X86MMXTy)); EXPECT_FALSE(CastInst::isBitCastable(V8x64Ty, V8x8Ty)); EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, V8x64Ty)); // Check address space casts are rejected since we don't know the sizes here EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, Int32PtrAS1Ty)); EXPECT_FALSE(CastInst::isBitCastable(Int32PtrAS1Ty, Int32PtrTy)); EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, V2Int32PtrAS1Ty)); EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int32PtrTy)); EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int64PtrAS1Ty)); EXPECT_TRUE(CastInst::isCastable(V2Int32PtrAS1Ty, V2Int32PtrTy)); EXPECT_EQ(CastInst::AddrSpaceCast, CastInst::getCastOpcode(v2ptr32, true, V2Int32PtrAS1Ty, true)); // Test mismatched number of elements for pointers EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int64PtrAS1Ty)); EXPECT_FALSE(CastInst::isBitCastable(V4Int64PtrAS1Ty, V2Int32PtrAS1Ty)); EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int32PtrAS1Ty)); EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, V2Int32PtrTy)); EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int32PtrTy)); EXPECT_TRUE(CastInst::isBitCastable(Int32PtrTy, Int64PtrTy)); EXPECT_FALSE(CastInst::isBitCastable(DoubleTy, FloatTy)); EXPECT_FALSE(CastInst::isBitCastable(FloatTy, DoubleTy)); EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy)); EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy)); EXPECT_TRUE(CastInst::isBitCastable(FloatTy, Int32Ty)); EXPECT_TRUE(CastInst::isBitCastable(Int16Ty, HalfTy)); EXPECT_TRUE(CastInst::isBitCastable(Int32Ty, FloatTy)); EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, Int64Ty)); EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, V4Int16Ty)); EXPECT_FALSE(CastInst::isBitCastable(Int32Ty, Int64Ty)); EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, Int32Ty)); EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int64Ty)); EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, V2Int32PtrTy)); EXPECT_TRUE(CastInst::isBitCastable(V2Int64PtrTy, V2Int32PtrTy)); EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrTy, V2Int64PtrTy)); EXPECT_FALSE(CastInst::isBitCastable(V2Int32Ty, V2Int64Ty)); EXPECT_FALSE(CastInst::isBitCastable(V2Int64Ty, V2Int32Ty)); EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast, Constant::getNullValue(V4Int32PtrTy), V2Int32PtrTy)); EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast, Constant::getNullValue(V2Int32PtrTy), V4Int32PtrTy)); EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast, Constant::getNullValue(V4Int32PtrAS1Ty), V2Int32PtrTy)); EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast, Constant::getNullValue(V2Int32PtrTy), V4Int32PtrAS1Ty)); // Check that assertion is not hit when creating a cast with a vector of // pointers // First form BasicBlock *BB = BasicBlock::Create(C); Constant *NullV2I32Ptr = Constant::getNullValue(V2Int32PtrTy); CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty, "foo", BB); // Second form CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty); } TEST(InstructionsTest, VectorGep) { LLVMContext &C(getGlobalContext()); // Type Definitions Type *I8Ty = IntegerType::get(C, 8); Type *I32Ty = IntegerType::get(C, 32); PointerType *Ptri8Ty = PointerType::get(I8Ty, 0); PointerType *Ptri32Ty = PointerType::get(I32Ty, 0); VectorType *V2xi8PTy = VectorType::get(Ptri8Ty, 2); VectorType *V2xi32PTy = VectorType::get(Ptri32Ty, 2); // Test different aspects of the vector-of-pointers type // and GEPs which use this type. ConstantInt *Ci32a = ConstantInt::get(C, APInt(32, 1492)); ConstantInt *Ci32b = ConstantInt::get(C, APInt(32, 1948)); std::vector<Constant*> ConstVa(2, Ci32a); std::vector<Constant*> ConstVb(2, Ci32b); Constant *C2xi32a = ConstantVector::get(ConstVa); Constant *C2xi32b = ConstantVector::get(ConstVb); CastInst *PtrVecA = new IntToPtrInst(C2xi32a, V2xi32PTy); CastInst *PtrVecB = new IntToPtrInst(C2xi32b, V2xi32PTy); ICmpInst *ICmp0 = new ICmpInst(ICmpInst::ICMP_SGT, PtrVecA, PtrVecB); ICmpInst *ICmp1 = new ICmpInst(ICmpInst::ICMP_ULT, PtrVecA, PtrVecB); EXPECT_NE(ICmp0, ICmp1); // suppress warning. BasicBlock* BB0 = BasicBlock::Create(C); // Test InsertAtEnd ICmpInst constructor. ICmpInst *ICmp2 = new ICmpInst(*BB0, ICmpInst::ICMP_SGE, PtrVecA, PtrVecB); EXPECT_NE(ICmp0, ICmp2); // suppress warning. GetElementPtrInst *Gep0 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32a); GetElementPtrInst *Gep1 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32b); GetElementPtrInst *Gep2 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32a); GetElementPtrInst *Gep3 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32b); CastInst *BTC0 = new BitCastInst(Gep0, V2xi8PTy); CastInst *BTC1 = new BitCastInst(Gep1, V2xi8PTy); CastInst *BTC2 = new BitCastInst(Gep2, V2xi8PTy); CastInst *BTC3 = new BitCastInst(Gep3, V2xi8PTy); Value *S0 = BTC0->stripPointerCasts(); Value *S1 = BTC1->stripPointerCasts(); Value *S2 = BTC2->stripPointerCasts(); Value *S3 = BTC3->stripPointerCasts(); EXPECT_NE(S0, Gep0); EXPECT_NE(S1, Gep1); EXPECT_NE(S2, Gep2); EXPECT_NE(S3, Gep3); int64_t Offset; DataLayout TD("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f3" "2:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-s:64:64-f80" ":128:128-n8:16:32:64-S128"); // Make sure we don't crash GetPointerBaseWithConstantOffset(Gep0, Offset, TD); GetPointerBaseWithConstantOffset(Gep1, Offset, TD); GetPointerBaseWithConstantOffset(Gep2, Offset, TD); GetPointerBaseWithConstantOffset(Gep3, Offset, TD); // Gep of Geps GetElementPtrInst *GepII0 = GetElementPtrInst::Create(I32Ty, Gep0, C2xi32b); GetElementPtrInst *GepII1 = GetElementPtrInst::Create(I32Ty, Gep1, C2xi32a); GetElementPtrInst *GepII2 = GetElementPtrInst::Create(I32Ty, Gep2, C2xi32b); GetElementPtrInst *GepII3 = GetElementPtrInst::Create(I32Ty, Gep3, C2xi32a); EXPECT_EQ(GepII0->getNumIndices(), 1u); EXPECT_EQ(GepII1->getNumIndices(), 1u); EXPECT_EQ(GepII2->getNumIndices(), 1u); EXPECT_EQ(GepII3->getNumIndices(), 1u); EXPECT_FALSE(GepII0->hasAllZeroIndices()); EXPECT_FALSE(GepII1->hasAllZeroIndices()); EXPECT_FALSE(GepII2->hasAllZeroIndices()); EXPECT_FALSE(GepII3->hasAllZeroIndices()); delete GepII0; delete GepII1; delete GepII2; delete GepII3; delete BTC0; delete BTC1; delete BTC2; delete BTC3; delete Gep0; delete Gep1; delete Gep2; delete Gep3; ICmp2->eraseFromParent(); delete BB0; delete ICmp0; delete ICmp1; delete PtrVecA; delete PtrVecB; } TEST(InstructionsTest, FPMathOperator) { LLVMContext &Context = getGlobalContext(); IRBuilder<> Builder(Context); MDBuilder MDHelper(Context); Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0); MDNode *MD1 = MDHelper.createFPMath(1.0); Value *V1 = Builder.CreateFAdd(I, I, "", MD1); EXPECT_TRUE(isa<FPMathOperator>(V1)); FPMathOperator *O1 = cast<FPMathOperator>(V1); EXPECT_EQ(O1->getFPAccuracy(), 1.0); delete V1; delete I; } TEST(InstructionsTest, isEliminableCastPair) { LLVMContext &C(getGlobalContext()); Type* Int16Ty = Type::getInt16Ty(C); Type* Int32Ty = Type::getInt32Ty(C); Type* Int64Ty = Type::getInt64Ty(C); Type* Int64PtrTy = Type::getInt64PtrTy(C); // Source and destination pointers have same size -> bitcast. EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt, CastInst::IntToPtr, Int64PtrTy, Int64Ty, Int64PtrTy, Int32Ty, nullptr, Int32Ty), CastInst::BitCast); // Source and destination have unknown sizes, but the same address space and // the intermediate int is the maximum pointer size -> bitcast EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt, CastInst::IntToPtr, Int64PtrTy, Int64Ty, Int64PtrTy, nullptr, nullptr, nullptr), CastInst::BitCast); // Source and destination have unknown sizes, but the same address space and // the intermediate int is not the maximum pointer size -> nothing EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt, CastInst::IntToPtr, Int64PtrTy, Int32Ty, Int64PtrTy, nullptr, nullptr, nullptr), 0U); // Middle pointer big enough -> bitcast. EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr, CastInst::PtrToInt, Int64Ty, Int64PtrTy, Int64Ty, nullptr, Int64Ty, nullptr), CastInst::BitCast); // Middle pointer too small -> fail. EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr, CastInst::PtrToInt, Int64Ty, Int64PtrTy, Int64Ty, nullptr, Int32Ty, nullptr), 0U); // Test that we don't eliminate bitcasts between different address spaces, // or if we don't have available pointer size information. DataLayout DL("e-p:32:32:32-p1:16:16:16-p2:64:64:64-i1:8:8-i8:8:8-i16:16:16" "-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64" "-v128:128:128-a:0:64-s:64:64-f80:128:128-n8:16:32:64-S128"); Type* Int64PtrTyAS1 = Type::getInt64PtrTy(C, 1); Type* Int64PtrTyAS2 = Type::getInt64PtrTy(C, 2); IntegerType *Int16SizePtr = DL.getIntPtrType(C, 1); IntegerType *Int64SizePtr = DL.getIntPtrType(C, 2); // Cannot simplify inttoptr, addrspacecast EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr, CastInst::AddrSpaceCast, Int16Ty, Int64PtrTyAS1, Int64PtrTyAS2, nullptr, Int16SizePtr, Int64SizePtr), 0U); // Cannot simplify addrspacecast, ptrtoint EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::AddrSpaceCast, CastInst::PtrToInt, Int64PtrTyAS1, Int64PtrTyAS2, Int16Ty, Int64SizePtr, Int16SizePtr, nullptr), 0U); // Pass since the bitcast address spaces are the same EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr, CastInst::BitCast, Int16Ty, Int64PtrTyAS1, Int64PtrTyAS1, nullptr, nullptr, nullptr), CastInst::IntToPtr); } TEST(InstructionsTest, CloneCall) { LLVMContext &C(getGlobalContext()); Type *Int32Ty = Type::getInt32Ty(C); Type *ArgTys[] = {Int32Ty, Int32Ty, Int32Ty}; Type *FnTy = FunctionType::get(Int32Ty, ArgTys, /*isVarArg=*/false); Value *Callee = Constant::getNullValue(FnTy->getPointerTo()); Value *Args[] = { ConstantInt::get(Int32Ty, 1), ConstantInt::get(Int32Ty, 2), ConstantInt::get(Int32Ty, 3) }; std::unique_ptr<CallInst> Call(CallInst::Create(Callee, Args, "result")); // Test cloning the tail call kind. CallInst::TailCallKind Kinds[] = {CallInst::TCK_None, CallInst::TCK_Tail, CallInst::TCK_MustTail}; for (CallInst::TailCallKind TCK : Kinds) { Call->setTailCallKind(TCK); std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone())); EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind()); } Call->setTailCallKind(CallInst::TCK_None); // Test cloning an attribute. { AttrBuilder AB; AB.addAttribute(Attribute::ReadOnly); Call->setAttributes(AttributeSet::get(C, AttributeSet::FunctionIndex, AB)); std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone())); EXPECT_TRUE(Clone->onlyReadsMemory()); } } } // end anonymous namespace } // end namespace llvm
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/DominatorTreeTest.cpp
//===- llvm/unittests/IR/DominatorTreeTest.cpp - Constants unit tests -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Dominators.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace llvm { void initializeDPassPass(PassRegistry&); namespace { struct DPass : public FunctionPass { static char ID; bool runOnFunction(Function &F) override { DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>(); Function::iterator FI = F.begin(); BasicBlock *BB0 = FI++; BasicBlock::iterator BBI = BB0->begin(); Instruction *Y1 = BBI++; Instruction *Y2 = BBI++; Instruction *Y3 = BBI++; BasicBlock *BB1 = FI++; BBI = BB1->begin(); Instruction *Y4 = BBI++; BasicBlock *BB2 = FI++; BBI = BB2->begin(); Instruction *Y5 = BBI++; BasicBlock *BB3 = FI++; BBI = BB3->begin(); Instruction *Y6 = BBI++; Instruction *Y7 = BBI++; BasicBlock *BB4 = FI++; BBI = BB4->begin(); Instruction *Y8 = BBI++; Instruction *Y9 = BBI++; // Reachability EXPECT_TRUE(DT->isReachableFromEntry(BB0)); EXPECT_TRUE(DT->isReachableFromEntry(BB1)); EXPECT_TRUE(DT->isReachableFromEntry(BB2)); EXPECT_FALSE(DT->isReachableFromEntry(BB3)); EXPECT_TRUE(DT->isReachableFromEntry(BB4)); // BB dominance EXPECT_TRUE(DT->dominates(BB0, BB0)); EXPECT_TRUE(DT->dominates(BB0, BB1)); EXPECT_TRUE(DT->dominates(BB0, BB2)); EXPECT_TRUE(DT->dominates(BB0, BB3)); EXPECT_TRUE(DT->dominates(BB0, BB4)); EXPECT_FALSE(DT->dominates(BB1, BB0)); EXPECT_TRUE(DT->dominates(BB1, BB1)); EXPECT_FALSE(DT->dominates(BB1, BB2)); EXPECT_TRUE(DT->dominates(BB1, BB3)); EXPECT_FALSE(DT->dominates(BB1, BB4)); EXPECT_FALSE(DT->dominates(BB2, BB0)); EXPECT_FALSE(DT->dominates(BB2, BB1)); EXPECT_TRUE(DT->dominates(BB2, BB2)); EXPECT_TRUE(DT->dominates(BB2, BB3)); EXPECT_FALSE(DT->dominates(BB2, BB4)); EXPECT_FALSE(DT->dominates(BB3, BB0)); EXPECT_FALSE(DT->dominates(BB3, BB1)); EXPECT_FALSE(DT->dominates(BB3, BB2)); EXPECT_TRUE(DT->dominates(BB3, BB3)); EXPECT_FALSE(DT->dominates(BB3, BB4)); // BB proper dominance EXPECT_FALSE(DT->properlyDominates(BB0, BB0)); EXPECT_TRUE(DT->properlyDominates(BB0, BB1)); EXPECT_TRUE(DT->properlyDominates(BB0, BB2)); EXPECT_TRUE(DT->properlyDominates(BB0, BB3)); EXPECT_FALSE(DT->properlyDominates(BB1, BB0)); EXPECT_FALSE(DT->properlyDominates(BB1, BB1)); EXPECT_FALSE(DT->properlyDominates(BB1, BB2)); EXPECT_TRUE(DT->properlyDominates(BB1, BB3)); EXPECT_FALSE(DT->properlyDominates(BB2, BB0)); EXPECT_FALSE(DT->properlyDominates(BB2, BB1)); EXPECT_FALSE(DT->properlyDominates(BB2, BB2)); EXPECT_TRUE(DT->properlyDominates(BB2, BB3)); EXPECT_FALSE(DT->properlyDominates(BB3, BB0)); EXPECT_FALSE(DT->properlyDominates(BB3, BB1)); EXPECT_FALSE(DT->properlyDominates(BB3, BB2)); EXPECT_FALSE(DT->properlyDominates(BB3, BB3)); // Instruction dominance in the same reachable BB EXPECT_FALSE(DT->dominates(Y1, Y1)); EXPECT_TRUE(DT->dominates(Y1, Y2)); EXPECT_FALSE(DT->dominates(Y2, Y1)); EXPECT_FALSE(DT->dominates(Y2, Y2)); // Instruction dominance in the same unreachable BB EXPECT_TRUE(DT->dominates(Y6, Y6)); EXPECT_TRUE(DT->dominates(Y6, Y7)); EXPECT_TRUE(DT->dominates(Y7, Y6)); EXPECT_TRUE(DT->dominates(Y7, Y7)); // Invoke EXPECT_TRUE(DT->dominates(Y3, Y4)); EXPECT_FALSE(DT->dominates(Y3, Y5)); // Phi EXPECT_TRUE(DT->dominates(Y2, Y9)); EXPECT_FALSE(DT->dominates(Y3, Y9)); EXPECT_FALSE(DT->dominates(Y8, Y9)); // Anything dominates unreachable EXPECT_TRUE(DT->dominates(Y1, Y6)); EXPECT_TRUE(DT->dominates(Y3, Y6)); // Unreachable doesn't dominate reachable EXPECT_FALSE(DT->dominates(Y6, Y1)); // Instruction, BB dominance EXPECT_FALSE(DT->dominates(Y1, BB0)); EXPECT_TRUE(DT->dominates(Y1, BB1)); EXPECT_TRUE(DT->dominates(Y1, BB2)); EXPECT_TRUE(DT->dominates(Y1, BB3)); EXPECT_TRUE(DT->dominates(Y1, BB4)); EXPECT_FALSE(DT->dominates(Y3, BB0)); EXPECT_TRUE(DT->dominates(Y3, BB1)); EXPECT_FALSE(DT->dominates(Y3, BB2)); EXPECT_TRUE(DT->dominates(Y3, BB3)); EXPECT_FALSE(DT->dominates(Y3, BB4)); EXPECT_TRUE(DT->dominates(Y6, BB3)); // Post dominance. EXPECT_TRUE(PDT->dominates(BB0, BB0)); EXPECT_FALSE(PDT->dominates(BB1, BB0)); EXPECT_FALSE(PDT->dominates(BB2, BB0)); EXPECT_FALSE(PDT->dominates(BB3, BB0)); EXPECT_TRUE(PDT->dominates(BB4, BB1)); // Dominance descendants. SmallVector<BasicBlock *, 8> DominatedBBs, PostDominatedBBs; DT->getDescendants(BB0, DominatedBBs); PDT->getDescendants(BB0, PostDominatedBBs); EXPECT_EQ(DominatedBBs.size(), 4UL); EXPECT_EQ(PostDominatedBBs.size(), 1UL); // BB3 is unreachable. It should have no dominators nor postdominators. DominatedBBs.clear(); PostDominatedBBs.clear(); DT->getDescendants(BB3, DominatedBBs); DT->getDescendants(BB3, PostDominatedBBs); EXPECT_EQ(DominatedBBs.size(), 0UL); EXPECT_EQ(PostDominatedBBs.size(), 0UL); // Check DFS Numbers before EXPECT_EQ(DT->getNode(BB0)->getDFSNumIn(), 0UL); EXPECT_EQ(DT->getNode(BB0)->getDFSNumOut(), 7UL); EXPECT_EQ(DT->getNode(BB1)->getDFSNumIn(), 1UL); EXPECT_EQ(DT->getNode(BB1)->getDFSNumOut(), 2UL); EXPECT_EQ(DT->getNode(BB2)->getDFSNumIn(), 5UL); EXPECT_EQ(DT->getNode(BB2)->getDFSNumOut(), 6UL); EXPECT_EQ(DT->getNode(BB4)->getDFSNumIn(), 3UL); EXPECT_EQ(DT->getNode(BB4)->getDFSNumOut(), 4UL); // Reattach block 3 to block 1 and recalculate BB1->getTerminator()->eraseFromParent(); BranchInst::Create(BB4, BB3, ConstantInt::getTrue(F.getContext()), BB1); DT->recalculate(F); // Check DFS Numbers after EXPECT_EQ(DT->getNode(BB0)->getDFSNumIn(), 0UL); EXPECT_EQ(DT->getNode(BB0)->getDFSNumOut(), 9UL); EXPECT_EQ(DT->getNode(BB1)->getDFSNumIn(), 1UL); EXPECT_EQ(DT->getNode(BB1)->getDFSNumOut(), 4UL); EXPECT_EQ(DT->getNode(BB2)->getDFSNumIn(), 7UL); EXPECT_EQ(DT->getNode(BB2)->getDFSNumOut(), 8UL); EXPECT_EQ(DT->getNode(BB3)->getDFSNumIn(), 2UL); EXPECT_EQ(DT->getNode(BB3)->getDFSNumOut(), 3UL); EXPECT_EQ(DT->getNode(BB4)->getDFSNumIn(), 5UL); EXPECT_EQ(DT->getNode(BB4)->getDFSNumOut(), 6UL); return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<PostDominatorTree>(); } DPass() : FunctionPass(ID) { initializeDPassPass(*PassRegistry::getPassRegistry()); } }; char DPass::ID = 0; std::unique_ptr<Module> makeLLVMModule(DPass *P) { const char *ModuleStrig = "declare i32 @g()\n" \ "define void @f(i32 %x) personality i32 ()* @g {\n" \ "bb0:\n" \ " %y1 = add i32 %x, 1\n" \ " %y2 = add i32 %x, 1\n" \ " %y3 = invoke i32 @g() to label %bb1 unwind label %bb2\n" \ "bb1:\n" \ " %y4 = add i32 %x, 1\n" \ " br label %bb4\n" \ "bb2:\n" \ " %y5 = landingpad i32\n" \ " cleanup\n" \ " br label %bb4\n" \ "bb3:\n" \ " %y6 = add i32 %x, 1\n" \ " %y7 = add i32 %x, 1\n" \ " ret void\n" \ "bb4:\n" \ " %y8 = phi i32 [0, %bb2], [%y4, %bb1]\n" " %y9 = phi i32 [0, %bb2], [%y4, %bb1]\n" " ret void\n" \ "}\n"; LLVMContext &C = getGlobalContext(); SMDiagnostic Err; return parseAssemblyString(ModuleStrig, Err, C); } TEST(DominatorTree, Unreachable) { DPass *P = new DPass(); std::unique_ptr<Module> M = makeLLVMModule(P); legacy::PassManager Passes; Passes.add(P); Passes.run(*M); } } } INITIALIZE_PASS_BEGIN(DPass, "dpass", "dpass", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(PostDominatorTree) INITIALIZE_PASS_END(DPass, "dpass", "dpass", false, false)
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Analysis AsmParser Core IPA Support ) set(IRSources AttributesTest.cpp ConstantRangeTest.cpp ConstantsTest.cpp DebugInfoTest.cpp DominatorTreeTest.cpp IRBuilderTest.cpp InstructionsTest.cpp LegacyPassManagerTest.cpp MDBuilderTest.cpp MetadataTest.cpp PassManagerTest.cpp PatternMatch.cpp TypeBuilderTest.cpp TypesTest.cpp UseTest.cpp UserTest.cpp ValueHandleTest.cpp ValueMapTest.cpp ValueTest.cpp VerifierTest.cpp WaymarkTest.cpp ) # HACK: Declare a couple of source files as optionally compiled to satisfy the # missing-file-checker in LLVM's weird CMake build. set(LLVM_OPTIONAL_SOURCES ValueMapTest.cpp ) add_llvm_unittest(IRTests ${IRSources} )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/UserTest.cpp
//===- llvm/unittest/IR/UserTest.cpp - User unit tests --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/User.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(UserTest, ValueOpIteration) { LLVMContext C; const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" "entry:\n" " switch i32 undef, label %s0\n" " [ i32 1, label %s1\n" " i32 2, label %s2\n" " i32 3, label %s3\n" " i32 4, label %s4\n" " i32 5, label %s5\n" " i32 6, label %s6\n" " i32 7, label %s7\n" " i32 8, label %s8\n" " i32 9, label %s9 ]\n" "\n" "s0:\n" " br label %exit\n" "s1:\n" " br label %exit\n" "s2:\n" " br label %exit\n" "s3:\n" " br label %exit\n" "s4:\n" " br label %exit\n" "s5:\n" " br label %exit\n" "s6:\n" " br label %exit\n" "s7:\n" " br label %exit\n" "s8:\n" " br label %exit\n" "s9:\n" " br label %exit\n" "\n" "exit:\n" " %phi = phi i32 [ 0, %s0 ], [ 1, %s1 ],\n" " [ 2, %s2 ], [ 3, %s3 ],\n" " [ 4, %s4 ], [ 5, %s5 ],\n" " [ 6, %s6 ], [ 7, %s7 ],\n" " [ 8, %s8 ], [ 9, %s9 ]\n" " ret void\n" "}\n"; SMDiagnostic Err; std::unique_ptr<Module> M = parseAssemblyString(ModuleString, Err, C); Function *F = M->getFunction("f"); BasicBlock &ExitBB = F->back(); PHINode &P = cast<PHINode>(ExitBB.front()); EXPECT_TRUE(P.value_op_begin() == P.value_op_begin()); EXPECT_FALSE(P.value_op_begin() == P.value_op_end()); EXPECT_TRUE(P.value_op_begin() != P.value_op_end()); EXPECT_FALSE(P.value_op_end() != P.value_op_end()); EXPECT_TRUE(P.value_op_begin() < P.value_op_end()); EXPECT_FALSE(P.value_op_begin() < P.value_op_begin()); EXPECT_TRUE(P.value_op_end() > P.value_op_begin()); EXPECT_FALSE(P.value_op_begin() > P.value_op_begin()); EXPECT_TRUE(P.value_op_begin() <= P.value_op_begin()); EXPECT_FALSE(P.value_op_end() <= P.value_op_begin()); EXPECT_TRUE(P.value_op_begin() >= P.value_op_begin()); EXPECT_FALSE(P.value_op_begin() >= P.value_op_end()); EXPECT_EQ(10, std::distance(P.value_op_begin(), P.value_op_end())); User::value_op_iterator I = P.value_op_begin(); I += 3; EXPECT_EQ(std::next(P.value_op_begin(), 3), I); EXPECT_EQ(P.getOperand(3), *I); I++; EXPECT_EQ(P.getOperand(6), I[2]); EXPECT_EQ(P.value_op_end(), (I - 2) + 8); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/ValueMapTest.cpp
//===- llvm/unittest/ADT/ValueMapTest.cpp - ValueMap unit tests -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/ValueMap.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture template<typename T> class ValueMapTest : public testing::Test { protected: Constant *ConstantV; std::unique_ptr<BitCastInst> BitcastV; std::unique_ptr<BinaryOperator> AddV; ValueMapTest() : ConstantV(ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0)), BitcastV(new BitCastInst(ConstantV, Type::getInt32Ty(getGlobalContext()))), AddV(BinaryOperator::CreateAdd(ConstantV, ConstantV)) { } }; // Run everything on Value*, a subtype to make sure that casting works as // expected, and a const subtype to make sure we cast const correctly. typedef ::testing::Types<Value, Instruction, const Instruction> KeyTypes; TYPED_TEST_CASE(ValueMapTest, KeyTypes); TYPED_TEST(ValueMapTest, Null) { ValueMap<TypeParam*, int> VM1; VM1[nullptr] = 7; EXPECT_EQ(7, VM1.lookup(nullptr)); } TYPED_TEST(ValueMapTest, FollowsValue) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0u, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->AddV.get())); EXPECT_EQ(0u, VM.count(this->BitcastV.get())); this->AddV.reset(); EXPECT_EQ(0u, VM.count(this->AddV.get())); EXPECT_EQ(0u, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); } TYPED_TEST(ValueMapTest, OperationsWork) { ValueMap<TypeParam*, int> VM; ValueMap<TypeParam*, int> VM2(16); (void)VM2; typename ValueMapConfig<TypeParam*>::ExtraData Data; ValueMap<TypeParam*, int> VM3(Data, 16); (void)VM3; EXPECT_TRUE(VM.empty()); VM[this->BitcastV.get()] = 7; // Find: typename ValueMap<TypeParam*, int>::iterator I = VM.find(this->BitcastV.get()); ASSERT_TRUE(I != VM.end()); EXPECT_EQ(this->BitcastV.get(), I->first); EXPECT_EQ(7, I->second); EXPECT_TRUE(VM.find(this->AddV.get()) == VM.end()); // Const find: const ValueMap<TypeParam*, int> &CVM = VM; typename ValueMap<TypeParam*, int>::const_iterator CI = CVM.find(this->BitcastV.get()); ASSERT_TRUE(CI != CVM.end()); EXPECT_EQ(this->BitcastV.get(), CI->first); EXPECT_EQ(7, CI->second); EXPECT_TRUE(CVM.find(this->AddV.get()) == CVM.end()); // Insert: std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult1 = VM.insert(std::make_pair(this->AddV.get(), 3)); EXPECT_EQ(this->AddV.get(), InsertResult1.first->first); EXPECT_EQ(3, InsertResult1.first->second); EXPECT_TRUE(InsertResult1.second); EXPECT_EQ(1u, VM.count(this->AddV.get())); std::pair<typename ValueMap<TypeParam*, int>::iterator, bool> InsertResult2 = VM.insert(std::make_pair(this->AddV.get(), 5)); EXPECT_EQ(this->AddV.get(), InsertResult2.first->first); EXPECT_EQ(3, InsertResult2.first->second); EXPECT_FALSE(InsertResult2.second); // Erase: VM.erase(InsertResult2.first); EXPECT_EQ(0U, VM.count(this->AddV.get())); EXPECT_EQ(1U, VM.count(this->BitcastV.get())); VM.erase(this->BitcastV.get()); EXPECT_EQ(0U, VM.count(this->BitcastV.get())); EXPECT_EQ(0U, VM.size()); // Range insert: SmallVector<std::pair<Instruction*, int>, 2> Elems; Elems.push_back(std::make_pair(this->AddV.get(), 1)); Elems.push_back(std::make_pair(this->BitcastV.get(), 2)); VM.insert(Elems.begin(), Elems.end()); EXPECT_EQ(1, VM.lookup(this->AddV.get())); EXPECT_EQ(2, VM.lookup(this->BitcastV.get())); } template<typename ExpectedType, typename VarType> void CompileAssertHasType(VarType) { static_assert(std::is_same<ExpectedType, VarType>::value, "Not the same type"); } TYPED_TEST(ValueMapTest, Iteration) { ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 2; VM[this->AddV.get()] = 3; size_t size = 0; for (typename ValueMap<TypeParam*, int>::iterator I = VM.begin(), E = VM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 2) { EXPECT_EQ(this->BitcastV.get(), I->first); I->second = 5; } else if (I->second == 3) { EXPECT_EQ(this->AddV.get(), I->first); I->second = 6; } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); EXPECT_EQ(5, VM[this->BitcastV.get()]); EXPECT_EQ(6, VM[this->AddV.get()]); size = 0; // Cast to const ValueMap to avoid a bug in DenseMap's iterators. const ValueMap<TypeParam*, int>& CVM = VM; for (typename ValueMap<TypeParam*, int>::const_iterator I = CVM.begin(), E = CVM.end(); I != E; ++I) { ++size; std::pair<TypeParam*, int> value = *I; (void)value; CompileAssertHasType<TypeParam*>(I->first); if (I->second == 5) { EXPECT_EQ(this->BitcastV.get(), I->first); } else if (I->second == 6) { EXPECT_EQ(this->AddV.get(), I->first); } else { ADD_FAILURE() << "Iterated through an extra value."; } } EXPECT_EQ(2U, size); } TYPED_TEST(ValueMapTest, DefaultCollisionBehavior) { // By default, we overwrite the old value with the replaced value. ValueMap<TypeParam*, int> VM; VM[this->BitcastV.get()] = 7; VM[this->AddV.get()] = 9; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0u, VM.count(this->BitcastV.get())); EXPECT_EQ(9, VM.lookup(this->AddV.get())); } TYPED_TEST(ValueMapTest, ConfiguredCollisionBehavior) { // TODO: Implement this when someone needs it. } template<typename KeyT, typename MutexT> struct LockMutex : ValueMapConfig<KeyT, MutexT> { struct ExtraData { MutexT *M; bool *CalledRAUW; bool *CalledDeleted; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { *Data.CalledRAUW = true; EXPECT_FALSE(Data.M->try_lock()) << "Mutex should already be locked."; } static void onDelete(const ExtraData &Data, KeyT Old) { *Data.CalledDeleted = true; EXPECT_FALSE(Data.M->try_lock()) << "Mutex should already be locked."; } static MutexT *getMutex(const ExtraData &Data) { return Data.M; } }; // FIXME: These tests started failing on Windows. #if LLVM_ENABLE_THREADS && !defined(LLVM_ON_WIN32) TYPED_TEST(ValueMapTest, LocksMutex) { sys::Mutex M(false); // Not recursive. bool CalledRAUW = false, CalledDeleted = false; typedef LockMutex<TypeParam*, sys::Mutex> ConfigType; typename ConfigType::ExtraData Data = {&M, &CalledRAUW, &CalledDeleted}; ValueMap<TypeParam*, int, ConfigType> VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); this->AddV.reset(); EXPECT_TRUE(CalledRAUW); EXPECT_TRUE(CalledDeleted); } #endif template<typename KeyT> struct NoFollow : ValueMapConfig<KeyT> { enum { FollowRAUW = false }; }; TYPED_TEST(ValueMapTest, NoFollowRAUW) { ValueMap<TypeParam*, int, NoFollow<TypeParam*> > VM; VM[this->BitcastV.get()] = 7; EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0u, VM.count(this->AddV.get())); this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->AddV.reset(); EXPECT_EQ(7, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); this->BitcastV.reset(); EXPECT_EQ(0, VM.lookup(this->BitcastV.get())); EXPECT_EQ(0, VM.lookup(this->AddV.get())); EXPECT_EQ(0U, VM.size()); } template<typename KeyT> struct CountOps : ValueMapConfig<KeyT> { struct ExtraData { int *Deletions; int *RAUWs; }; static void onRAUW(const ExtraData &Data, KeyT Old, KeyT New) { ++*Data.RAUWs; } static void onDelete(const ExtraData &Data, KeyT Old) { ++*Data.Deletions; } }; TYPED_TEST(ValueMapTest, CallsConfig) { int Deletions = 0, RAUWs = 0; typename CountOps<TypeParam*>::ExtraData Data = {&Deletions, &RAUWs}; ValueMap<TypeParam*, int, CountOps<TypeParam*> > VM(Data); VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0, Deletions); EXPECT_EQ(1, RAUWs); this->AddV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); this->BitcastV.reset(); EXPECT_EQ(1, Deletions); EXPECT_EQ(1, RAUWs); } template<typename KeyT> struct ModifyingConfig : ValueMapConfig<KeyT> { // We'll put a pointer here back to the ValueMap this key is in, so // that we can modify it (and clobber *this) before the ValueMap // tries to do the same modification. In previous versions of // ValueMap, that exploded. typedef ValueMap<KeyT, int, ModifyingConfig<KeyT> > **ExtraData; static void onRAUW(ExtraData Map, KeyT Old, KeyT New) { (*Map)->erase(Old); } static void onDelete(ExtraData Map, KeyT Old) { (*Map)->erase(Old); } }; TYPED_TEST(ValueMapTest, SurvivesModificationByConfig) { ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > *MapAddress; ValueMap<TypeParam*, int, ModifyingConfig<TypeParam*> > VM(&MapAddress); MapAddress = &VM; // Now the ModifyingConfig can modify the Map inside a callback. VM[this->BitcastV.get()] = 7; this->BitcastV->replaceAllUsesWith(this->AddV.get()); EXPECT_EQ(0u, VM.count(this->BitcastV.get())); EXPECT_EQ(0u, VM.count(this->AddV.get())); VM[this->AddV.get()] = 7; this->AddV.reset(); EXPECT_EQ(0u, VM.count(this->AddV.get())); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/ValueTest.cpp
//===- llvm/unittest/IR/ValueTest.cpp - Value unit tests ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Function.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/ModuleSlotTracker.h" #include "llvm/IR/Value.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(ValueTest, UsedInBasicBlock) { LLVMContext C; const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" "bb0:\n" " %y1 = add i32 %y, 1\n" " %y2 = add i32 %y, 1\n" " %y3 = add i32 %y, 1\n" " %y4 = add i32 %y, 1\n" " %y5 = add i32 %y, 1\n" " %y6 = add i32 %y, 1\n" " %y7 = add i32 %y, 1\n" " %y8 = add i32 %x, 1\n" " ret void\n" "}\n"; SMDiagnostic Err; std::unique_ptr<Module> M = parseAssemblyString(ModuleString, Err, C); Function *F = M->getFunction("f"); EXPECT_FALSE(F->isUsedInBasicBlock(F->begin())); EXPECT_TRUE((++F->arg_begin())->isUsedInBasicBlock(F->begin())); EXPECT_TRUE(F->arg_begin()->isUsedInBasicBlock(F->begin())); } TEST(GlobalTest, CreateAddressSpace) { LLVMContext &Ctx = getGlobalContext(); std::unique_ptr<Module> M(new Module("TestModule", Ctx)); Type *Int8Ty = Type::getInt8Ty(Ctx); Type *Int32Ty = Type::getInt32Ty(Ctx); GlobalVariable *Dummy0 = new GlobalVariable(*M, Int32Ty, true, GlobalValue::ExternalLinkage, Constant::getAllOnesValue(Int32Ty), "dummy", nullptr, GlobalVariable::NotThreadLocal, 1); EXPECT_TRUE(Value::MaximumAlignment == 536870912U); Dummy0->setAlignment(536870912U); EXPECT_EQ(Dummy0->getAlignment(), 536870912U); // Make sure the address space isn't dropped when returning this. Constant *Dummy1 = M->getOrInsertGlobal("dummy", Int32Ty); EXPECT_EQ(Dummy0, Dummy1); EXPECT_EQ(1u, Dummy1->getType()->getPointerAddressSpace()); // This one requires a bitcast, but the address space must also stay the same. GlobalVariable *DummyCast0 = new GlobalVariable(*M, Int32Ty, true, GlobalValue::ExternalLinkage, Constant::getAllOnesValue(Int32Ty), "dummy_cast", nullptr, GlobalVariable::NotThreadLocal, 1); // Make sure the address space isn't dropped when returning this. Constant *DummyCast1 = M->getOrInsertGlobal("dummy_cast", Int8Ty); EXPECT_EQ(1u, DummyCast1->getType()->getPointerAddressSpace()); EXPECT_NE(DummyCast0, DummyCast1) << *DummyCast1; } #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG TEST(GlobalTest, AlignDeath) { LLVMContext &Ctx = getGlobalContext(); std::unique_ptr<Module> M(new Module("TestModule", Ctx)); Type *Int32Ty = Type::getInt32Ty(Ctx); GlobalVariable *Var = new GlobalVariable(*M, Int32Ty, true, GlobalValue::ExternalLinkage, Constant::getAllOnesValue(Int32Ty), "var", nullptr, GlobalVariable::NotThreadLocal, 1); EXPECT_DEATH(Var->setAlignment(536870913U), "Alignment is not a power of 2"); EXPECT_DEATH(Var->setAlignment(1073741824U), "Alignment is greater than MaximumAlignment"); } #endif #endif TEST(ValueTest, printSlots) { // Check that Value::print() and Value::printAsOperand() work with and // without a slot tracker. LLVMContext C; const char *ModuleString = "define void @f(i32 %x, i32 %y) {\n" "entry:\n" " %0 = add i32 %y, 1\n" " %1 = add i32 %y, 1\n" " ret void\n" "}\n"; SMDiagnostic Err; std::unique_ptr<Module> M = parseAssemblyString(ModuleString, Err, C); Function *F = M->getFunction("f"); ASSERT_TRUE(F); ASSERT_FALSE(F->empty()); BasicBlock &BB = F->getEntryBlock(); ASSERT_EQ(3u, BB.size()); Instruction *I0 = BB.begin(); ASSERT_TRUE(I0); Instruction *I1 = ++BB.begin(); ASSERT_TRUE(I1); ModuleSlotTracker MST(M.get()); #define CHECK_PRINT(INST, STR) \ do { \ { \ std::string S; \ raw_string_ostream OS(S); \ INST->print(OS); \ EXPECT_EQ(STR, OS.str()); \ } \ { \ std::string S; \ raw_string_ostream OS(S); \ INST->print(OS, MST); \ EXPECT_EQ(STR, OS.str()); \ } \ } while (false) CHECK_PRINT(I0, " %0 = add i32 %y, 1"); CHECK_PRINT(I1, " %1 = add i32 %y, 1"); #undef CHECK_PRINT #define CHECK_PRINT_AS_OPERAND(INST, TYPE, STR) \ do { \ { \ std::string S; \ raw_string_ostream OS(S); \ INST->printAsOperand(OS, TYPE); \ EXPECT_EQ(StringRef(STR), StringRef(OS.str())); \ } \ { \ std::string S; \ raw_string_ostream OS(S); \ INST->printAsOperand(OS, TYPE, MST); \ EXPECT_EQ(StringRef(STR), StringRef(OS.str())); \ } \ } while (false) CHECK_PRINT_AS_OPERAND(I0, false, "%0"); CHECK_PRINT_AS_OPERAND(I1, false, "%1"); CHECK_PRINT_AS_OPERAND(I0, true, "i32 %0"); CHECK_PRINT_AS_OPERAND(I1, true, "i32 %1"); #undef CHECK_PRINT_AS_OPERAND } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/MDBuilderTest.cpp
//===- llvm/unittests/MDBuilderTest.cpp - MDBuilder unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/MDBuilder.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Operator.h" #include "gtest/gtest.h" using namespace llvm; namespace { class MDBuilderTest : public testing::Test { protected: LLVMContext Context; }; TEST_F(MDBuilderTest, createString) { MDBuilder MDHelper(Context); MDString *Str0 = MDHelper.createString(""); MDString *Str1 = MDHelper.createString("string"); EXPECT_EQ(Str0->getString(), StringRef("")); EXPECT_EQ(Str1->getString(), StringRef("string")); } TEST_F(MDBuilderTest, createFPMath) { MDBuilder MDHelper(Context); MDNode *MD0 = MDHelper.createFPMath(0.0); MDNode *MD1 = MDHelper.createFPMath(1.0); EXPECT_EQ(MD0, (MDNode *)nullptr); EXPECT_NE(MD1, (MDNode *)nullptr); EXPECT_EQ(MD1->getNumOperands(), 1U); Metadata *Op = MD1->getOperand(0); EXPECT_TRUE(mdconst::hasa<ConstantFP>(Op)); ConstantFP *Val = mdconst::extract<ConstantFP>(Op); EXPECT_TRUE(Val->getType()->isFloatingPointTy()); EXPECT_TRUE(Val->isExactlyValue(1.0)); } TEST_F(MDBuilderTest, createRangeMetadata) { MDBuilder MDHelper(Context); APInt A(8, 1), B(8, 2); MDNode *R0 = MDHelper.createRange(A, A); MDNode *R1 = MDHelper.createRange(A, B); EXPECT_EQ(R0, (MDNode *)nullptr); EXPECT_NE(R1, (MDNode *)nullptr); EXPECT_EQ(R1->getNumOperands(), 2U); EXPECT_TRUE(mdconst::hasa<ConstantInt>(R1->getOperand(0))); EXPECT_TRUE(mdconst::hasa<ConstantInt>(R1->getOperand(1))); ConstantInt *C0 = mdconst::extract<ConstantInt>(R1->getOperand(0)); ConstantInt *C1 = mdconst::extract<ConstantInt>(R1->getOperand(1)); EXPECT_EQ(C0->getValue(), A); EXPECT_EQ(C1->getValue(), B); } TEST_F(MDBuilderTest, createAnonymousTBAARoot) { MDBuilder MDHelper(Context); MDNode *R0 = MDHelper.createAnonymousTBAARoot(); MDNode *R1 = MDHelper.createAnonymousTBAARoot(); EXPECT_NE(R0, R1); EXPECT_GE(R0->getNumOperands(), 1U); EXPECT_GE(R1->getNumOperands(), 1U); EXPECT_EQ(R0->getOperand(0), R0); EXPECT_EQ(R1->getOperand(0), R1); EXPECT_TRUE(R0->getNumOperands() == 1 || R0->getOperand(1) == nullptr); EXPECT_TRUE(R1->getNumOperands() == 1 || R1->getOperand(1) == nullptr); } TEST_F(MDBuilderTest, createTBAARoot) { MDBuilder MDHelper(Context); MDNode *R0 = MDHelper.createTBAARoot("Root"); MDNode *R1 = MDHelper.createTBAARoot("Root"); EXPECT_EQ(R0, R1); EXPECT_GE(R0->getNumOperands(), 1U); EXPECT_TRUE(isa<MDString>(R0->getOperand(0))); EXPECT_EQ(cast<MDString>(R0->getOperand(0))->getString(), "Root"); EXPECT_TRUE(R0->getNumOperands() == 1 || R0->getOperand(1) == nullptr); } TEST_F(MDBuilderTest, createTBAANode) { MDBuilder MDHelper(Context); MDNode *R = MDHelper.createTBAARoot("Root"); MDNode *N0 = MDHelper.createTBAANode("Node", R); MDNode *N1 = MDHelper.createTBAANode("edoN", R); MDNode *N2 = MDHelper.createTBAANode("Node", R, true); MDNode *N3 = MDHelper.createTBAANode("Node", R); EXPECT_EQ(N0, N3); EXPECT_NE(N0, N1); EXPECT_NE(N0, N2); EXPECT_GE(N0->getNumOperands(), 2U); EXPECT_GE(N1->getNumOperands(), 2U); EXPECT_GE(N2->getNumOperands(), 3U); EXPECT_TRUE(isa<MDString>(N0->getOperand(0))); EXPECT_TRUE(isa<MDString>(N1->getOperand(0))); EXPECT_TRUE(isa<MDString>(N2->getOperand(0))); EXPECT_EQ(cast<MDString>(N0->getOperand(0))->getString(), "Node"); EXPECT_EQ(cast<MDString>(N1->getOperand(0))->getString(), "edoN"); EXPECT_EQ(cast<MDString>(N2->getOperand(0))->getString(), "Node"); EXPECT_EQ(N0->getOperand(1), R); EXPECT_EQ(N1->getOperand(1), R); EXPECT_EQ(N2->getOperand(1), R); EXPECT_TRUE(mdconst::hasa<ConstantInt>(N2->getOperand(2))); EXPECT_EQ(mdconst::extract<ConstantInt>(N2->getOperand(2))->getZExtValue(), 1U); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/WaymarkTest.cpp
//===- llvm/unittest/IR/WaymarkTest.cpp - getUser() unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" #include <algorithm> namespace llvm { namespace { Constant *char2constant(char c) { return ConstantInt::get(Type::getInt8Ty(getGlobalContext()), c); } TEST(WaymarkTest, NativeArray) { static uint8_t tail[22] = "s02s33s30y2y0s1x0syxS"; Value * values[22]; std::transform(tail, tail + 22, values, char2constant); FunctionType *FT = FunctionType::get(Type::getVoidTy(getGlobalContext()), true); std::unique_ptr<Function> F( Function::Create(FT, GlobalValue::ExternalLinkage)); const CallInst *A = CallInst::Create(F.get(), makeArrayRef(values)); ASSERT_NE(A, (const CallInst*)nullptr); ASSERT_EQ(1U + 22, A->getNumOperands()); const Use *U = &A->getOperandUse(0); const Use *Ue = &A->getOperandUse(22); for (; U != Ue; ++U) { EXPECT_EQ(A, U->getUser()); } delete A; } TEST(WaymarkTest, TwoBit) { Use* many = (Use*)calloc(sizeof(Use), 8212 + 1); ASSERT_TRUE(many); Use::initTags(many, many + 8212); for (Use *U = many, *Ue = many + 8212 - 1; U != Ue; ++U) { EXPECT_EQ(reinterpret_cast<User *>(Ue + 1), U->getUser()); } free(many); } } // end anonymous namespace } // end namespace llvm
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/LegacyPassManagerTest.cpp
//===- llvm/unittest/IR/LegacyPassManager.cpp - Legacy PassManager tests --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This unit test exercises the legacy pass manager infrastructure. We use the // old names as well to ensure that the source-level compatibility is preserved // where possible. // //===----------------------------------------------------------------------===// #include "llvm/IR/LegacyPassManager.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/CallGraphSCCPass.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Pass.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace llvm { void initializeModuleNDMPass(PassRegistry&); void initializeFPassPass(PassRegistry&); void initializeCGPassPass(PassRegistry&); void initializeLPassPass(PassRegistry&); void initializeBPassPass(PassRegistry&); namespace { // ND = no deps // NM = no modifications struct ModuleNDNM: public ModulePass { public: static char run; static char ID; ModuleNDNM() : ModulePass(ID) { } bool runOnModule(Module &M) override { run++; return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } }; char ModuleNDNM::ID=0; char ModuleNDNM::run=0; struct ModuleNDM : public ModulePass { public: static char run; static char ID; ModuleNDM() : ModulePass(ID) {} bool runOnModule(Module &M) override { run++; return true; } }; char ModuleNDM::ID=0; char ModuleNDM::run=0; struct ModuleNDM2 : public ModulePass { public: static char run; static char ID; ModuleNDM2() : ModulePass(ID) {} bool runOnModule(Module &M) override { run++; return true; } }; char ModuleNDM2::ID=0; char ModuleNDM2::run=0; struct ModuleDNM : public ModulePass { public: static char run; static char ID; ModuleDNM() : ModulePass(ID) { initializeModuleNDMPass(*PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override { run++; return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<ModuleNDM>(); AU.setPreservesAll(); } }; char ModuleDNM::ID=0; char ModuleDNM::run=0; template<typename P> struct PassTestBase : public P { protected: static int runc; static bool initialized; static bool finalized; int allocated; void run() { EXPECT_TRUE(initialized); EXPECT_FALSE(finalized); EXPECT_EQ(0, allocated); allocated++; runc++; } public: static char ID; static void finishedOK(int run) { EXPECT_GT(runc, 0); EXPECT_TRUE(initialized); EXPECT_TRUE(finalized); EXPECT_EQ(run, runc); } PassTestBase() : P(ID), allocated(0) { initialized = false; finalized = false; runc = 0; } void releaseMemory() override { EXPECT_GT(runc, 0); EXPECT_GT(allocated, 0); allocated--; } }; template<typename P> char PassTestBase<P>::ID; template<typename P> int PassTestBase<P>::runc; template<typename P> bool PassTestBase<P>::initialized; template<typename P> bool PassTestBase<P>::finalized; template<typename T, typename P> struct PassTest : public PassTestBase<P> { public: #ifndef _MSC_VER // MSVC complains that Pass is not base class. using llvm::Pass::doInitialization; using llvm::Pass::doFinalization; #endif bool doInitialization(T &t) override { EXPECT_FALSE(PassTestBase<P>::initialized); PassTestBase<P>::initialized = true; return false; } bool doFinalization(T &t) override { EXPECT_FALSE(PassTestBase<P>::finalized); PassTestBase<P>::finalized = true; EXPECT_EQ(0, PassTestBase<P>::allocated); return false; } }; struct CGPass : public PassTest<CallGraph, CallGraphSCCPass> { public: CGPass() { initializeCGPassPass(*PassRegistry::getPassRegistry()); } bool runOnSCC(CallGraphSCC &SCMM) override { run(); return false; } }; struct FPass : public PassTest<Module, FunctionPass> { public: bool runOnFunction(Function &F) override { // FIXME: PR4112 // EXPECT_TRUE(getAnalysisIfAvailable<DataLayout>()); run(); return false; } }; struct LPass : public PassTestBase<LoopPass> { private: static int initcount; static int fincount; public: LPass() { initializeLPassPass(*PassRegistry::getPassRegistry()); initcount = 0; fincount=0; EXPECT_FALSE(initialized); } static void finishedOK(int run, int finalized) { PassTestBase<LoopPass>::finishedOK(run); EXPECT_EQ(run, initcount); EXPECT_EQ(finalized, fincount); } using llvm::Pass::doInitialization; using llvm::Pass::doFinalization; bool doInitialization(Loop* L, LPPassManager &LPM) override { initialized = true; initcount++; return false; } bool runOnLoop(Loop *L, LPPassManager &LPM) override { run(); return false; } bool doFinalization() override { fincount++; finalized = true; return false; } }; int LPass::initcount=0; int LPass::fincount=0; struct BPass : public PassTestBase<BasicBlockPass> { private: static int inited; static int fin; public: static void finishedOK(int run, int N) { PassTestBase<BasicBlockPass>::finishedOK(run); EXPECT_EQ(inited, N); EXPECT_EQ(fin, N); } BPass() { inited = 0; fin = 0; } bool doInitialization(Module &M) override { EXPECT_FALSE(initialized); initialized = true; return false; } bool doInitialization(Function &F) override { inited++; return false; } bool runOnBasicBlock(BasicBlock &BB) override { run(); return false; } bool doFinalization(Function &F) override { fin++; return false; } bool doFinalization(Module &M) override { EXPECT_FALSE(finalized); finalized = true; EXPECT_EQ(0, allocated); return false; } }; int BPass::inited=0; int BPass::fin=0; struct OnTheFlyTest: public ModulePass { public: static char ID; OnTheFlyTest() : ModulePass(ID) { initializeFPassPass(*PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override { for (Module::iterator I=M.begin(),E=M.end(); I != E; ++I) { Function &F = *I; { SCOPED_TRACE("Running on the fly function pass"); getAnalysis<FPass>(F); } } return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<FPass>(); } }; char OnTheFlyTest::ID=0; TEST(PassManager, RunOnce) { Module M("test-once", getGlobalContext()); struct ModuleNDNM *mNDNM = new ModuleNDNM(); struct ModuleDNM *mDNM = new ModuleDNM(); struct ModuleNDM *mNDM = new ModuleNDM(); struct ModuleNDM2 *mNDM2 = new ModuleNDM2(); mNDM->run = mNDNM->run = mDNM->run = mNDM2->run = 0; legacy::PassManager Passes; Passes.add(mNDM2); Passes.add(mNDM); Passes.add(mNDNM); Passes.add(mDNM); Passes.run(M); // each pass must be run exactly once, since nothing invalidates them EXPECT_EQ(1, mNDM->run); EXPECT_EQ(1, mNDNM->run); EXPECT_EQ(1, mDNM->run); EXPECT_EQ(1, mNDM2->run); } TEST(PassManager, ReRun) { Module M("test-rerun", getGlobalContext()); struct ModuleNDNM *mNDNM = new ModuleNDNM(); struct ModuleDNM *mDNM = new ModuleDNM(); struct ModuleNDM *mNDM = new ModuleNDM(); struct ModuleNDM2 *mNDM2 = new ModuleNDM2(); mNDM->run = mNDNM->run = mDNM->run = mNDM2->run = 0; legacy::PassManager Passes; Passes.add(mNDM); Passes.add(mNDNM); Passes.add(mNDM2);// invalidates mNDM needed by mDNM Passes.add(mDNM); Passes.run(M); // Some passes must be rerun because a pass that modified the // module/function was run in between EXPECT_EQ(2, mNDM->run); EXPECT_EQ(1, mNDNM->run); EXPECT_EQ(1, mNDM2->run); EXPECT_EQ(1, mDNM->run); } Module* makeLLVMModule(); template<typename T> void MemoryTestHelper(int run) { std::unique_ptr<Module> M(makeLLVMModule()); T *P = new T(); legacy::PassManager Passes; Passes.add(P); Passes.run(*M); T::finishedOK(run); } template<typename T> void MemoryTestHelper(int run, int N) { Module *M = makeLLVMModule(); T *P = new T(); legacy::PassManager Passes; Passes.add(P); Passes.run(*M); T::finishedOK(run, N); delete M; } TEST(PassManager, Memory) { // SCC#1: test1->test2->test3->test1 // SCC#2: test4 // SCC#3: indirect call node { SCOPED_TRACE("Callgraph pass"); MemoryTestHelper<CGPass>(3); } { SCOPED_TRACE("Function pass"); MemoryTestHelper<FPass>(4);// 4 functions } { SCOPED_TRACE("Loop pass"); MemoryTestHelper<LPass>(2, 1); //2 loops, 1 function } { SCOPED_TRACE("Basic block pass"); MemoryTestHelper<BPass>(7, 4); //9 basic blocks } } TEST(PassManager, MemoryOnTheFly) { Module *M = makeLLVMModule(); { SCOPED_TRACE("Running OnTheFlyTest"); struct OnTheFlyTest *O = new OnTheFlyTest(); legacy::PassManager Passes; Passes.add(O); Passes.run(*M); FPass::finishedOK(4); } delete M; } Module* makeLLVMModule() { // Module Construction Module* mod = new Module("test-mem", getGlobalContext()); mod->setDataLayout("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-" "a:0:64-s:64:64-f80:128:128"); mod->setTargetTriple("x86_64-unknown-linux-gnu"); // Type Definitions std::vector<Type*>FuncTy_0_args; FunctionType* FuncTy_0 = FunctionType::get( /*Result=*/IntegerType::get(getGlobalContext(), 32), /*Params=*/FuncTy_0_args, /*isVarArg=*/false); std::vector<Type*>FuncTy_2_args; FuncTy_2_args.push_back(IntegerType::get(getGlobalContext(), 1)); FunctionType* FuncTy_2 = FunctionType::get( /*Result=*/Type::getVoidTy(getGlobalContext()), /*Params=*/FuncTy_2_args, /*isVarArg=*/false); // Function Declarations Function* func_test1 = Function::Create( /*Type=*/FuncTy_0, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test1", mod); func_test1->setCallingConv(CallingConv::C); AttributeSet func_test1_PAL; func_test1->setAttributes(func_test1_PAL); Function* func_test2 = Function::Create( /*Type=*/FuncTy_0, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test2", mod); func_test2->setCallingConv(CallingConv::C); AttributeSet func_test2_PAL; func_test2->setAttributes(func_test2_PAL); Function* func_test3 = Function::Create( /*Type=*/FuncTy_0, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test3", mod); func_test3->setCallingConv(CallingConv::C); AttributeSet func_test3_PAL; func_test3->setAttributes(func_test3_PAL); Function* func_test4 = Function::Create( /*Type=*/FuncTy_2, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test4", mod); func_test4->setCallingConv(CallingConv::C); AttributeSet func_test4_PAL; func_test4->setAttributes(func_test4_PAL); // Global Variable Declarations // Constant Definitions // Global Variable Definitions // Function Definitions // Function: test1 (func_test1) { BasicBlock* label_entry = BasicBlock::Create(getGlobalContext(), "entry",func_test1,nullptr); // Block entry (label_entry) CallInst* int32_3 = CallInst::Create(func_test2, "", label_entry); int32_3->setCallingConv(CallingConv::C); int32_3->setTailCall(false);AttributeSet int32_3_PAL; int32_3->setAttributes(int32_3_PAL); ReturnInst::Create(getGlobalContext(), int32_3, label_entry); } // Function: test2 (func_test2) { BasicBlock* label_entry_5 = BasicBlock::Create(getGlobalContext(), "entry",func_test2,nullptr); // Block entry (label_entry_5) CallInst* int32_6 = CallInst::Create(func_test3, "", label_entry_5); int32_6->setCallingConv(CallingConv::C); int32_6->setTailCall(false);AttributeSet int32_6_PAL; int32_6->setAttributes(int32_6_PAL); ReturnInst::Create(getGlobalContext(), int32_6, label_entry_5); } // Function: test3 (func_test3) { BasicBlock* label_entry_8 = BasicBlock::Create(getGlobalContext(), "entry",func_test3,nullptr); // Block entry (label_entry_8) CallInst* int32_9 = CallInst::Create(func_test1, "", label_entry_8); int32_9->setCallingConv(CallingConv::C); int32_9->setTailCall(false);AttributeSet int32_9_PAL; int32_9->setAttributes(int32_9_PAL); ReturnInst::Create(getGlobalContext(), int32_9, label_entry_8); } // Function: test4 (func_test4) { Function::arg_iterator args = func_test4->arg_begin(); Value* int1_f = args++; int1_f->setName("f"); BasicBlock* label_entry_11 = BasicBlock::Create(getGlobalContext(), "entry",func_test4,nullptr); BasicBlock* label_bb = BasicBlock::Create(getGlobalContext(), "bb",func_test4,nullptr); BasicBlock* label_bb1 = BasicBlock::Create(getGlobalContext(), "bb1",func_test4,nullptr); BasicBlock* label_return = BasicBlock::Create(getGlobalContext(), "return",func_test4,nullptr); // Block entry (label_entry_11) BranchInst::Create(label_bb, label_entry_11); // Block bb (label_bb) BranchInst::Create(label_bb, label_bb1, int1_f, label_bb); // Block bb1 (label_bb1) BranchInst::Create(label_bb1, label_return, int1_f, label_bb1); // Block return (label_return) ReturnInst::Create(getGlobalContext(), label_return); } return mod; } } } INITIALIZE_PASS(ModuleNDM, "mndm", "mndm", false, false) INITIALIZE_PASS_BEGIN(CGPass, "cgp","cgp", false, false) INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) INITIALIZE_PASS_END(CGPass, "cgp","cgp", false, false) INITIALIZE_PASS(FPass, "fp","fp", false, false) INITIALIZE_PASS_BEGIN(LPass, "lp","lp", false, false) INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) INITIALIZE_PASS_END(LPass, "lp","lp", false, false) INITIALIZE_PASS(BPass, "bp","bp", false, false)
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/AttributesTest.cpp
//===- llvm/unittest/IR/AttributesTest.cpp - Attributes unit tests --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/Attributes.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(Attributes, Uniquing) { LLVMContext C; Attribute AttrA = Attribute::get(C, Attribute::AlwaysInline); Attribute AttrB = Attribute::get(C, Attribute::AlwaysInline); EXPECT_EQ(AttrA, AttrB); AttributeSet ASs[] = { AttributeSet::get(C, 1, Attribute::ZExt), AttributeSet::get(C, 2, Attribute::SExt) }; AttributeSet SetA = AttributeSet::get(C, ASs); AttributeSet SetB = AttributeSet::get(C, ASs); EXPECT_EQ(SetA, SetB); } TEST(Attributes, Ordering) { LLVMContext C; AttributeSet ASs[] = { AttributeSet::get(C, 2, Attribute::ZExt), AttributeSet::get(C, 1, Attribute::SExt) }; AttributeSet SetA = AttributeSet::get(C, ASs); AttributeSet SetB = SetA.removeAttributes(C, 1, ASs[1]); EXPECT_NE(SetA, SetB); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/TypeBuilderTest.cpp
//===- llvm/unittest/TypeBuilderTest.cpp - TypeBuilder tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/TypeBuilder.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(TypeBuilderTest, Void) { EXPECT_EQ(Type::getVoidTy(getGlobalContext()), (TypeBuilder<void, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getVoidTy(getGlobalContext()), (TypeBuilder<void, false>::get(getGlobalContext()))); // Special cases for C compatibility: EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()), (TypeBuilder<void*, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()), (TypeBuilder<const void*, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()), (TypeBuilder<volatile void*, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()), (TypeBuilder<const volatile void*, false>::get( getGlobalContext()))); } TEST(TypeBuilderTest, HostIntegers) { EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<int8_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<uint8_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt16Ty(getGlobalContext()), (TypeBuilder<int16_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt16Ty(getGlobalContext()), (TypeBuilder<uint16_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (TypeBuilder<int32_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt32Ty(getGlobalContext()), (TypeBuilder<uint32_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt64Ty(getGlobalContext()), (TypeBuilder<int64_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt64Ty(getGlobalContext()), (TypeBuilder<uint64_t, false>::get(getGlobalContext()))); EXPECT_EQ(IntegerType::get(getGlobalContext(), sizeof(size_t) * CHAR_BIT), (TypeBuilder<size_t, false>::get(getGlobalContext()))); EXPECT_EQ(IntegerType::get(getGlobalContext(), sizeof(ptrdiff_t) * CHAR_BIT), (TypeBuilder<ptrdiff_t, false>::get(getGlobalContext()))); } TEST(TypeBuilderTest, CrossCompilableIntegers) { EXPECT_EQ(IntegerType::get(getGlobalContext(), 1), (TypeBuilder<types::i<1>, true>::get(getGlobalContext()))); EXPECT_EQ(IntegerType::get(getGlobalContext(), 1), (TypeBuilder<types::i<1>, false>::get(getGlobalContext()))); EXPECT_EQ(IntegerType::get(getGlobalContext(), 72), (TypeBuilder<types::i<72>, true>::get(getGlobalContext()))); EXPECT_EQ(IntegerType::get(getGlobalContext(), 72), (TypeBuilder<types::i<72>, false>::get(getGlobalContext()))); } TEST(TypeBuilderTest, Float) { EXPECT_EQ(Type::getFloatTy(getGlobalContext()), (TypeBuilder<float, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getDoubleTy(getGlobalContext()), (TypeBuilder<double, false>::get(getGlobalContext()))); // long double isn't supported yet. EXPECT_EQ(Type::getFloatTy(getGlobalContext()), (TypeBuilder<types::ieee_float, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getFloatTy(getGlobalContext()), (TypeBuilder<types::ieee_float, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getDoubleTy(getGlobalContext()), (TypeBuilder<types::ieee_double, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getDoubleTy(getGlobalContext()), (TypeBuilder<types::ieee_double, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getX86_FP80Ty(getGlobalContext()), (TypeBuilder<types::x86_fp80, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getX86_FP80Ty(getGlobalContext()), (TypeBuilder<types::x86_fp80, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getFP128Ty(getGlobalContext()), (TypeBuilder<types::fp128, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getFP128Ty(getGlobalContext()), (TypeBuilder<types::fp128, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getPPC_FP128Ty(getGlobalContext()), (TypeBuilder<types::ppc_fp128, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getPPC_FP128Ty(getGlobalContext()), (TypeBuilder<types::ppc_fp128, false>::get(getGlobalContext()))); } TEST(TypeBuilderTest, Derived) { EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(getGlobalContext())), (TypeBuilder<int8_t**, false>::get(getGlobalContext()))); EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 7), (TypeBuilder<int8_t[7], false>::get(getGlobalContext()))); EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 0), (TypeBuilder<int8_t[], false>::get(getGlobalContext()))); EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(getGlobalContext())), (TypeBuilder<types::i<8>**, false>::get(getGlobalContext()))); EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 7), (TypeBuilder<types::i<8>[7], false>::get(getGlobalContext()))); EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 0), (TypeBuilder<types::i<8>[], false>::get(getGlobalContext()))); EXPECT_EQ(PointerType::getUnqual(Type::getInt8PtrTy(getGlobalContext())), (TypeBuilder<types::i<8>**, true>::get(getGlobalContext()))); EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 7), (TypeBuilder<types::i<8>[7], true>::get(getGlobalContext()))); EXPECT_EQ(ArrayType::get(Type::getInt8Ty(getGlobalContext()), 0), (TypeBuilder<types::i<8>[], true>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<const int8_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<volatile int8_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<const volatile int8_t, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<const types::i<8>, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<volatile types::i<8>, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<const volatile types::i<8>, false>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<const types::i<8>, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<volatile types::i<8>, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8Ty(getGlobalContext()), (TypeBuilder<const volatile types::i<8>, true>::get(getGlobalContext()))); EXPECT_EQ(Type::getInt8PtrTy(getGlobalContext()), (TypeBuilder<const volatile int8_t*const volatile, false>::get(getGlobalContext()))); } TEST(TypeBuilderTest, Functions) { std::vector<Type*> params; EXPECT_EQ(FunctionType::get(Type::getVoidTy(getGlobalContext()), params, false), (TypeBuilder<void(), true>::get(getGlobalContext()))); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true), (TypeBuilder<int8_t(...), false>::get(getGlobalContext()))); params.push_back(TypeBuilder<int32_t*, false>::get(getGlobalContext())); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false), (TypeBuilder<int8_t(const int32_t*), false>::get(getGlobalContext()))); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true), (TypeBuilder<int8_t(const int32_t*, ...), false>::get(getGlobalContext()))); params.push_back(TypeBuilder<char*, false>::get(getGlobalContext())); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false), (TypeBuilder<int8_t(int32_t*, void*), false>::get(getGlobalContext()))); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true), (TypeBuilder<int8_t(int32_t*, char*, ...), false>::get(getGlobalContext()))); params.push_back(TypeBuilder<char, false>::get(getGlobalContext())); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false), (TypeBuilder<int8_t(int32_t*, void*, char), false>::get(getGlobalContext()))); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true), (TypeBuilder<int8_t(int32_t*, char*, char, ...), false>::get(getGlobalContext()))); params.push_back(TypeBuilder<char, false>::get(getGlobalContext())); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false), (TypeBuilder<int8_t(int32_t*, void*, char, char), false>::get(getGlobalContext()))); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true), (TypeBuilder<int8_t(int32_t*, char*, char, char, ...), false>::get(getGlobalContext()))); params.push_back(TypeBuilder<char, false>::get(getGlobalContext())); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, false), (TypeBuilder<int8_t(int32_t*, void*, char, char, char), false>::get(getGlobalContext()))); EXPECT_EQ(FunctionType::get(Type::getInt8Ty(getGlobalContext()), params, true), (TypeBuilder<int8_t(int32_t*, char*, char, char, char, ...), false>::get(getGlobalContext()))); } TEST(TypeBuilderTest, Context) { // We used to cache TypeBuilder results in static local variables. This // produced the same type for different contexts, which of course broke // things. LLVMContext context1; EXPECT_EQ(&context1, &(TypeBuilder<types::i<1>, true>::get(context1))->getContext()); LLVMContext context2; EXPECT_EQ(&context2, &(TypeBuilder<types::i<1>, true>::get(context2))->getContext()); } struct MyType { int a; int *b; void *array[1]; }; struct MyPortableType { int32_t a; int32_t *b; void *array[1]; }; } // anonymous namespace namespace llvm { template<bool cross> class TypeBuilder<MyType, cross> { public: static StructType *get(LLVMContext &Context) { // Using the static result variable ensures that the type is // only looked up once. std::vector<Type*> st; st.push_back(TypeBuilder<int, cross>::get(Context)); st.push_back(TypeBuilder<int*, cross>::get(Context)); st.push_back(TypeBuilder<void*[], cross>::get(Context)); static StructType *const result = StructType::get(Context, st); return result; } // You may find this a convenient place to put some constants // to help with getelementptr. They don't have any effect on // the operation of TypeBuilder. enum Fields { FIELD_A, FIELD_B, FIELD_ARRAY }; }; template<bool cross> class TypeBuilder<MyPortableType, cross> { public: static StructType *get(LLVMContext &Context) { // Using the static result variable ensures that the type is // only looked up once. std::vector<Type*> st; st.push_back(TypeBuilder<types::i<32>, cross>::get(Context)); st.push_back(TypeBuilder<types::i<32>*, cross>::get(Context)); st.push_back(TypeBuilder<types::i<8>*[], cross>::get(Context)); static StructType *const result = StructType::get(Context, st); return result; } // You may find this a convenient place to put some constants // to help with getelementptr. They don't have any effect on // the operation of TypeBuilder. enum Fields { FIELD_A, FIELD_B, FIELD_ARRAY }; }; } // namespace llvm namespace { TEST(TypeBuilderTest, Extensions) { EXPECT_EQ(PointerType::getUnqual(StructType::get( TypeBuilder<int, false>::get(getGlobalContext()), TypeBuilder<int*, false>::get(getGlobalContext()), TypeBuilder<void*[], false>::get(getGlobalContext()), (void*)nullptr)), (TypeBuilder<MyType*, false>::get(getGlobalContext()))); EXPECT_EQ(PointerType::getUnqual(StructType::get( TypeBuilder<types::i<32>, false>::get(getGlobalContext()), TypeBuilder<types::i<32>*, false>::get(getGlobalContext()), TypeBuilder<types::i<8>*[], false>::get(getGlobalContext()), (void*)nullptr)), (TypeBuilder<MyPortableType*, false>::get(getGlobalContext()))); EXPECT_EQ(PointerType::getUnqual(StructType::get( TypeBuilder<types::i<32>, false>::get(getGlobalContext()), TypeBuilder<types::i<32>*, false>::get(getGlobalContext()), TypeBuilder<types::i<8>*[], false>::get(getGlobalContext()), (void*)nullptr)), (TypeBuilder<MyPortableType*, true>::get(getGlobalContext()))); } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/PassManagerTest.cpp
//===- llvm/unittest/IR/PassManager.cpp - PassManager tests ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Function.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/PassManager.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace { class TestFunctionAnalysis { public: struct Result { Result(int Count) : InstructionCount(Count) {} int InstructionCount; }; /// \brief Returns an opaque, unique ID for this pass type. static void *ID() { return (void *)&PassID; } /// \brief Returns the name of the analysis. static StringRef name() { return "TestFunctionAnalysis"; } TestFunctionAnalysis(int &Runs) : Runs(Runs) {} /// \brief Run the analysis pass over the function and return a result. Result run(Function &F, FunctionAnalysisManager *AM) { ++Runs; int Count = 0; for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) for (BasicBlock::iterator II = BBI->begin(), IE = BBI->end(); II != IE; ++II) ++Count; return Result(Count); } private: /// \brief Private static data to provide unique ID. static char PassID; int &Runs; }; char TestFunctionAnalysis::PassID; class TestModuleAnalysis { public: struct Result { Result(int Count) : FunctionCount(Count) {} int FunctionCount; }; static void *ID() { return (void *)&PassID; } static StringRef name() { return "TestModuleAnalysis"; } TestModuleAnalysis(int &Runs) : Runs(Runs) {} Result run(Module &M, ModuleAnalysisManager *AM) { ++Runs; int Count = 0; for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) ++Count; return Result(Count); } private: static char PassID; int &Runs; }; char TestModuleAnalysis::PassID; struct TestModulePass { TestModulePass(int &RunCount) : RunCount(RunCount) {} PreservedAnalyses run(Module &M) { ++RunCount; return PreservedAnalyses::none(); } static StringRef name() { return "TestModulePass"; } int &RunCount; }; struct TestPreservingModulePass { PreservedAnalyses run(Module &M) { return PreservedAnalyses::all(); } static StringRef name() { return "TestPreservingModulePass"; } }; struct TestMinPreservingModulePass { PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) { PreservedAnalyses PA; // Force running an analysis. (void)AM->getResult<TestModuleAnalysis>(M); PA.preserve<FunctionAnalysisManagerModuleProxy>(); return PA; } static StringRef name() { return "TestMinPreservingModulePass"; } }; struct TestFunctionPass { TestFunctionPass(int &RunCount, int &AnalyzedInstrCount, int &AnalyzedFunctionCount, bool OnlyUseCachedResults = false) : RunCount(RunCount), AnalyzedInstrCount(AnalyzedInstrCount), AnalyzedFunctionCount(AnalyzedFunctionCount), OnlyUseCachedResults(OnlyUseCachedResults) {} PreservedAnalyses run(Function &F, FunctionAnalysisManager *AM) { ++RunCount; const ModuleAnalysisManager &MAM = AM->getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager(); if (TestModuleAnalysis::Result *TMA = MAM.getCachedResult<TestModuleAnalysis>(*F.getParent())) AnalyzedFunctionCount += TMA->FunctionCount; if (OnlyUseCachedResults) { // Hack to force the use of the cached interface. if (TestFunctionAnalysis::Result *AR = AM->getCachedResult<TestFunctionAnalysis>(F)) AnalyzedInstrCount += AR->InstructionCount; } else { // Typical path just runs the analysis as needed. TestFunctionAnalysis::Result &AR = AM->getResult<TestFunctionAnalysis>(F); AnalyzedInstrCount += AR.InstructionCount; } return PreservedAnalyses::all(); } static StringRef name() { return "TestFunctionPass"; } int &RunCount; int &AnalyzedInstrCount; int &AnalyzedFunctionCount; bool OnlyUseCachedResults; }; // A test function pass that invalidates all function analyses for a function // with a specific name. struct TestInvalidationFunctionPass { TestInvalidationFunctionPass(StringRef FunctionName) : Name(FunctionName) {} PreservedAnalyses run(Function &F) { return F.getName() == Name ? PreservedAnalyses::none() : PreservedAnalyses::all(); } static StringRef name() { return "TestInvalidationFunctionPass"; } StringRef Name; }; std::unique_ptr<Module> parseIR(const char *IR) { LLVMContext &C = getGlobalContext(); SMDiagnostic Err; return parseAssemblyString(IR, Err, C); } class PassManagerTest : public ::testing::Test { protected: std::unique_ptr<Module> M; public: PassManagerTest() : M(parseIR("define void @f() {\n" "entry:\n" " call void @g()\n" " call void @h()\n" " ret void\n" "}\n" "define void @g() {\n" " ret void\n" "}\n" "define void @h() {\n" " ret void\n" "}\n")) {} }; TEST_F(PassManagerTest, BasicPreservedAnalyses) { PreservedAnalyses PA1 = PreservedAnalyses(); EXPECT_FALSE(PA1.preserved<TestFunctionAnalysis>()); EXPECT_FALSE(PA1.preserved<TestModuleAnalysis>()); PreservedAnalyses PA2 = PreservedAnalyses::none(); EXPECT_FALSE(PA2.preserved<TestFunctionAnalysis>()); EXPECT_FALSE(PA2.preserved<TestModuleAnalysis>()); PreservedAnalyses PA3 = PreservedAnalyses::all(); EXPECT_TRUE(PA3.preserved<TestFunctionAnalysis>()); EXPECT_TRUE(PA3.preserved<TestModuleAnalysis>()); PreservedAnalyses PA4 = PA1; EXPECT_FALSE(PA4.preserved<TestFunctionAnalysis>()); EXPECT_FALSE(PA4.preserved<TestModuleAnalysis>()); PA4 = PA3; EXPECT_TRUE(PA4.preserved<TestFunctionAnalysis>()); EXPECT_TRUE(PA4.preserved<TestModuleAnalysis>()); PA4 = std::move(PA2); EXPECT_FALSE(PA4.preserved<TestFunctionAnalysis>()); EXPECT_FALSE(PA4.preserved<TestModuleAnalysis>()); PA4.preserve<TestFunctionAnalysis>(); EXPECT_TRUE(PA4.preserved<TestFunctionAnalysis>()); EXPECT_FALSE(PA4.preserved<TestModuleAnalysis>()); PA1.preserve<TestModuleAnalysis>(); EXPECT_FALSE(PA1.preserved<TestFunctionAnalysis>()); EXPECT_TRUE(PA1.preserved<TestModuleAnalysis>()); PA1.preserve<TestFunctionAnalysis>(); EXPECT_TRUE(PA1.preserved<TestFunctionAnalysis>()); EXPECT_TRUE(PA1.preserved<TestModuleAnalysis>()); PA1.intersect(PA4); EXPECT_TRUE(PA1.preserved<TestFunctionAnalysis>()); EXPECT_FALSE(PA1.preserved<TestModuleAnalysis>()); } TEST_F(PassManagerTest, Basic) { FunctionAnalysisManager FAM; int FunctionAnalysisRuns = 0; FAM.registerPass(TestFunctionAnalysis(FunctionAnalysisRuns)); ModuleAnalysisManager MAM; int ModuleAnalysisRuns = 0; MAM.registerPass(TestModuleAnalysis(ModuleAnalysisRuns)); MAM.registerPass(FunctionAnalysisManagerModuleProxy(FAM)); FAM.registerPass(ModuleAnalysisManagerFunctionProxy(MAM)); ModulePassManager MPM; // Count the runs over a Function. int FunctionPassRunCount1 = 0; int AnalyzedInstrCount1 = 0; int AnalyzedFunctionCount1 = 0; { // Pointless scoped copy to test move assignment. ModulePassManager NestedMPM; FunctionPassManager FPM; { // Pointless scope to test move assignment. FunctionPassManager NestedFPM; NestedFPM.addPass(TestFunctionPass(FunctionPassRunCount1, AnalyzedInstrCount1, AnalyzedFunctionCount1)); FPM = std::move(NestedFPM); } NestedMPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); MPM = std::move(NestedMPM); } // Count the runs over a module. int ModulePassRunCount = 0; MPM.addPass(TestModulePass(ModulePassRunCount)); // Count the runs over a Function in a separate manager. int FunctionPassRunCount2 = 0; int AnalyzedInstrCount2 = 0; int AnalyzedFunctionCount2 = 0; { FunctionPassManager FPM; FPM.addPass(TestFunctionPass(FunctionPassRunCount2, AnalyzedInstrCount2, AnalyzedFunctionCount2)); MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); } // A third function pass manager but with only preserving intervening passes // and with a function pass that invalidates exactly one analysis. MPM.addPass(TestPreservingModulePass()); int FunctionPassRunCount3 = 0; int AnalyzedInstrCount3 = 0; int AnalyzedFunctionCount3 = 0; { FunctionPassManager FPM; FPM.addPass(TestFunctionPass(FunctionPassRunCount3, AnalyzedInstrCount3, AnalyzedFunctionCount3)); FPM.addPass(TestInvalidationFunctionPass("f")); MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); } // A fourth function pass manager but with a minimal intervening passes. MPM.addPass(TestMinPreservingModulePass()); int FunctionPassRunCount4 = 0; int AnalyzedInstrCount4 = 0; int AnalyzedFunctionCount4 = 0; { FunctionPassManager FPM; FPM.addPass(TestFunctionPass(FunctionPassRunCount4, AnalyzedInstrCount4, AnalyzedFunctionCount4)); MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); } // A fifth function pass manager but which uses only cached results. int FunctionPassRunCount5 = 0; int AnalyzedInstrCount5 = 0; int AnalyzedFunctionCount5 = 0; { FunctionPassManager FPM; FPM.addPass(TestInvalidationFunctionPass("f")); FPM.addPass(TestFunctionPass(FunctionPassRunCount5, AnalyzedInstrCount5, AnalyzedFunctionCount5, /*OnlyUseCachedResults=*/true)); MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); } MPM.run(*M, &MAM); // Validate module pass counters. EXPECT_EQ(1, ModulePassRunCount); // Validate all function pass counter sets are the same. EXPECT_EQ(3, FunctionPassRunCount1); EXPECT_EQ(5, AnalyzedInstrCount1); EXPECT_EQ(0, AnalyzedFunctionCount1); EXPECT_EQ(3, FunctionPassRunCount2); EXPECT_EQ(5, AnalyzedInstrCount2); EXPECT_EQ(0, AnalyzedFunctionCount2); EXPECT_EQ(3, FunctionPassRunCount3); EXPECT_EQ(5, AnalyzedInstrCount3); EXPECT_EQ(0, AnalyzedFunctionCount3); EXPECT_EQ(3, FunctionPassRunCount4); EXPECT_EQ(5, AnalyzedInstrCount4); EXPECT_EQ(0, AnalyzedFunctionCount4); EXPECT_EQ(3, FunctionPassRunCount5); EXPECT_EQ(2, AnalyzedInstrCount5); // Only 'g' and 'h' were cached. EXPECT_EQ(0, AnalyzedFunctionCount5); // Validate the analysis counters: // first run over 3 functions, then module pass invalidates // second run over 3 functions, nothing invalidates // third run over 0 functions, but 1 function invalidated // fourth run over 1 function EXPECT_EQ(7, FunctionAnalysisRuns); EXPECT_EQ(1, ModuleAnalysisRuns); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/TypesTest.cpp
//===- llvm/unittest/IR/TypesTest.cpp - Type unit tests -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(TypesTest, StructType) { LLVMContext C; // PR13522 StructType *Struct = StructType::create(C, "FooBar"); EXPECT_EQ("FooBar", Struct->getName()); Struct->setName(Struct->getName().substr(0, 3)); EXPECT_EQ("Foo", Struct->getName()); Struct->setName(""); EXPECT_TRUE(Struct->getName().empty()); EXPECT_FALSE(Struct->hasName()); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/ConstantRangeTest.cpp
//===- ConstantRangeTest.cpp - ConstantRange tests ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/IR/ConstantRange.h" #include "llvm/IR/Instructions.h" #include "gtest/gtest.h" using namespace llvm; namespace { class ConstantRangeTest : public ::testing::Test { protected: static ConstantRange Full; static ConstantRange Empty; static ConstantRange One; static ConstantRange Some; static ConstantRange Wrap; }; ConstantRange ConstantRangeTest::Full(16); ConstantRange ConstantRangeTest::Empty(16, false); ConstantRange ConstantRangeTest::One(APInt(16, 0xa)); ConstantRange ConstantRangeTest::Some(APInt(16, 0xa), APInt(16, 0xaaa)); ConstantRange ConstantRangeTest::Wrap(APInt(16, 0xaaa), APInt(16, 0xa)); TEST_F(ConstantRangeTest, Basics) { EXPECT_TRUE(Full.isFullSet()); EXPECT_FALSE(Full.isEmptySet()); EXPECT_TRUE(Full.inverse().isEmptySet()); EXPECT_FALSE(Full.isWrappedSet()); EXPECT_TRUE(Full.contains(APInt(16, 0x0))); EXPECT_TRUE(Full.contains(APInt(16, 0x9))); EXPECT_TRUE(Full.contains(APInt(16, 0xa))); EXPECT_TRUE(Full.contains(APInt(16, 0xaa9))); EXPECT_TRUE(Full.contains(APInt(16, 0xaaa))); EXPECT_FALSE(Empty.isFullSet()); EXPECT_TRUE(Empty.isEmptySet()); EXPECT_TRUE(Empty.inverse().isFullSet()); EXPECT_FALSE(Empty.isWrappedSet()); EXPECT_FALSE(Empty.contains(APInt(16, 0x0))); EXPECT_FALSE(Empty.contains(APInt(16, 0x9))); EXPECT_FALSE(Empty.contains(APInt(16, 0xa))); EXPECT_FALSE(Empty.contains(APInt(16, 0xaa9))); EXPECT_FALSE(Empty.contains(APInt(16, 0xaaa))); EXPECT_FALSE(One.isFullSet()); EXPECT_FALSE(One.isEmptySet()); EXPECT_FALSE(One.isWrappedSet()); EXPECT_FALSE(One.contains(APInt(16, 0x0))); EXPECT_FALSE(One.contains(APInt(16, 0x9))); EXPECT_TRUE(One.contains(APInt(16, 0xa))); EXPECT_FALSE(One.contains(APInt(16, 0xaa9))); EXPECT_FALSE(One.contains(APInt(16, 0xaaa))); EXPECT_FALSE(One.inverse().contains(APInt(16, 0xa))); EXPECT_FALSE(Some.isFullSet()); EXPECT_FALSE(Some.isEmptySet()); EXPECT_FALSE(Some.isWrappedSet()); EXPECT_FALSE(Some.contains(APInt(16, 0x0))); EXPECT_FALSE(Some.contains(APInt(16, 0x9))); EXPECT_TRUE(Some.contains(APInt(16, 0xa))); EXPECT_TRUE(Some.contains(APInt(16, 0xaa9))); EXPECT_FALSE(Some.contains(APInt(16, 0xaaa))); EXPECT_FALSE(Wrap.isFullSet()); EXPECT_FALSE(Wrap.isEmptySet()); EXPECT_TRUE(Wrap.isWrappedSet()); EXPECT_TRUE(Wrap.contains(APInt(16, 0x0))); EXPECT_TRUE(Wrap.contains(APInt(16, 0x9))); EXPECT_FALSE(Wrap.contains(APInt(16, 0xa))); EXPECT_FALSE(Wrap.contains(APInt(16, 0xaa9))); EXPECT_TRUE(Wrap.contains(APInt(16, 0xaaa))); } TEST_F(ConstantRangeTest, Equality) { EXPECT_EQ(Full, Full); EXPECT_EQ(Empty, Empty); EXPECT_EQ(One, One); EXPECT_EQ(Some, Some); EXPECT_EQ(Wrap, Wrap); EXPECT_NE(Full, Empty); EXPECT_NE(Full, One); EXPECT_NE(Full, Some); EXPECT_NE(Full, Wrap); EXPECT_NE(Empty, One); EXPECT_NE(Empty, Some); EXPECT_NE(Empty, Wrap); EXPECT_NE(One, Some); EXPECT_NE(One, Wrap); EXPECT_NE(Some, Wrap); } TEST_F(ConstantRangeTest, SingleElement) { EXPECT_EQ(Full.getSingleElement(), static_cast<APInt *>(nullptr)); EXPECT_EQ(Empty.getSingleElement(), static_cast<APInt *>(nullptr)); EXPECT_EQ(*One.getSingleElement(), APInt(16, 0xa)); EXPECT_EQ(Some.getSingleElement(), static_cast<APInt *>(nullptr)); EXPECT_EQ(Wrap.getSingleElement(), static_cast<APInt *>(nullptr)); EXPECT_FALSE(Full.isSingleElement()); EXPECT_FALSE(Empty.isSingleElement()); EXPECT_TRUE(One.isSingleElement()); EXPECT_FALSE(Some.isSingleElement()); EXPECT_FALSE(Wrap.isSingleElement()); } TEST_F(ConstantRangeTest, GetSetSize) { EXPECT_EQ(Full.getSetSize(), APInt(17, 65536)); EXPECT_EQ(Empty.getSetSize(), APInt(17, 0)); EXPECT_EQ(One.getSetSize(), APInt(17, 1)); EXPECT_EQ(Some.getSetSize(), APInt(17, 0xaa0)); ConstantRange Wrap(APInt(4, 7), APInt(4, 3)); ConstantRange Wrap2(APInt(4, 8), APInt(4, 7)); EXPECT_EQ(Wrap.getSetSize(), APInt(5, 12)); EXPECT_EQ(Wrap2.getSetSize(), APInt(5, 15)); } TEST_F(ConstantRangeTest, GetMinsAndMaxes) { EXPECT_EQ(Full.getUnsignedMax(), APInt(16, UINT16_MAX)); EXPECT_EQ(One.getUnsignedMax(), APInt(16, 0xa)); EXPECT_EQ(Some.getUnsignedMax(), APInt(16, 0xaa9)); EXPECT_EQ(Wrap.getUnsignedMax(), APInt(16, UINT16_MAX)); EXPECT_EQ(Full.getUnsignedMin(), APInt(16, 0)); EXPECT_EQ(One.getUnsignedMin(), APInt(16, 0xa)); EXPECT_EQ(Some.getUnsignedMin(), APInt(16, 0xa)); EXPECT_EQ(Wrap.getUnsignedMin(), APInt(16, 0)); EXPECT_EQ(Full.getSignedMax(), APInt(16, INT16_MAX)); EXPECT_EQ(One.getSignedMax(), APInt(16, 0xa)); EXPECT_EQ(Some.getSignedMax(), APInt(16, 0xaa9)); EXPECT_EQ(Wrap.getSignedMax(), APInt(16, INT16_MAX)); EXPECT_EQ(Full.getSignedMin(), APInt(16, (uint64_t)INT16_MIN)); EXPECT_EQ(One.getSignedMin(), APInt(16, 0xa)); EXPECT_EQ(Some.getSignedMin(), APInt(16, 0xa)); EXPECT_EQ(Wrap.getSignedMin(), APInt(16, (uint64_t)INT16_MIN)); // Found by Klee EXPECT_EQ(ConstantRange(APInt(4, 7), APInt(4, 0)).getSignedMax(), APInt(4, 7)); } TEST_F(ConstantRangeTest, SignWrapped) { EXPECT_TRUE(Full.isSignWrappedSet()); EXPECT_FALSE(Empty.isSignWrappedSet()); EXPECT_FALSE(One.isSignWrappedSet()); EXPECT_FALSE(Some.isSignWrappedSet()); EXPECT_TRUE(Wrap.isSignWrappedSet()); EXPECT_FALSE(ConstantRange(APInt(8, 127), APInt(8, 128)).isSignWrappedSet()); EXPECT_TRUE(ConstantRange(APInt(8, 127), APInt(8, 129)).isSignWrappedSet()); EXPECT_FALSE(ConstantRange(APInt(8, 128), APInt(8, 129)).isSignWrappedSet()); EXPECT_TRUE(ConstantRange(APInt(8, 10), APInt(8, 9)).isSignWrappedSet()); EXPECT_TRUE(ConstantRange(APInt(8, 10), APInt(8, 250)).isSignWrappedSet()); EXPECT_FALSE(ConstantRange(APInt(8, 250), APInt(8, 10)).isSignWrappedSet()); EXPECT_FALSE(ConstantRange(APInt(8, 250), APInt(8, 251)).isSignWrappedSet()); } TEST_F(ConstantRangeTest, Trunc) { ConstantRange TFull = Full.truncate(10); ConstantRange TEmpty = Empty.truncate(10); ConstantRange TOne = One.truncate(10); ConstantRange TSome = Some.truncate(10); ConstantRange TWrap = Wrap.truncate(10); EXPECT_TRUE(TFull.isFullSet()); EXPECT_TRUE(TEmpty.isEmptySet()); EXPECT_EQ(TOne, ConstantRange(One.getLower().trunc(10), One.getUpper().trunc(10))); EXPECT_TRUE(TSome.isFullSet()); } TEST_F(ConstantRangeTest, ZExt) { ConstantRange ZFull = Full.zeroExtend(20); ConstantRange ZEmpty = Empty.zeroExtend(20); ConstantRange ZOne = One.zeroExtend(20); ConstantRange ZSome = Some.zeroExtend(20); ConstantRange ZWrap = Wrap.zeroExtend(20); EXPECT_EQ(ZFull, ConstantRange(APInt(20, 0), APInt(20, 0x10000))); EXPECT_TRUE(ZEmpty.isEmptySet()); EXPECT_EQ(ZOne, ConstantRange(One.getLower().zext(20), One.getUpper().zext(20))); EXPECT_EQ(ZSome, ConstantRange(Some.getLower().zext(20), Some.getUpper().zext(20))); EXPECT_EQ(ZWrap, ConstantRange(APInt(20, 0), APInt(20, 0x10000))); // zext([5, 0), 3->7) = [5, 8) ConstantRange FiveZero(APInt(3, 5), APInt(3, 0)); EXPECT_EQ(FiveZero.zeroExtend(7), ConstantRange(APInt(7, 5), APInt(7, 8))); } TEST_F(ConstantRangeTest, SExt) { ConstantRange SFull = Full.signExtend(20); ConstantRange SEmpty = Empty.signExtend(20); ConstantRange SOne = One.signExtend(20); ConstantRange SSome = Some.signExtend(20); ConstantRange SWrap = Wrap.signExtend(20); EXPECT_EQ(SFull, ConstantRange(APInt(20, (uint64_t)INT16_MIN, true), APInt(20, INT16_MAX + 1, true))); EXPECT_TRUE(SEmpty.isEmptySet()); EXPECT_EQ(SOne, ConstantRange(One.getLower().sext(20), One.getUpper().sext(20))); EXPECT_EQ(SSome, ConstantRange(Some.getLower().sext(20), Some.getUpper().sext(20))); EXPECT_EQ(SWrap, ConstantRange(APInt(20, (uint64_t)INT16_MIN, true), APInt(20, INT16_MAX + 1, true))); EXPECT_EQ(ConstantRange(APInt(8, 120), APInt(8, 140)).signExtend(16), ConstantRange(APInt(16, -128), APInt(16, 128))); EXPECT_EQ(ConstantRange(APInt(16, 0x0200), APInt(16, 0x8000)).signExtend(19), ConstantRange(APInt(19, 0x0200), APInt(19, 0x8000))); } TEST_F(ConstantRangeTest, IntersectWith) { EXPECT_EQ(Empty.intersectWith(Full), Empty); EXPECT_EQ(Empty.intersectWith(Empty), Empty); EXPECT_EQ(Empty.intersectWith(One), Empty); EXPECT_EQ(Empty.intersectWith(Some), Empty); EXPECT_EQ(Empty.intersectWith(Wrap), Empty); EXPECT_EQ(Full.intersectWith(Full), Full); EXPECT_EQ(Some.intersectWith(Some), Some); EXPECT_EQ(Some.intersectWith(One), One); EXPECT_EQ(Full.intersectWith(One), One); EXPECT_EQ(Full.intersectWith(Some), Some); EXPECT_EQ(Some.intersectWith(Wrap), Empty); EXPECT_EQ(One.intersectWith(Wrap), Empty); EXPECT_EQ(One.intersectWith(Wrap), Wrap.intersectWith(One)); // Klee generated testcase from PR4545. // The intersection of i16 [4, 2) and [6, 5) is disjoint, looking like // 01..4.6789ABCDEF where the dots represent values not in the intersection. ConstantRange LHS(APInt(16, 4), APInt(16, 2)); ConstantRange RHS(APInt(16, 6), APInt(16, 5)); EXPECT_TRUE(LHS.intersectWith(RHS) == LHS); // previous bug: intersection of [min, 3) and [2, max) should be 2 LHS = ConstantRange(APInt(32, -2147483646), APInt(32, 3)); RHS = ConstantRange(APInt(32, 2), APInt(32, 2147483646)); EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 2))); // [2, 0) /\ [4, 3) = [2, 0) LHS = ConstantRange(APInt(32, 2), APInt(32, 0)); RHS = ConstantRange(APInt(32, 4), APInt(32, 3)); EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 2), APInt(32, 0))); // [2, 0) /\ [4, 2) = [4, 0) LHS = ConstantRange(APInt(32, 2), APInt(32, 0)); RHS = ConstantRange(APInt(32, 4), APInt(32, 2)); EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 4), APInt(32, 0))); // [4, 2) /\ [5, 1) = [5, 1) LHS = ConstantRange(APInt(32, 4), APInt(32, 2)); RHS = ConstantRange(APInt(32, 5), APInt(32, 1)); EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 5), APInt(32, 1))); // [2, 0) /\ [7, 4) = [7, 4) LHS = ConstantRange(APInt(32, 2), APInt(32, 0)); RHS = ConstantRange(APInt(32, 7), APInt(32, 4)); EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 7), APInt(32, 4))); // [4, 2) /\ [1, 0) = [1, 0) LHS = ConstantRange(APInt(32, 4), APInt(32, 2)); RHS = ConstantRange(APInt(32, 1), APInt(32, 0)); EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 4), APInt(32, 2))); // [15, 0) /\ [7, 6) = [15, 0) LHS = ConstantRange(APInt(32, 15), APInt(32, 0)); RHS = ConstantRange(APInt(32, 7), APInt(32, 6)); EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 15), APInt(32, 0))); } TEST_F(ConstantRangeTest, UnionWith) { EXPECT_EQ(Wrap.unionWith(One), ConstantRange(APInt(16, 0xaaa), APInt(16, 0xb))); EXPECT_EQ(One.unionWith(Wrap), Wrap.unionWith(One)); EXPECT_EQ(Empty.unionWith(Empty), Empty); EXPECT_EQ(Full.unionWith(Full), Full); EXPECT_EQ(Some.unionWith(Wrap), Full); // PR4545 EXPECT_EQ(ConstantRange(APInt(16, 14), APInt(16, 1)).unionWith( ConstantRange(APInt(16, 0), APInt(16, 8))), ConstantRange(APInt(16, 14), APInt(16, 8))); EXPECT_EQ(ConstantRange(APInt(16, 6), APInt(16, 4)).unionWith( ConstantRange(APInt(16, 4), APInt(16, 0))), ConstantRange(16)); EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 0)).unionWith( ConstantRange(APInt(16, 2), APInt(16, 1))), ConstantRange(16)); } TEST_F(ConstantRangeTest, SetDifference) { EXPECT_EQ(Full.difference(Empty), Full); EXPECT_EQ(Full.difference(Full), Empty); EXPECT_EQ(Empty.difference(Empty), Empty); EXPECT_EQ(Empty.difference(Full), Empty); ConstantRange A(APInt(16, 3), APInt(16, 7)); ConstantRange B(APInt(16, 5), APInt(16, 9)); ConstantRange C(APInt(16, 3), APInt(16, 5)); ConstantRange D(APInt(16, 7), APInt(16, 9)); ConstantRange E(APInt(16, 5), APInt(16, 4)); ConstantRange F(APInt(16, 7), APInt(16, 3)); EXPECT_EQ(A.difference(B), C); EXPECT_EQ(B.difference(A), D); EXPECT_EQ(E.difference(A), F); } TEST_F(ConstantRangeTest, SubtractAPInt) { EXPECT_EQ(Full.subtract(APInt(16, 4)), Full); EXPECT_EQ(Empty.subtract(APInt(16, 4)), Empty); EXPECT_EQ(Some.subtract(APInt(16, 4)), ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6))); EXPECT_EQ(Wrap.subtract(APInt(16, 4)), ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6))); EXPECT_EQ(One.subtract(APInt(16, 4)), ConstantRange(APInt(16, 0x6))); } TEST_F(ConstantRangeTest, Add) { EXPECT_EQ(Full.add(APInt(16, 4)), Full); EXPECT_EQ(Full.add(Full), Full); EXPECT_EQ(Full.add(Empty), Empty); EXPECT_EQ(Full.add(One), Full); EXPECT_EQ(Full.add(Some), Full); EXPECT_EQ(Full.add(Wrap), Full); EXPECT_EQ(Empty.add(Empty), Empty); EXPECT_EQ(Empty.add(One), Empty); EXPECT_EQ(Empty.add(Some), Empty); EXPECT_EQ(Empty.add(Wrap), Empty); EXPECT_EQ(Empty.add(APInt(16, 4)), Empty); EXPECT_EQ(Some.add(APInt(16, 4)), ConstantRange(APInt(16, 0xe), APInt(16, 0xaae))); EXPECT_EQ(Wrap.add(APInt(16, 4)), ConstantRange(APInt(16, 0xaae), APInt(16, 0xe))); EXPECT_EQ(One.add(APInt(16, 4)), ConstantRange(APInt(16, 0xe))); } TEST_F(ConstantRangeTest, Sub) { EXPECT_EQ(Full.sub(APInt(16, 4)), Full); EXPECT_EQ(Full.sub(Full), Full); EXPECT_EQ(Full.sub(Empty), Empty); EXPECT_EQ(Full.sub(One), Full); EXPECT_EQ(Full.sub(Some), Full); EXPECT_EQ(Full.sub(Wrap), Full); EXPECT_EQ(Empty.sub(Empty), Empty); EXPECT_EQ(Empty.sub(One), Empty); EXPECT_EQ(Empty.sub(Some), Empty); EXPECT_EQ(Empty.sub(Wrap), Empty); EXPECT_EQ(Empty.sub(APInt(16, 4)), Empty); EXPECT_EQ(Some.sub(APInt(16, 4)), ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6))); EXPECT_EQ(Some.sub(Some), ConstantRange(APInt(16, 0xf561), APInt(16, 0xaa0))); EXPECT_EQ(Wrap.sub(APInt(16, 4)), ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6))); EXPECT_EQ(One.sub(APInt(16, 4)), ConstantRange(APInt(16, 0x6))); } TEST_F(ConstantRangeTest, Multiply) { EXPECT_EQ(Full.multiply(Full), Full); EXPECT_EQ(Full.multiply(Empty), Empty); EXPECT_EQ(Full.multiply(One), Full); EXPECT_EQ(Full.multiply(Some), Full); EXPECT_EQ(Full.multiply(Wrap), Full); EXPECT_EQ(Empty.multiply(Empty), Empty); EXPECT_EQ(Empty.multiply(One), Empty); EXPECT_EQ(Empty.multiply(Some), Empty); EXPECT_EQ(Empty.multiply(Wrap), Empty); EXPECT_EQ(One.multiply(One), ConstantRange(APInt(16, 0xa*0xa), APInt(16, 0xa*0xa + 1))); EXPECT_EQ(One.multiply(Some), ConstantRange(APInt(16, 0xa*0xa), APInt(16, 0xa*0xaa9 + 1))); EXPECT_EQ(One.multiply(Wrap), Full); EXPECT_EQ(Some.multiply(Some), Full); EXPECT_EQ(Some.multiply(Wrap), Full); EXPECT_EQ(Wrap.multiply(Wrap), Full); ConstantRange Zero(APInt(16, 0)); EXPECT_EQ(Zero.multiply(Full), Zero); EXPECT_EQ(Zero.multiply(Some), Zero); EXPECT_EQ(Zero.multiply(Wrap), Zero); EXPECT_EQ(Full.multiply(Zero), Zero); EXPECT_EQ(Some.multiply(Zero), Zero); EXPECT_EQ(Wrap.multiply(Zero), Zero); // http://llvm.org/PR4545 EXPECT_EQ(ConstantRange(APInt(4, 1), APInt(4, 6)).multiply( ConstantRange(APInt(4, 6), APInt(4, 2))), ConstantRange(4, /*isFullSet=*/true)); EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 0)).multiply( ConstantRange(APInt(8, 252), APInt(8, 4))), ConstantRange(APInt(8, 250), APInt(8, 9))); EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 255)).multiply( ConstantRange(APInt(8, 2), APInt(8, 4))), ConstantRange(APInt(8, 250), APInt(8, 253))); } TEST_F(ConstantRangeTest, UMax) { EXPECT_EQ(Full.umax(Full), Full); EXPECT_EQ(Full.umax(Empty), Empty); EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0))); EXPECT_EQ(Full.umax(Wrap), Full); EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0))); EXPECT_EQ(Empty.umax(Empty), Empty); EXPECT_EQ(Empty.umax(Some), Empty); EXPECT_EQ(Empty.umax(Wrap), Empty); EXPECT_EQ(Empty.umax(One), Empty); EXPECT_EQ(Some.umax(Some), Some); EXPECT_EQ(Some.umax(Wrap), ConstantRange(APInt(16, 0xa), APInt(16, 0))); EXPECT_EQ(Some.umax(One), Some); // TODO: ConstantRange is currently over-conservative here. EXPECT_EQ(Wrap.umax(Wrap), Full); EXPECT_EQ(Wrap.umax(One), ConstantRange(APInt(16, 0xa), APInt(16, 0))); EXPECT_EQ(One.umax(One), One); } TEST_F(ConstantRangeTest, SMax) { EXPECT_EQ(Full.smax(Full), Full); EXPECT_EQ(Full.smax(Empty), Empty); EXPECT_EQ(Full.smax(Some), ConstantRange(APInt(16, 0xa), APInt::getSignedMinValue(16))); EXPECT_EQ(Full.smax(Wrap), Full); EXPECT_EQ(Full.smax(One), ConstantRange(APInt(16, 0xa), APInt::getSignedMinValue(16))); EXPECT_EQ(Empty.smax(Empty), Empty); EXPECT_EQ(Empty.smax(Some), Empty); EXPECT_EQ(Empty.smax(Wrap), Empty); EXPECT_EQ(Empty.smax(One), Empty); EXPECT_EQ(Some.smax(Some), Some); EXPECT_EQ(Some.smax(Wrap), ConstantRange(APInt(16, 0xa), APInt(16, (uint64_t)INT16_MIN))); EXPECT_EQ(Some.smax(One), Some); EXPECT_EQ(Wrap.smax(One), ConstantRange(APInt(16, 0xa), APInt(16, (uint64_t)INT16_MIN))); EXPECT_EQ(One.smax(One), One); } TEST_F(ConstantRangeTest, UDiv) { EXPECT_EQ(Full.udiv(Full), Full); EXPECT_EQ(Full.udiv(Empty), Empty); EXPECT_EQ(Full.udiv(One), ConstantRange(APInt(16, 0), APInt(16, 0xffff / 0xa + 1))); EXPECT_EQ(Full.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 0xffff / 0xa + 1))); EXPECT_EQ(Full.udiv(Wrap), Full); EXPECT_EQ(Empty.udiv(Empty), Empty); EXPECT_EQ(Empty.udiv(One), Empty); EXPECT_EQ(Empty.udiv(Some), Empty); EXPECT_EQ(Empty.udiv(Wrap), Empty); EXPECT_EQ(One.udiv(One), ConstantRange(APInt(16, 1))); EXPECT_EQ(One.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 2))); EXPECT_EQ(One.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb))); EXPECT_EQ(Some.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 0x111))); EXPECT_EQ(Some.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa))); EXPECT_EQ(Wrap.udiv(Wrap), Full); } TEST_F(ConstantRangeTest, Shl) { EXPECT_EQ(Full.shl(Full), Full); EXPECT_EQ(Full.shl(Empty), Empty); EXPECT_EQ(Full.shl(One), Full); // TODO: [0, (-1 << 0xa) + 1) EXPECT_EQ(Full.shl(Some), Full); // TODO: [0, (-1 << 0xa) + 1) EXPECT_EQ(Full.shl(Wrap), Full); EXPECT_EQ(Empty.shl(Empty), Empty); EXPECT_EQ(Empty.shl(One), Empty); EXPECT_EQ(Empty.shl(Some), Empty); EXPECT_EQ(Empty.shl(Wrap), Empty); EXPECT_EQ(One.shl(One), ConstantRange(APInt(16, 0xa << 0xa), APInt(16, (0xa << 0xa) + 1))); EXPECT_EQ(One.shl(Some), Full); // TODO: [0xa << 0xa, 0) EXPECT_EQ(One.shl(Wrap), Full); // TODO: [0xa, 0xa << 14 + 1) EXPECT_EQ(Some.shl(Some), Full); // TODO: [0xa << 0xa, 0xfc01) EXPECT_EQ(Some.shl(Wrap), Full); // TODO: [0xa, 0x7ff << 0x5 + 1) EXPECT_EQ(Wrap.shl(Wrap), Full); } TEST_F(ConstantRangeTest, Lshr) { EXPECT_EQ(Full.lshr(Full), Full); EXPECT_EQ(Full.lshr(Empty), Empty); EXPECT_EQ(Full.lshr(One), ConstantRange(APInt(16, 0), APInt(16, (0xffff >> 0xa) + 1))); EXPECT_EQ(Full.lshr(Some), ConstantRange(APInt(16, 0), APInt(16, (0xffff >> 0xa) + 1))); EXPECT_EQ(Full.lshr(Wrap), Full); EXPECT_EQ(Empty.lshr(Empty), Empty); EXPECT_EQ(Empty.lshr(One), Empty); EXPECT_EQ(Empty.lshr(Some), Empty); EXPECT_EQ(Empty.lshr(Wrap), Empty); EXPECT_EQ(One.lshr(One), ConstantRange(APInt(16, 0))); EXPECT_EQ(One.lshr(Some), ConstantRange(APInt(16, 0))); EXPECT_EQ(One.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb))); EXPECT_EQ(Some.lshr(Some), ConstantRange(APInt(16, 0), APInt(16, (0xaaa >> 0xa) + 1))); EXPECT_EQ(Some.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa))); EXPECT_EQ(Wrap.lshr(Wrap), Full); } TEST(ConstantRange, MakeAllowedICmpRegion) { // PR8250 ConstantRange SMax = ConstantRange(APInt::getSignedMaxValue(32)); EXPECT_TRUE(ConstantRange::makeAllowedICmpRegion(ICmpInst::ICMP_SGT, SMax) .isEmptySet()); } TEST(ConstantRange, MakeSatisfyingICmpRegion) { ConstantRange LowHalf(APInt(8, 0), APInt(8, 128)); ConstantRange HighHalf(APInt(8, 128), APInt(8, 0)); ConstantRange EmptySet(8, /* isFullSet = */ false); EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, LowHalf), HighHalf); EXPECT_EQ( ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, HighHalf), LowHalf); EXPECT_TRUE(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_EQ, HighHalf).isEmptySet()); ConstantRange UnsignedSample(APInt(8, 5), APInt(8, 200)); EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULT, UnsignedSample), ConstantRange(APInt(8, 0), APInt(8, 5))); EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULE, UnsignedSample), ConstantRange(APInt(8, 0), APInt(8, 6))); EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGT, UnsignedSample), ConstantRange(APInt(8, 200), APInt(8, 0))); EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGE, UnsignedSample), ConstantRange(APInt(8, 199), APInt(8, 0))); ConstantRange SignedSample(APInt(8, -5), APInt(8, 5)); EXPECT_EQ( ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLT, SignedSample), ConstantRange(APInt(8, -128), APInt(8, -5))); EXPECT_EQ( ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLE, SignedSample), ConstantRange(APInt(8, -128), APInt(8, -4))); EXPECT_EQ( ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGT, SignedSample), ConstantRange(APInt(8, 5), APInt(8, -128))); EXPECT_EQ( ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGE, SignedSample), ConstantRange(APInt(8, 4), APInt(8, -128))); } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/IR/ConstantsTest.cpp
//===- llvm/unittest/IR/ConstantsTest.cpp - Constants unit tests ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" namespace llvm { namespace { TEST(ConstantsTest, Integer_i1) { IntegerType* Int1 = IntegerType::get(getGlobalContext(), 1); Constant* One = ConstantInt::get(Int1, 1, true); Constant* Zero = ConstantInt::get(Int1, 0); Constant* NegOne = ConstantInt::get(Int1, static_cast<uint64_t>(-1), true); EXPECT_EQ(NegOne, ConstantInt::getSigned(Int1, -1)); Constant* Undef = UndefValue::get(Int1); // Input: @b = constant i1 add(i1 1 , i1 1) // Output: @b = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getAdd(One, One)); // @c = constant i1 add(i1 -1, i1 1) // @c = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, One)); // @d = constant i1 add(i1 -1, i1 -1) // @d = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, NegOne)); // @e = constant i1 sub(i1 -1, i1 1) // @e = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSub(NegOne, One)); // @f = constant i1 sub(i1 1 , i1 -1) // @f = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSub(One, NegOne)); // @g = constant i1 sub(i1 1 , i1 1) // @g = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSub(One, One)); // @h = constant i1 shl(i1 1 , i1 1) ; undefined // @h = constant i1 undef EXPECT_EQ(Undef, ConstantExpr::getShl(One, One)); // @i = constant i1 shl(i1 1 , i1 0) // @i = constant i1 true EXPECT_EQ(One, ConstantExpr::getShl(One, Zero)); // @j = constant i1 lshr(i1 1, i1 1) ; undefined // @j = constant i1 undef EXPECT_EQ(Undef, ConstantExpr::getLShr(One, One)); // @m = constant i1 ashr(i1 1, i1 1) ; undefined // @m = constant i1 undef EXPECT_EQ(Undef, ConstantExpr::getAShr(One, One)); // @n = constant i1 mul(i1 -1, i1 1) // @n = constant i1 true EXPECT_EQ(One, ConstantExpr::getMul(NegOne, One)); // @o = constant i1 sdiv(i1 -1, i1 1) ; overflow // @o = constant i1 true EXPECT_EQ(One, ConstantExpr::getSDiv(NegOne, One)); // @p = constant i1 sdiv(i1 1 , i1 -1); overflow // @p = constant i1 true EXPECT_EQ(One, ConstantExpr::getSDiv(One, NegOne)); // @q = constant i1 udiv(i1 -1, i1 1) // @q = constant i1 true EXPECT_EQ(One, ConstantExpr::getUDiv(NegOne, One)); // @r = constant i1 udiv(i1 1, i1 -1) // @r = constant i1 true EXPECT_EQ(One, ConstantExpr::getUDiv(One, NegOne)); // @s = constant i1 srem(i1 -1, i1 1) ; overflow // @s = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSRem(NegOne, One)); // @t = constant i1 urem(i1 -1, i1 1) // @t = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getURem(NegOne, One)); // @u = constant i1 srem(i1 1, i1 -1) ; overflow // @u = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSRem(One, NegOne)); } TEST(ConstantsTest, IntSigns) { IntegerType* Int8Ty = Type::getInt8Ty(getGlobalContext()); EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, false)->getSExtValue()); EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, true)->getSExtValue()); EXPECT_EQ(100, ConstantInt::getSigned(Int8Ty, 100)->getSExtValue()); EXPECT_EQ(-50, ConstantInt::get(Int8Ty, 206)->getSExtValue()); EXPECT_EQ(-50, ConstantInt::getSigned(Int8Ty, -50)->getSExtValue()); EXPECT_EQ(206U, ConstantInt::getSigned(Int8Ty, -50)->getZExtValue()); // Overflow is handled by truncation. EXPECT_EQ(0x3b, ConstantInt::get(Int8Ty, 0x13b)->getSExtValue()); } TEST(ConstantsTest, FP128Test) { Type *FP128Ty = Type::getFP128Ty(getGlobalContext()); IntegerType *Int128Ty = Type::getIntNTy(getGlobalContext(), 128); Constant *Zero128 = Constant::getNullValue(Int128Ty); Constant *X = ConstantExpr::getUIToFP(Zero128, FP128Ty); EXPECT_TRUE(isa<ConstantFP>(X)); } TEST(ConstantsTest, PointerCast) { LLVMContext &C(getGlobalContext()); Type *Int8PtrTy = Type::getInt8PtrTy(C); Type *Int32PtrTy = Type::getInt32PtrTy(C); Type *Int64Ty = Type::getInt64Ty(C); VectorType *Int8PtrVecTy = VectorType::get(Int8PtrTy, 4); VectorType *Int32PtrVecTy = VectorType::get(Int32PtrTy, 4); VectorType *Int64VecTy = VectorType::get(Int64Ty, 4); // ptrtoint i8* to i64 EXPECT_EQ(Constant::getNullValue(Int64Ty), ConstantExpr::getPointerCast( Constant::getNullValue(Int8PtrTy), Int64Ty)); // bitcast i8* to i32* EXPECT_EQ(Constant::getNullValue(Int32PtrTy), ConstantExpr::getPointerCast( Constant::getNullValue(Int8PtrTy), Int32PtrTy)); // ptrtoint <4 x i8*> to <4 x i64> EXPECT_EQ(Constant::getNullValue(Int64VecTy), ConstantExpr::getPointerCast( Constant::getNullValue(Int8PtrVecTy), Int64VecTy)); // bitcast <4 x i8*> to <4 x i32*> EXPECT_EQ(Constant::getNullValue(Int32PtrVecTy), ConstantExpr::getPointerCast( Constant::getNullValue(Int8PtrVecTy), Int32PtrVecTy)); } #define CHECK(x, y) { \ std::string __s; \ raw_string_ostream __o(__s); \ Instruction *__I = cast<ConstantExpr>(x)->getAsInstruction(); \ __I->print(__o); \ delete __I; \ __o.flush(); \ EXPECT_EQ(std::string(" <badref> = " y), __s); \ } TEST(ConstantsTest, AsInstructionsTest) { std::unique_ptr<Module> M(new Module("MyModule", getGlobalContext())); Type *Int64Ty = Type::getInt64Ty(getGlobalContext()); Type *Int32Ty = Type::getInt32Ty(getGlobalContext()); Type *Int16Ty = Type::getInt16Ty(getGlobalContext()); Type *Int1Ty = Type::getInt1Ty(getGlobalContext()); Type *FloatTy = Type::getFloatTy(getGlobalContext()); Type *DoubleTy = Type::getDoubleTy(getGlobalContext()); Constant *Global = M->getOrInsertGlobal("dummy", PointerType::getUnqual(Int32Ty)); Constant *Global2 = M->getOrInsertGlobal("dummy2", PointerType::getUnqual(Int32Ty)); Constant *P0 = ConstantExpr::getPtrToInt(Global, Int32Ty); Constant *P1 = ConstantExpr::getUIToFP(P0, FloatTy); Constant *P2 = ConstantExpr::getUIToFP(P0, DoubleTy); Constant *P3 = ConstantExpr::getTrunc(P0, Int1Ty); Constant *P4 = ConstantExpr::getPtrToInt(Global2, Int32Ty); Constant *P5 = ConstantExpr::getUIToFP(P4, FloatTy); Constant *P6 = ConstantExpr::getBitCast(P4, VectorType::get(Int16Ty, 2)); Constant *One = ConstantInt::get(Int32Ty, 1); Constant *Two = ConstantInt::get(Int64Ty, 2); Constant *Big = ConstantInt::get(getGlobalContext(), APInt{256, uint64_t(-1), true}); Constant *Elt = ConstantInt::get(Int16Ty, 2015); Constant *Undef16 = UndefValue::get(Int16Ty); Constant *Undef64 = UndefValue::get(Int64Ty); Constant *UndefV16 = UndefValue::get(P6->getType()); #define P0STR "ptrtoint (i32** @dummy to i32)" #define P1STR "uitofp (i32 ptrtoint (i32** @dummy to i32) to float)" #define P2STR "uitofp (i32 ptrtoint (i32** @dummy to i32) to double)" #define P3STR "ptrtoint (i32** @dummy to i1)" #define P4STR "ptrtoint (i32** @dummy2 to i32)" #define P5STR "uitofp (i32 ptrtoint (i32** @dummy2 to i32) to float)" #define P6STR "bitcast (i32 ptrtoint (i32** @dummy2 to i32) to <2 x i16>)" CHECK(ConstantExpr::getNeg(P0), "sub i32 0, " P0STR); CHECK(ConstantExpr::getFNeg(P1), "fsub float -0.000000e+00, " P1STR); CHECK(ConstantExpr::getNot(P0), "xor i32 " P0STR ", -1"); CHECK(ConstantExpr::getAdd(P0, P0), "add i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getAdd(P0, P0, false, true), "add nsw i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getAdd(P0, P0, true, true), "add nuw nsw i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getFAdd(P1, P1), "fadd float " P1STR ", " P1STR); CHECK(ConstantExpr::getSub(P0, P0), "sub i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getFSub(P1, P1), "fsub float " P1STR ", " P1STR); CHECK(ConstantExpr::getMul(P0, P0), "mul i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getFMul(P1, P1), "fmul float " P1STR ", " P1STR); CHECK(ConstantExpr::getUDiv(P0, P0), "udiv i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getSDiv(P0, P0), "sdiv i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getFDiv(P1, P1), "fdiv float " P1STR ", " P1STR); CHECK(ConstantExpr::getURem(P0, P0), "urem i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getSRem(P0, P0), "srem i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getFRem(P1, P1), "frem float " P1STR ", " P1STR); CHECK(ConstantExpr::getAnd(P0, P0), "and i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getOr(P0, P0), "or i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getXor(P0, P0), "xor i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getShl(P0, P0), "shl i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getShl(P0, P0, true), "shl nuw i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getShl(P0, P0, false, true), "shl nsw i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getLShr(P0, P0, false), "lshr i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getLShr(P0, P0, true), "lshr exact i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getAShr(P0, P0, false), "ashr i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getAShr(P0, P0, true), "ashr exact i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getSExt(P0, Int64Ty), "sext i32 " P0STR " to i64"); CHECK(ConstantExpr::getZExt(P0, Int64Ty), "zext i32 " P0STR " to i64"); CHECK(ConstantExpr::getFPTrunc(P2, FloatTy), "fptrunc double " P2STR " to float"); CHECK(ConstantExpr::getFPExtend(P1, DoubleTy), "fpext float " P1STR " to double"); CHECK(ConstantExpr::getExactUDiv(P0, P0), "udiv exact i32 " P0STR ", " P0STR); CHECK(ConstantExpr::getSelect(P3, P0, P4), "select i1 " P3STR ", i32 " P0STR ", i32 " P4STR); CHECK(ConstantExpr::getICmp(CmpInst::ICMP_EQ, P0, P4), "icmp eq i32 " P0STR ", " P4STR); CHECK(ConstantExpr::getFCmp(CmpInst::FCMP_ULT, P1, P5), "fcmp ult float " P1STR ", " P5STR); std::vector<Constant*> V; V.push_back(One); // FIXME: getGetElementPtr() actually creates an inbounds ConstantGEP, // not a normal one! //CHECK(ConstantExpr::getGetElementPtr(Global, V, false), // "getelementptr i32*, i32** @dummy, i32 1"); CHECK(ConstantExpr::getInBoundsGetElementPtr(PointerType::getUnqual(Int32Ty), Global, V), "getelementptr inbounds i32*, i32** @dummy, i32 1"); CHECK(ConstantExpr::getExtractElement(P6, One), "extractelement <2 x i16> " P6STR ", i32 1"); EXPECT_EQ(Undef16, ConstantExpr::getExtractElement(P6, Two)); EXPECT_EQ(Undef16, ConstantExpr::getExtractElement(P6, Big)); EXPECT_EQ(Undef16, ConstantExpr::getExtractElement(P6, Undef64)); EXPECT_EQ(Elt, ConstantExpr::getExtractElement( ConstantExpr::getInsertElement(P6, Elt, One), One)); EXPECT_EQ(UndefV16, ConstantExpr::getInsertElement(P6, Elt, Two)); EXPECT_EQ(UndefV16, ConstantExpr::getInsertElement(P6, Elt, Big)); EXPECT_EQ(UndefV16, ConstantExpr::getInsertElement(P6, Elt, Undef64)); } #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG TEST(ConstantsTest, ReplaceWithConstantTest) { std::unique_ptr<Module> M(new Module("MyModule", getGlobalContext())); Type *Int32Ty = Type::getInt32Ty(getGlobalContext()); Constant *One = ConstantInt::get(Int32Ty, 1); Constant *Global = M->getOrInsertGlobal("dummy", PointerType::getUnqual(Int32Ty)); Constant *GEP = ConstantExpr::getGetElementPtr( PointerType::getUnqual(Int32Ty), Global, One); EXPECT_DEATH(Global->replaceAllUsesWith(GEP), "this->replaceAllUsesWith\\(expr\\(this\\)\\) is NOT valid!"); } #endif #endif #undef CHECK TEST(ConstantsTest, ConstantArrayReplaceWithConstant) { LLVMContext Context; std::unique_ptr<Module> M(new Module("MyModule", Context)); Type *IntTy = Type::getInt8Ty(Context); ArrayType *ArrayTy = ArrayType::get(IntTy, 2); Constant *A01Vals[2] = {ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1)}; Constant *A01 = ConstantArray::get(ArrayTy, A01Vals); Constant *Global = new GlobalVariable(*M, IntTy, false, GlobalValue::ExternalLinkage, nullptr); Constant *GlobalInt = ConstantExpr::getPtrToInt(Global, IntTy); Constant *A0GVals[2] = {ConstantInt::get(IntTy, 0), GlobalInt}; Constant *A0G = ConstantArray::get(ArrayTy, A0GVals); ASSERT_NE(A01, A0G); GlobalVariable *RefArray = new GlobalVariable(*M, ArrayTy, false, GlobalValue::ExternalLinkage, A0G); ASSERT_EQ(A0G, RefArray->getInitializer()); GlobalInt->replaceAllUsesWith(ConstantInt::get(IntTy, 1)); ASSERT_EQ(A01, RefArray->getInitializer()); } TEST(ConstantsTest, ConstantExprReplaceWithConstant) { LLVMContext Context; std::unique_ptr<Module> M(new Module("MyModule", Context)); Type *IntTy = Type::getInt8Ty(Context); Constant *G1 = new GlobalVariable(*M, IntTy, false, GlobalValue::ExternalLinkage, nullptr); Constant *G2 = new GlobalVariable(*M, IntTy, false, GlobalValue::ExternalLinkage, nullptr); ASSERT_NE(G1, G2); Constant *Int1 = ConstantExpr::getPtrToInt(G1, IntTy); Constant *Int2 = ConstantExpr::getPtrToInt(G2, IntTy); ASSERT_NE(Int1, Int2); GlobalVariable *Ref = new GlobalVariable(*M, IntTy, false, GlobalValue::ExternalLinkage, Int1); ASSERT_EQ(Int1, Ref->getInitializer()); G1->replaceAllUsesWith(G2); ASSERT_EQ(Int2, Ref->getInitializer()); } TEST(ConstantsTest, GEPReplaceWithConstant) { LLVMContext Context; std::unique_ptr<Module> M(new Module("MyModule", Context)); Type *IntTy = Type::getInt32Ty(Context); auto *PtrTy = PointerType::get(IntTy, 0); auto *C1 = ConstantInt::get(IntTy, 1); auto *Placeholder = new GlobalVariable( *M, IntTy, false, GlobalValue::ExternalWeakLinkage, nullptr); auto *GEP = ConstantExpr::getGetElementPtr(IntTy, Placeholder, C1); ASSERT_EQ(GEP->getOperand(0), Placeholder); auto *Ref = new GlobalVariable(*M, PtrTy, false, GlobalValue::ExternalLinkage, GEP); ASSERT_EQ(GEP, Ref->getInitializer()); auto *Global = new GlobalVariable(*M, PtrTy, false, GlobalValue::ExternalLinkage, nullptr); auto *Alias = GlobalAlias::create(PtrTy, GlobalValue::ExternalLinkage, "alias", Global, M.get()); Placeholder->replaceAllUsesWith(Alias); ASSERT_EQ(GEP, Ref->getInitializer()); ASSERT_EQ(GEP->getOperand(0), Alias); } TEST(ConstantsTest, AliasCAPI) { LLVMContext Context; SMDiagnostic Error; std::unique_ptr<Module> M = parseAssemblyString("@g = global i32 42", Error, Context); GlobalVariable *G = M->getGlobalVariable("g"); Type *I16Ty = Type::getInt16Ty(Context); Type *I16PTy = PointerType::get(I16Ty, 0); Constant *Aliasee = ConstantExpr::getBitCast(G, I16PTy); LLVMValueRef AliasRef = LLVMAddAlias(wrap(M.get()), wrap(I16PTy), wrap(Aliasee), "a"); ASSERT_EQ(unwrap<GlobalAlias>(AliasRef)->getAliasee(), Aliasee); } } // end anonymous namespace } // end namespace llvm
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/DebugInfo/CMakeLists.txt
add_subdirectory(DWARF) add_subdirectory(PDB)
0
repos/DirectXShaderCompiler/unittests/DebugInfo
repos/DirectXShaderCompiler/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp
//===- llvm/unittest/DebugInfo/DWARFFormValueTest.cpp ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/Host.h" #include "llvm/Support/LEB128.h" #include "gtest/gtest.h" #include <climits> using namespace llvm; using namespace dwarf; namespace { TEST(DWARFFormValue, FixedFormSizes) { // Size of DW_FORM_addr and DW_FORM_ref_addr are equal in DWARF2, // DW_FORM_ref_addr is always 4 bytes in DWARF32 starting from DWARF3. ArrayRef<uint8_t> sizes = DWARFFormValue::getFixedFormSizes(4, 2); EXPECT_EQ(sizes[DW_FORM_addr], sizes[DW_FORM_ref_addr]); sizes = DWARFFormValue::getFixedFormSizes(8, 2); EXPECT_EQ(sizes[DW_FORM_addr], sizes[DW_FORM_ref_addr]); sizes = DWARFFormValue::getFixedFormSizes(8, 3); EXPECT_EQ(4, sizes[DW_FORM_ref_addr]); // Check that we don't have fixed form sizes for weird address sizes. EXPECT_EQ(0U, DWARFFormValue::getFixedFormSizes(16, 2).size()); } bool isFormClass(uint16_t Form, DWARFFormValue::FormClass FC) { return DWARFFormValue(Form).isFormClass(FC); } TEST(DWARFFormValue, FormClass) { EXPECT_TRUE(isFormClass(DW_FORM_addr, DWARFFormValue::FC_Address)); EXPECT_FALSE(isFormClass(DW_FORM_data8, DWARFFormValue::FC_Address)); EXPECT_TRUE(isFormClass(DW_FORM_data8, DWARFFormValue::FC_Constant)); EXPECT_TRUE(isFormClass(DW_FORM_data8, DWARFFormValue::FC_SectionOffset)); EXPECT_TRUE( isFormClass(DW_FORM_sec_offset, DWARFFormValue::FC_SectionOffset)); EXPECT_TRUE(isFormClass(DW_FORM_GNU_str_index, DWARFFormValue::FC_String)); EXPECT_TRUE(isFormClass(DW_FORM_GNU_addr_index, DWARFFormValue::FC_Address)); EXPECT_FALSE(isFormClass(DW_FORM_ref_addr, DWARFFormValue::FC_Address)); EXPECT_TRUE(isFormClass(DW_FORM_ref_addr, DWARFFormValue::FC_Reference)); EXPECT_TRUE(isFormClass(DW_FORM_ref_sig8, DWARFFormValue::FC_Reference)); } template<typename RawTypeT> DWARFFormValue createDataXFormValue(uint16_t Form, RawTypeT Value) { char Raw[sizeof(RawTypeT)]; memcpy(Raw, &Value, sizeof(RawTypeT)); uint32_t Offset = 0; DWARFFormValue Result(Form); DataExtractor Data(StringRef(Raw, sizeof(RawTypeT)), sys::IsLittleEndianHost, sizeof(void*)); Result.extractValue(Data, &Offset, nullptr); return Result; } DWARFFormValue createULEBFormValue(uint64_t Value) { SmallString<10> RawData; raw_svector_ostream OS(RawData); encodeULEB128(Value, OS); uint32_t Offset = 0; DWARFFormValue Result(DW_FORM_udata); DataExtractor Data(OS.str(), sys::IsLittleEndianHost, sizeof(void*)); Result.extractValue(Data, &Offset, nullptr); return Result; } DWARFFormValue createSLEBFormValue(int64_t Value) { SmallString<10> RawData; raw_svector_ostream OS(RawData); encodeSLEB128(Value, OS); uint32_t Offset = 0; DWARFFormValue Result(DW_FORM_sdata); DataExtractor Data(OS.str(), sys::IsLittleEndianHost, sizeof(void*)); Result.extractValue(Data, &Offset, nullptr); return Result; } TEST(DWARFFormValue, SignedConstantForms) { // Check that we correctly sign extend fixed size forms. auto Sign1 = createDataXFormValue<uint8_t>(DW_FORM_data1, -123); auto Sign2 = createDataXFormValue<uint16_t>(DW_FORM_data2, -12345); auto Sign4 = createDataXFormValue<uint32_t>(DW_FORM_data4, -123456789); auto Sign8 = createDataXFormValue<uint64_t>(DW_FORM_data8, -1); EXPECT_EQ(Sign1.getAsSignedConstant().getValue(), -123); EXPECT_EQ(Sign2.getAsSignedConstant().getValue(), -12345); EXPECT_EQ(Sign4.getAsSignedConstant().getValue(), -123456789); EXPECT_EQ(Sign8.getAsSignedConstant().getValue(), -1); // Check that we can handle big positive values, but that we return // an error just over the limit. auto UMax = createULEBFormValue(LLONG_MAX); auto TooBig = createULEBFormValue(uint64_t(LLONG_MAX) + 1); EXPECT_EQ(UMax.getAsSignedConstant().getValue(), LLONG_MAX); EXPECT_EQ(TooBig.getAsSignedConstant().hasValue(), false); // Sanity check some other forms. auto Data1 = createDataXFormValue<uint8_t>(DW_FORM_data1, 120); auto Data2 = createDataXFormValue<uint16_t>(DW_FORM_data2, 32000); auto Data4 = createDataXFormValue<uint32_t>(DW_FORM_data4, 2000000000); auto Data8 = createDataXFormValue<uint64_t>(DW_FORM_data8, 0x1234567812345678LL); auto LEBMin = createSLEBFormValue(LLONG_MIN); auto LEBMax = createSLEBFormValue(LLONG_MAX); auto LEB1 = createSLEBFormValue(-42); auto LEB2 = createSLEBFormValue(42); EXPECT_EQ(Data1.getAsSignedConstant().getValue(), 120); EXPECT_EQ(Data2.getAsSignedConstant().getValue(), 32000); EXPECT_EQ(Data4.getAsSignedConstant().getValue(), 2000000000); EXPECT_EQ(Data8.getAsSignedConstant().getValue(), 0x1234567812345678LL); EXPECT_EQ(LEBMin.getAsSignedConstant().getValue(), LLONG_MIN); EXPECT_EQ(LEBMax.getAsSignedConstant().getValue(), LLONG_MAX); EXPECT_EQ(LEB1.getAsSignedConstant().getValue(), -42); EXPECT_EQ(LEB2.getAsSignedConstant().getValue(), 42); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests/DebugInfo
repos/DirectXShaderCompiler/unittests/DebugInfo/DWARF/CMakeLists.txt
set(LLVM_LINK_COMPONENTS DebugInfoDWARF ) set(DebugInfoSources DWARFFormValueTest.cpp ) add_llvm_unittest(DebugInfoDWARFTests ${DebugInfoSources} )
0
repos/DirectXShaderCompiler/unittests/DebugInfo
repos/DirectXShaderCompiler/unittests/DebugInfo/PDB/PDBApiTest.cpp
//===- llvm/unittest/DebugInfo/PDB/PDBApiTest.cpp -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <unordered_map> #include "llvm/ADT/STLExtras.h" #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" #include "llvm/DebugInfo/PDB/IPDBRawSymbol.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/IPDBSourceFile.h" #include "llvm/DebugInfo/PDB/PDBSymbol.h" #include "llvm/DebugInfo/PDB/PDBSymbolAnnotation.h" #include "llvm/DebugInfo/PDB/PDBSymbolBlock.h" #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h" #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h" #include "llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h" #include "llvm/DebugInfo/PDB/PDBSymbolCustom.h" #include "llvm/DebugInfo/PDB/PDBSymbolData.h" #include "llvm/DebugInfo/PDB/PDBSymbolExe.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h" #include "llvm/DebugInfo/PDB/PDBSymbolLabel.h" #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h" #include "llvm/DebugInfo/PDB/PDBSymbolThunk.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h" #include "llvm/DebugInfo/PDB/PDBSymbolUnknown.h" #include "llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h" #include "llvm/DebugInfo/PDB/PDBTypes.h" #include "gtest/gtest.h" using namespace llvm; namespace { #define MOCK_SYMBOL_ACCESSOR(Func) \ decltype(std::declval<IPDBRawSymbol>().Func()) Func() const override { \ typedef decltype(IPDBRawSymbol::Func()) ReturnType; \ return ReturnType(); \ } class MockSession : public IPDBSession { uint64_t getLoadAddress() const override { return 0; } void setLoadAddress(uint64_t Address) override {} std::unique_ptr<PDBSymbolExe> getGlobalScope() const override { return nullptr; } std::unique_ptr<PDBSymbol> getSymbolById(uint32_t SymbolId) const override { return nullptr; } std::unique_ptr<IPDBSourceFile> getSourceFileById(uint32_t SymbolId) const override { return nullptr; } std::unique_ptr<PDBSymbol> findSymbolByAddress(uint64_t Address, PDB_SymType Type) const override { return nullptr; } std::unique_ptr<IPDBEnumLineNumbers> findLineNumbersByAddress(uint64_t Address, uint32_t Length) const override { return nullptr; } std::unique_ptr<IPDBEnumSourceFiles> getAllSourceFiles() const override { return nullptr; } std::unique_ptr<IPDBEnumSourceFiles> getSourceFilesForCompiland( const PDBSymbolCompiland &Compiland) const override { return nullptr; } std::unique_ptr<IPDBEnumDataStreams> getDebugStreams() const override { return nullptr; } }; class MockRawSymbol : public IPDBRawSymbol { public: MockRawSymbol(PDB_SymType SymType) : Type(SymType) {} void dump(raw_ostream &OS, int Indent) const override {} std::unique_ptr<IPDBEnumSymbols> findChildren(PDB_SymType Type) const override { return nullptr; } std::unique_ptr<IPDBEnumSymbols> findChildren(PDB_SymType Type, StringRef Name, PDB_NameSearchFlags Flags) const override { return nullptr; } std::unique_ptr<IPDBEnumSymbols> findChildrenByRVA(PDB_SymType Type, StringRef Name, PDB_NameSearchFlags Flags, uint32_t RVA) const override { return nullptr; } std::unique_ptr<IPDBEnumSymbols> findInlineFramesByRVA(uint32_t RVA) const override { return nullptr; } void getDataBytes(llvm::SmallVector<uint8_t, 32> &bytes) const override {} void getFrontEndVersion(VersionInfo &Version) const override {} void getBackEndVersion(VersionInfo &Version) const override {} PDB_SymType getSymTag() const override { return Type; } MOCK_SYMBOL_ACCESSOR(getAccess) MOCK_SYMBOL_ACCESSOR(getAddressOffset) MOCK_SYMBOL_ACCESSOR(getAddressSection) MOCK_SYMBOL_ACCESSOR(getAge) MOCK_SYMBOL_ACCESSOR(getArrayIndexTypeId) MOCK_SYMBOL_ACCESSOR(getBaseDataOffset) MOCK_SYMBOL_ACCESSOR(getBaseDataSlot) MOCK_SYMBOL_ACCESSOR(getBaseSymbolId) MOCK_SYMBOL_ACCESSOR(getBuiltinType) MOCK_SYMBOL_ACCESSOR(getBitPosition) MOCK_SYMBOL_ACCESSOR(getCallingConvention) MOCK_SYMBOL_ACCESSOR(getClassParentId) MOCK_SYMBOL_ACCESSOR(getCompilerName) MOCK_SYMBOL_ACCESSOR(getCount) MOCK_SYMBOL_ACCESSOR(getCountLiveRanges) MOCK_SYMBOL_ACCESSOR(getLanguage) MOCK_SYMBOL_ACCESSOR(getLexicalParentId) MOCK_SYMBOL_ACCESSOR(getLibraryName) MOCK_SYMBOL_ACCESSOR(getLiveRangeStartAddressOffset) MOCK_SYMBOL_ACCESSOR(getLiveRangeStartAddressSection) MOCK_SYMBOL_ACCESSOR(getLiveRangeStartRelativeVirtualAddress) MOCK_SYMBOL_ACCESSOR(getLocalBasePointerRegisterId) MOCK_SYMBOL_ACCESSOR(getLowerBoundId) MOCK_SYMBOL_ACCESSOR(getMemorySpaceKind) MOCK_SYMBOL_ACCESSOR(getName) MOCK_SYMBOL_ACCESSOR(getNumberOfAcceleratorPointerTags) MOCK_SYMBOL_ACCESSOR(getNumberOfColumns) MOCK_SYMBOL_ACCESSOR(getNumberOfModifiers) MOCK_SYMBOL_ACCESSOR(getNumberOfRegisterIndices) MOCK_SYMBOL_ACCESSOR(getNumberOfRows) MOCK_SYMBOL_ACCESSOR(getObjectFileName) MOCK_SYMBOL_ACCESSOR(getOemId) MOCK_SYMBOL_ACCESSOR(getOemSymbolId) MOCK_SYMBOL_ACCESSOR(getOffsetInUdt) MOCK_SYMBOL_ACCESSOR(getPlatform) MOCK_SYMBOL_ACCESSOR(getRank) MOCK_SYMBOL_ACCESSOR(getRegisterId) MOCK_SYMBOL_ACCESSOR(getRegisterType) MOCK_SYMBOL_ACCESSOR(getRelativeVirtualAddress) MOCK_SYMBOL_ACCESSOR(getSamplerSlot) MOCK_SYMBOL_ACCESSOR(getSignature) MOCK_SYMBOL_ACCESSOR(getSizeInUdt) MOCK_SYMBOL_ACCESSOR(getSlot) MOCK_SYMBOL_ACCESSOR(getSourceFileName) MOCK_SYMBOL_ACCESSOR(getStride) MOCK_SYMBOL_ACCESSOR(getSubTypeId) MOCK_SYMBOL_ACCESSOR(getSymbolsFileName) MOCK_SYMBOL_ACCESSOR(getSymIndexId) MOCK_SYMBOL_ACCESSOR(getTargetOffset) MOCK_SYMBOL_ACCESSOR(getTargetRelativeVirtualAddress) MOCK_SYMBOL_ACCESSOR(getTargetVirtualAddress) MOCK_SYMBOL_ACCESSOR(getTargetSection) MOCK_SYMBOL_ACCESSOR(getTextureSlot) MOCK_SYMBOL_ACCESSOR(getTimeStamp) MOCK_SYMBOL_ACCESSOR(getToken) MOCK_SYMBOL_ACCESSOR(getTypeId) MOCK_SYMBOL_ACCESSOR(getUavSlot) MOCK_SYMBOL_ACCESSOR(getUndecoratedName) MOCK_SYMBOL_ACCESSOR(getUnmodifiedTypeId) MOCK_SYMBOL_ACCESSOR(getUpperBoundId) MOCK_SYMBOL_ACCESSOR(getVirtualBaseDispIndex) MOCK_SYMBOL_ACCESSOR(getVirtualBaseOffset) MOCK_SYMBOL_ACCESSOR(getVirtualTableShapeId) MOCK_SYMBOL_ACCESSOR(getDataKind) MOCK_SYMBOL_ACCESSOR(getGuid) MOCK_SYMBOL_ACCESSOR(getOffset) MOCK_SYMBOL_ACCESSOR(getThisAdjust) MOCK_SYMBOL_ACCESSOR(getVirtualBasePointerOffset) MOCK_SYMBOL_ACCESSOR(getLocationType) MOCK_SYMBOL_ACCESSOR(getMachineType) MOCK_SYMBOL_ACCESSOR(getThunkOrdinal) MOCK_SYMBOL_ACCESSOR(getLength) MOCK_SYMBOL_ACCESSOR(getLiveRangeLength) MOCK_SYMBOL_ACCESSOR(getVirtualAddress) MOCK_SYMBOL_ACCESSOR(getUdtKind) MOCK_SYMBOL_ACCESSOR(hasConstructor) MOCK_SYMBOL_ACCESSOR(hasCustomCallingConvention) MOCK_SYMBOL_ACCESSOR(hasFarReturn) MOCK_SYMBOL_ACCESSOR(isCode) MOCK_SYMBOL_ACCESSOR(isCompilerGenerated) MOCK_SYMBOL_ACCESSOR(isConstType) MOCK_SYMBOL_ACCESSOR(isEditAndContinueEnabled) MOCK_SYMBOL_ACCESSOR(isFunction) MOCK_SYMBOL_ACCESSOR(getAddressTaken) MOCK_SYMBOL_ACCESSOR(getNoStackOrdering) MOCK_SYMBOL_ACCESSOR(hasAlloca) MOCK_SYMBOL_ACCESSOR(hasAssignmentOperator) MOCK_SYMBOL_ACCESSOR(hasCTypes) MOCK_SYMBOL_ACCESSOR(hasCastOperator) MOCK_SYMBOL_ACCESSOR(hasDebugInfo) MOCK_SYMBOL_ACCESSOR(hasEH) MOCK_SYMBOL_ACCESSOR(hasEHa) MOCK_SYMBOL_ACCESSOR(hasFramePointer) MOCK_SYMBOL_ACCESSOR(hasInlAsm) MOCK_SYMBOL_ACCESSOR(hasInlineAttribute) MOCK_SYMBOL_ACCESSOR(hasInterruptReturn) MOCK_SYMBOL_ACCESSOR(hasLongJump) MOCK_SYMBOL_ACCESSOR(hasManagedCode) MOCK_SYMBOL_ACCESSOR(hasNestedTypes) MOCK_SYMBOL_ACCESSOR(hasNoInlineAttribute) MOCK_SYMBOL_ACCESSOR(hasNoReturnAttribute) MOCK_SYMBOL_ACCESSOR(hasOptimizedCodeDebugInfo) MOCK_SYMBOL_ACCESSOR(hasOverloadedOperator) MOCK_SYMBOL_ACCESSOR(hasSEH) MOCK_SYMBOL_ACCESSOR(hasSecurityChecks) MOCK_SYMBOL_ACCESSOR(hasSetJump) MOCK_SYMBOL_ACCESSOR(hasStrictGSCheck) MOCK_SYMBOL_ACCESSOR(isAcceleratorGroupSharedLocal) MOCK_SYMBOL_ACCESSOR(isAcceleratorPointerTagLiveRange) MOCK_SYMBOL_ACCESSOR(isAcceleratorStubFunction) MOCK_SYMBOL_ACCESSOR(isAggregated) MOCK_SYMBOL_ACCESSOR(isIntroVirtualFunction) MOCK_SYMBOL_ACCESSOR(isCVTCIL) MOCK_SYMBOL_ACCESSOR(isConstructorVirtualBase) MOCK_SYMBOL_ACCESSOR(isCxxReturnUdt) MOCK_SYMBOL_ACCESSOR(isDataAligned) MOCK_SYMBOL_ACCESSOR(isHLSLData) MOCK_SYMBOL_ACCESSOR(isHotpatchable) MOCK_SYMBOL_ACCESSOR(isIndirectVirtualBaseClass) MOCK_SYMBOL_ACCESSOR(isInterfaceUdt) MOCK_SYMBOL_ACCESSOR(isIntrinsic) MOCK_SYMBOL_ACCESSOR(isLTCG) MOCK_SYMBOL_ACCESSOR(isLocationControlFlowDependent) MOCK_SYMBOL_ACCESSOR(isMSILNetmodule) MOCK_SYMBOL_ACCESSOR(isMatrixRowMajor) MOCK_SYMBOL_ACCESSOR(isManagedCode) MOCK_SYMBOL_ACCESSOR(isMSILCode) MOCK_SYMBOL_ACCESSOR(isMultipleInheritance) MOCK_SYMBOL_ACCESSOR(isNaked) MOCK_SYMBOL_ACCESSOR(isNested) MOCK_SYMBOL_ACCESSOR(isOptimizedAway) MOCK_SYMBOL_ACCESSOR(isPacked) MOCK_SYMBOL_ACCESSOR(isPointerBasedOnSymbolValue) MOCK_SYMBOL_ACCESSOR(isPointerToDataMember) MOCK_SYMBOL_ACCESSOR(isPointerToMemberFunction) MOCK_SYMBOL_ACCESSOR(isPureVirtual) MOCK_SYMBOL_ACCESSOR(isRValueReference) MOCK_SYMBOL_ACCESSOR(isRefUdt) MOCK_SYMBOL_ACCESSOR(isReference) MOCK_SYMBOL_ACCESSOR(isRestrictedType) MOCK_SYMBOL_ACCESSOR(isReturnValue) MOCK_SYMBOL_ACCESSOR(isSafeBuffers) MOCK_SYMBOL_ACCESSOR(isScoped) MOCK_SYMBOL_ACCESSOR(isSdl) MOCK_SYMBOL_ACCESSOR(isSingleInheritance) MOCK_SYMBOL_ACCESSOR(isSplitted) MOCK_SYMBOL_ACCESSOR(isStatic) MOCK_SYMBOL_ACCESSOR(hasPrivateSymbols) MOCK_SYMBOL_ACCESSOR(isUnalignedType) MOCK_SYMBOL_ACCESSOR(isUnreached) MOCK_SYMBOL_ACCESSOR(isValueUdt) MOCK_SYMBOL_ACCESSOR(isVirtual) MOCK_SYMBOL_ACCESSOR(isVirtualBaseClass) MOCK_SYMBOL_ACCESSOR(isVirtualInheritance) MOCK_SYMBOL_ACCESSOR(isVolatileType) MOCK_SYMBOL_ACCESSOR(getValue) MOCK_SYMBOL_ACCESSOR(wasInlined) MOCK_SYMBOL_ACCESSOR(getUnused) private: PDB_SymType Type; }; class PDBApiTest : public testing::Test { public: std::unordered_map<PDB_SymType, std::unique_ptr<PDBSymbol>> SymbolMap; void SetUp() override { Session.reset(new MockSession()); InsertItemWithTag(PDB_SymType::None); InsertItemWithTag(PDB_SymType::Exe); InsertItemWithTag(PDB_SymType::Compiland); InsertItemWithTag(PDB_SymType::CompilandDetails); InsertItemWithTag(PDB_SymType::CompilandEnv); InsertItemWithTag(PDB_SymType::Function); InsertItemWithTag(PDB_SymType::Block); InsertItemWithTag(PDB_SymType::Data); InsertItemWithTag(PDB_SymType::Annotation); InsertItemWithTag(PDB_SymType::Label); InsertItemWithTag(PDB_SymType::PublicSymbol); InsertItemWithTag(PDB_SymType::UDT); InsertItemWithTag(PDB_SymType::Enum); InsertItemWithTag(PDB_SymType::FunctionSig); InsertItemWithTag(PDB_SymType::PointerType); InsertItemWithTag(PDB_SymType::ArrayType); InsertItemWithTag(PDB_SymType::BuiltinType); InsertItemWithTag(PDB_SymType::Typedef); InsertItemWithTag(PDB_SymType::BaseClass); InsertItemWithTag(PDB_SymType::Friend); InsertItemWithTag(PDB_SymType::FunctionArg); InsertItemWithTag(PDB_SymType::FuncDebugStart); InsertItemWithTag(PDB_SymType::FuncDebugEnd); InsertItemWithTag(PDB_SymType::UsingNamespace); InsertItemWithTag(PDB_SymType::VTableShape); InsertItemWithTag(PDB_SymType::VTable); InsertItemWithTag(PDB_SymType::Custom); InsertItemWithTag(PDB_SymType::Thunk); InsertItemWithTag(PDB_SymType::CustomType); InsertItemWithTag(PDB_SymType::ManagedType); InsertItemWithTag(PDB_SymType::Dimension); InsertItemWithTag(PDB_SymType::Max); } template <class ExpectedType> void VerifyDyncast(PDB_SymType Tag) { for (auto item = SymbolMap.begin(); item != SymbolMap.end(); ++item) { EXPECT_EQ(item->first == Tag, llvm::isa<ExpectedType>(*item->second)); } } void VerifyUnknownDyncasts() { for (auto item = SymbolMap.begin(); item != SymbolMap.end(); ++item) { bool should_match = false; if (item->first == PDB_SymType::None || item->first >= PDB_SymType::Max) should_match = true; EXPECT_EQ(should_match, llvm::isa<PDBSymbolUnknown>(*item->second)); } } private: std::unique_ptr<IPDBSession> Session; void InsertItemWithTag(PDB_SymType Tag) { auto RawSymbol = llvm::make_unique<MockRawSymbol>(Tag); auto Symbol = PDBSymbol::create(*Session, std::move(RawSymbol)); SymbolMap.insert(std::make_pair(Tag, std::move(Symbol))); } }; TEST_F(PDBApiTest, Dyncast) { // Most of the types have a one-to-one mapping between Tag and concrete type. VerifyDyncast<PDBSymbolExe>(PDB_SymType::Exe); VerifyDyncast<PDBSymbolCompiland>(PDB_SymType::Compiland); VerifyDyncast<PDBSymbolCompilandDetails>(PDB_SymType::CompilandDetails); VerifyDyncast<PDBSymbolCompilandEnv>(PDB_SymType::CompilandEnv); VerifyDyncast<PDBSymbolFunc>(PDB_SymType::Function); VerifyDyncast<PDBSymbolBlock>(PDB_SymType::Block); VerifyDyncast<PDBSymbolData>(PDB_SymType::Data); VerifyDyncast<PDBSymbolAnnotation>(PDB_SymType::Annotation); VerifyDyncast<PDBSymbolLabel>(PDB_SymType::Label); VerifyDyncast<PDBSymbolPublicSymbol>(PDB_SymType::PublicSymbol); VerifyDyncast<PDBSymbolTypeUDT>(PDB_SymType::UDT); VerifyDyncast<PDBSymbolTypeEnum>(PDB_SymType::Enum); VerifyDyncast<PDBSymbolTypeFunctionSig>(PDB_SymType::FunctionSig); VerifyDyncast<PDBSymbolTypePointer>(PDB_SymType::PointerType); VerifyDyncast<PDBSymbolTypeArray>(PDB_SymType::ArrayType); VerifyDyncast<PDBSymbolTypeBuiltin>(PDB_SymType::BuiltinType); VerifyDyncast<PDBSymbolTypeTypedef>(PDB_SymType::Typedef); VerifyDyncast<PDBSymbolTypeBaseClass>(PDB_SymType::BaseClass); VerifyDyncast<PDBSymbolTypeFriend>(PDB_SymType::Friend); VerifyDyncast<PDBSymbolTypeFunctionArg>(PDB_SymType::FunctionArg); VerifyDyncast<PDBSymbolFuncDebugStart>(PDB_SymType::FuncDebugStart); VerifyDyncast<PDBSymbolFuncDebugEnd>(PDB_SymType::FuncDebugEnd); VerifyDyncast<PDBSymbolUsingNamespace>(PDB_SymType::UsingNamespace); VerifyDyncast<PDBSymbolTypeVTableShape>(PDB_SymType::VTableShape); VerifyDyncast<PDBSymbolTypeVTable>(PDB_SymType::VTable); VerifyDyncast<PDBSymbolCustom>(PDB_SymType::Custom); VerifyDyncast<PDBSymbolThunk>(PDB_SymType::Thunk); VerifyDyncast<PDBSymbolTypeCustom>(PDB_SymType::CustomType); VerifyDyncast<PDBSymbolTypeManaged>(PDB_SymType::ManagedType); VerifyDyncast<PDBSymbolTypeDimension>(PDB_SymType::Dimension); VerifyUnknownDyncasts(); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests/DebugInfo
repos/DirectXShaderCompiler/unittests/DebugInfo/PDB/CMakeLists.txt
set(LLVM_LINK_COMPONENTS DebugInfoPDB ) set(DebugInfoPDBSources PDBApiTest.cpp ) add_llvm_unittest(DebugInfoPDBTests ${DebugInfoPDBSources} )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/DxilHash/DxilHashTest.cpp
//===- unittests/DxilHash/DxilHashTest.cpp ---- Run DxilHash tests --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // DxilHashing.h unit tests. // //===----------------------------------------------------------------------===// using BYTE = unsigned char; using UINT32 = unsigned int; #include "dxc/DxilHash/DxilHash.h" #include "gtest/gtest.h" namespace { struct OutputHash { BYTE Data[DXIL_CONTAINER_HASH_SIZE]; bool equal(UINT32 A, UINT32 B, UINT32 C, UINT32 D) { UINT32 *DataPtr = (UINT32 *)Data; return DataPtr[0] == A && DataPtr[1] == B && DataPtr[2] == C && DataPtr[3] == D; } }; bool operator==(const OutputHash &A, const OutputHash &B) { return memcmp(&A, &B, sizeof(OutputHash)) == 0; } bool operator!=(const OutputHash &A, const OutputHash &B) { return memcmp(&A, &B, sizeof(OutputHash)) != 0; } template <typename T> OutputHash hash_value(T Input) { OutputHash O; ComputeHashRetail((const BYTE *)&Input, sizeof(T), (BYTE *)&O); return O; } template <> OutputHash hash_value<std::string>(std::string S) { OutputHash O; ComputeHashRetail((const BYTE *)S.data(), S.size(), (BYTE *)&O); return O; } enum TestEnumeration { TE_Foo = 42, TE_Bar = 43 }; TEST(DxilHashTest, HashValueBasicTest) { int x = 42, y = 43, c = 'x'; void *p = nullptr; uint64_t i = 71; const unsigned ci = 71; volatile int vi = 71; const volatile int cvi = 71; uintptr_t addr = reinterpret_cast<uintptr_t>(&y); EXPECT_EQ(hash_value(42), hash_value(x)); EXPECT_EQ(hash_value(42), hash_value(TE_Foo)); EXPECT_NE(hash_value(42), hash_value(y)); EXPECT_NE(hash_value(42), hash_value(TE_Bar)); EXPECT_NE(hash_value(42), hash_value(p)); EXPECT_EQ(hash_value(71), hash_value(ci)); EXPECT_EQ(hash_value(71), hash_value(vi)); EXPECT_EQ(hash_value(71), hash_value(cvi)); EXPECT_EQ(hash_value(addr), hash_value(&y)); // Miss match for type mismatch. EXPECT_NE(hash_value(71), hash_value(i)); EXPECT_NE(hash_value(c), hash_value('x')); EXPECT_NE(hash_value('4'), hash_value('0' + 4)); std::string strA = "42"; std::string strB = ""; std::string strC = "42"; EXPECT_NE(hash_value(strA), hash_value(strB)); EXPECT_EQ(hash_value(strA), hash_value(strC)); } TEST(DxilHashTest, FixHashValueTest) { std::string Data = ""; EXPECT_EQ( hash_value(Data).equal(0xf6600d14, 0xbae275b7, 0xd4be4a4e, 0xa1e9b201), true); std::string Data2 = "abcdefghijklmnopqrstuvwxyzabcdef" "abcdefghijklmnopqrstuvwxyzghijkl" "abcdefghijklmnopqrstuvwxyzmnopqr" "abcdefghijklmnopqrstuvwxyzstuvwx" "abcdefghijklmnopqrstuvwxyzyzabcd"; EXPECT_EQ( hash_value(Data2).equal(0x00830fe6, 0xd8d8a035, 0xe6d62794, 0x016629df), true); std::string Data3 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; EXPECT_EQ( hash_value(Data3).equal(0xa5e5a0bb, 0xd96dd9f8, 0x0b4b7191, 0xd63aa54a), true); std::string Data4 = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"; EXPECT_EQ( hash_value(Data4).equal(0x58ed1b7a, 0x90ede58b, 0xf9ad857c, 0x5440e613), true); std::string Data5 = "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab" "abababababababababababababababab"; EXPECT_EQ( hash_value(Data5).equal(0xf4fc06fc, 0x0bbd9ef7, 0x765ae0f7, 0x52a55925), true); } } // namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/DxilHash/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Support DxilHash ) add_clang_unittest(DxilHashTests DxilHashTest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Analysis/CallGraphTest.cpp
//=======- CallGraphTest.cpp - Unit tests for the CG analysis -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/CallGraph.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "gtest/gtest.h" using namespace llvm; namespace { template <typename Ty> void canSpecializeGraphTraitsIterators(Ty *G) { typedef typename GraphTraits<Ty *>::NodeType NodeTy; auto I = GraphTraits<Ty *>::nodes_begin(G); auto E = GraphTraits<Ty *>::nodes_end(G); auto X = ++I; // Should be able to iterate over all nodes of the graph. // HLSL - Changed iterators to unique_tr, requiring extra deference static_assert(std::is_same<decltype(**I), NodeTy &>::value, "Node type does not match"); static_assert(std::is_same<decltype(**X), NodeTy &>::value, "Node type does not match"); static_assert(std::is_same<decltype(**E), NodeTy &>::value, "Node type does not match"); NodeTy *N = GraphTraits<Ty *>::getEntryNode(G); auto S = GraphTraits<NodeTy *>::child_begin(N); auto F = GraphTraits<NodeTy *>::child_end(N); // Should be able to iterate over immediate successors of a node. static_assert(std::is_same<decltype(*S), NodeTy *>::value, "Node type does not match"); static_assert(std::is_same<decltype(*F), NodeTy *>::value, "Node type does not match"); } TEST(CallGraphTest, GraphTraitsSpecialization) { Module M("", getGlobalContext()); CallGraph CG(M); canSpecializeGraphTraitsIterators(&CG); } TEST(CallGraphTest, GraphTraitsConstSpecialization) { Module M("", getGlobalContext()); CallGraph CG(M); canSpecializeGraphTraitsIterators(const_cast<const CallGraph *>(&CG)); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Analysis/AliasAnalysisTest.cpp
//===--- AliasAnalysisTest.cpp - Mixed TBAA unit tests --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Support/CommandLine.h" #include "gtest/gtest.h" namespace llvm { namespace { class AliasAnalysisTest : public testing::Test { protected: AliasAnalysisTest() : M("AliasAnalysisTBAATest", C) {} // This is going to check that calling getModRefInfo without a location, and // with a default location, first, doesn't crash, and second, gives the right // answer. void CheckModRef(Instruction *I, AliasAnalysis::ModRefResult Result) { static char ID; class CheckModRefTestPass : public FunctionPass { public: CheckModRefTestPass(Instruction *I, AliasAnalysis::ModRefResult Result) : FunctionPass(ID), ExpectResult(Result), I(I) {} static int initialize() { PassInfo *PI = new PassInfo("CheckModRef testing pass", "", &ID, nullptr, true, true); PassRegistry::getPassRegistry()->registerPass(*PI, false); initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry()); initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry()); return 0; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); AU.addRequiredTransitive<AliasAnalysis>(); } bool runOnFunction(Function &) override { AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); EXPECT_EQ(AA.getModRefInfo(I, MemoryLocation()), ExpectResult); EXPECT_EQ(AA.getModRefInfo(I), ExpectResult); return false; } AliasAnalysis::ModRefResult ExpectResult; Instruction *I; }; static int initialize = CheckModRefTestPass::initialize(); (void)initialize; CheckModRefTestPass *P = new CheckModRefTestPass(I, Result); legacy::PassManager PM; PM.add(createBasicAliasAnalysisPass()); PM.add(P); PM.run(M); } LLVMContext C; Module M; }; TEST_F(AliasAnalysisTest, getModRefInfo) { // Setup function. FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), std::vector<Type *>(), false); auto *F = cast<Function>(M.getOrInsertFunction("f", FTy)); auto *BB = BasicBlock::Create(C, "entry", F); auto IntType = Type::getInt32Ty(C); auto PtrType = Type::getInt32PtrTy(C); auto *Value = ConstantInt::get(IntType, 42); auto *Addr = ConstantPointerNull::get(PtrType); auto *Store1 = new StoreInst(Value, Addr, BB); auto *Load1 = new LoadInst(Addr, "load", BB); auto *Add1 = BinaryOperator::CreateAdd(Value, Value, "add", BB); auto *VAArg1 = new VAArgInst(Addr, PtrType, "vaarg", BB); auto *CmpXChg1 = new AtomicCmpXchgInst(Addr, ConstantInt::get(IntType, 0), ConstantInt::get(IntType, 1), Monotonic, Monotonic, CrossThread, BB); auto *AtomicRMW = new AtomicRMWInst(AtomicRMWInst::Xchg, Addr, ConstantInt::get(IntType, 1), Monotonic, CrossThread, BB); ReturnInst::Create(C, nullptr, BB); // Check basic results CheckModRef(Store1, AliasAnalysis::ModRefResult::Mod); CheckModRef(Load1, AliasAnalysis::ModRefResult::Ref); CheckModRef(Add1, AliasAnalysis::ModRefResult::NoModRef); CheckModRef(VAArg1, AliasAnalysis::ModRefResult::ModRef); CheckModRef(CmpXChg1, AliasAnalysis::ModRefResult::ModRef); CheckModRef(AtomicRMW, AliasAnalysis::ModRefResult::ModRef); } } // end anonymous namspace } // end llvm namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Analysis/MixedTBAATest.cpp
//===--- MixedTBAATest.cpp - Mixed TBAA unit tests ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/Passes.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Support/CommandLine.h" #include "gtest/gtest.h" namespace llvm { namespace { class MixedTBAATest : public testing::Test { protected: MixedTBAATest() : M("MixedTBAATest", C), MD(C) {} LLVMContext C; Module M; MDBuilder MD; legacy::PassManager PM; }; TEST_F(MixedTBAATest, MixedTBAA) { // Setup function. FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), std::vector<Type *>(), false); auto *F = cast<Function>(M.getOrInsertFunction("f", FTy)); auto *BB = BasicBlock::Create(C, "entry", F); auto IntType = Type::getInt32Ty(C); auto PtrType = Type::getInt32PtrTy(C); auto *Value = ConstantInt::get(IntType, 42); auto *Addr = ConstantPointerNull::get(PtrType); auto *Store1 = new StoreInst(Value, Addr, BB); auto *Store2 = new StoreInst(Value, Addr, BB); ReturnInst::Create(C, nullptr, BB); // New TBAA metadata { auto RootMD = MD.createTBAARoot("Simple C/C++ TBAA"); auto MD1 = MD.createTBAAScalarTypeNode("omnipotent char", RootMD); auto MD2 = MD.createTBAAScalarTypeNode("int", MD1); auto MD3 = MD.createTBAAStructTagNode(MD2, MD2, 0); Store2->setMetadata(LLVMContext::MD_tbaa, MD3); } // Old TBAA metadata { auto RootMD = MD.createTBAARoot("Simple C/C++ TBAA"); auto MD1 = MD.createTBAANode("omnipotent char", RootMD); auto MD2 = MD.createTBAANode("int", MD1); Store1->setMetadata(LLVMContext::MD_tbaa, MD2); } // Run the TBAA eval pass on a mixture of path-aware and non-path-aware TBAA. // The order of the metadata (path-aware vs non-path-aware) is important, // because the AA eval pass only runs one test per store-pair. const char* args[] = { "MixedTBAATest", "-evaluate-aa-metadata" }; cl::ParseCommandLineOptions(sizeof(args) / sizeof(const char*), args); PM.add(createTypeBasedAliasAnalysisPass()); PM.add(createAAEvalPass()); PM.run(M); } } // end anonymous namspace } // end llvm namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Analysis/ScalarEvolutionTest.cpp
//===- ScalarEvolutionsTest.cpp - ScalarEvolution unit tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/LegacyPassManager.h" #include "gtest/gtest.h" namespace llvm { namespace { // We use this fixture to ensure that we clean up ScalarEvolution before // deleting the PassManager. class ScalarEvolutionsTest : public testing::Test { protected: ScalarEvolutionsTest() : M("", Context), SE(*new ScalarEvolution) {} ~ScalarEvolutionsTest() override { // Manually clean up, since we allocated new SCEV objects after the // pass was finished. SE.releaseMemory(); } LLVMContext Context; Module M; legacy::PassManager PM; ScalarEvolution &SE; }; TEST_F(ScalarEvolutionsTest, SCEVUnknownRAUW) { FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), std::vector<Type *>(), false); Function *F = cast<Function>(M.getOrInsertFunction("f", FTy)); BasicBlock *BB = BasicBlock::Create(Context, "entry", F); ReturnInst::Create(Context, nullptr, BB); Type *Ty = Type::getInt1Ty(Context); Constant *Init = Constant::getNullValue(Ty); Value *V0 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V0"); Value *V1 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V1"); Value *V2 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V2"); // Create a ScalarEvolution and "run" it so that it gets initialized. PM.add(&SE); PM.run(M); const SCEV *S0 = SE.getSCEV(V0); const SCEV *S1 = SE.getSCEV(V1); const SCEV *S2 = SE.getSCEV(V2); const SCEV *P0 = SE.getAddExpr(S0, S0); const SCEV *P1 = SE.getAddExpr(S1, S1); const SCEV *P2 = SE.getAddExpr(S2, S2); const SCEVMulExpr *M0 = cast<SCEVMulExpr>(P0); const SCEVMulExpr *M1 = cast<SCEVMulExpr>(P1); const SCEVMulExpr *M2 = cast<SCEVMulExpr>(P2); EXPECT_EQ(cast<SCEVConstant>(M0->getOperand(0))->getValue()->getZExtValue(), 2u); EXPECT_EQ(cast<SCEVConstant>(M1->getOperand(0))->getValue()->getZExtValue(), 2u); EXPECT_EQ(cast<SCEVConstant>(M2->getOperand(0))->getValue()->getZExtValue(), 2u); // Before the RAUWs, these are all pointing to separate values. EXPECT_EQ(cast<SCEVUnknown>(M0->getOperand(1))->getValue(), V0); EXPECT_EQ(cast<SCEVUnknown>(M1->getOperand(1))->getValue(), V1); EXPECT_EQ(cast<SCEVUnknown>(M2->getOperand(1))->getValue(), V2); // Do some RAUWs. V2->replaceAllUsesWith(V1); V1->replaceAllUsesWith(V0); // After the RAUWs, these should all be pointing to V0. EXPECT_EQ(cast<SCEVUnknown>(M0->getOperand(1))->getValue(), V0); EXPECT_EQ(cast<SCEVUnknown>(M1->getOperand(1))->getValue(), V0); EXPECT_EQ(cast<SCEVUnknown>(M2->getOperand(1))->getValue(), V0); } TEST_F(ScalarEvolutionsTest, SCEVMultiplyAddRecs) { Type *Ty = Type::getInt32Ty(Context); SmallVector<Type *, 10> Types; Types.append(10, Ty); FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), Types, false); Function *F = cast<Function>(M.getOrInsertFunction("f", FTy)); BasicBlock *BB = BasicBlock::Create(Context, "entry", F); ReturnInst::Create(Context, nullptr, BB); // Create a ScalarEvolution and "run" it so that it gets initialized. PM.add(&SE); PM.run(M); // It's possible to produce an empty loop through the default constructor, // but you can't add any blocks to it without a LoopInfo pass. Loop L; const_cast<std::vector<BasicBlock*>&>(L.getBlocks()).push_back(BB); Function::arg_iterator AI = F->arg_begin(); SmallVector<const SCEV *, 5> A; A.push_back(SE.getSCEV(&*AI++)); A.push_back(SE.getSCEV(&*AI++)); A.push_back(SE.getSCEV(&*AI++)); A.push_back(SE.getSCEV(&*AI++)); A.push_back(SE.getSCEV(&*AI++)); const SCEV *A_rec = SE.getAddRecExpr(A, &L, SCEV::FlagAnyWrap); SmallVector<const SCEV *, 5> B; B.push_back(SE.getSCEV(&*AI++)); B.push_back(SE.getSCEV(&*AI++)); B.push_back(SE.getSCEV(&*AI++)); B.push_back(SE.getSCEV(&*AI++)); B.push_back(SE.getSCEV(&*AI++)); const SCEV *B_rec = SE.getAddRecExpr(B, &L, SCEV::FlagAnyWrap); /* Spot check that we perform this transformation: {A0,+,A1,+,A2,+,A3,+,A4} * {B0,+,B1,+,B2,+,B3,+,B4} = {A0*B0,+, A1*B0 + A0*B1 + A1*B1,+, A2*B0 + 2A1*B1 + A0*B2 + 2A2*B1 + 2A1*B2 + A2*B2,+, A3*B0 + 3A2*B1 + 3A1*B2 + A0*B3 + 3A3*B1 + 6A2*B2 + 3A1*B3 + 3A3*B2 + 3A2*B3 + A3*B3,+, A4*B0 + 4A3*B1 + 6A2*B2 + 4A1*B3 + A0*B4 + 4A4*B1 + 12A3*B2 + 12A2*B3 + 4A1*B4 + 6A4*B2 + 12A3*B3 + 6A2*B4 + 4A4*B3 + 4A3*B4 + A4*B4,+, 5A4*B1 + 10A3*B2 + 10A2*B3 + 5A1*B4 + 20A4*B2 + 30A3*B3 + 20A2*B4 + 30A4*B3 + 30A3*B4 + 20A4*B4,+, 15A4*B2 + 20A3*B3 + 15A2*B4 + 60A4*B3 + 60A3*B4 + 90A4*B4,+, 35A4*B3 + 35A3*B4 + 140A4*B4,+, 70A4*B4} */ const SCEVAddRecExpr *Product = dyn_cast<SCEVAddRecExpr>(SE.getMulExpr(A_rec, B_rec)); ASSERT_TRUE(Product); ASSERT_EQ(Product->getNumOperands(), 9u); SmallVector<const SCEV *, 16> Sum; Sum.push_back(SE.getMulExpr(A[0], B[0])); EXPECT_EQ(Product->getOperand(0), SE.getAddExpr(Sum)); Sum.clear(); // SCEV produces different an equal but different expression for these. // Re-enable when PR11052 is fixed. #if 0 Sum.push_back(SE.getMulExpr(A[1], B[0])); Sum.push_back(SE.getMulExpr(A[0], B[1])); Sum.push_back(SE.getMulExpr(A[1], B[1])); EXPECT_EQ(Product->getOperand(1), SE.getAddExpr(Sum)); Sum.clear(); Sum.push_back(SE.getMulExpr(A[2], B[0])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 2), A[1], B[1])); Sum.push_back(SE.getMulExpr(A[0], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 2), A[2], B[1])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 2), A[1], B[2])); Sum.push_back(SE.getMulExpr(A[2], B[2])); EXPECT_EQ(Product->getOperand(2), SE.getAddExpr(Sum)); Sum.clear(); Sum.push_back(SE.getMulExpr(A[3], B[0])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 3), A[2], B[1])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 3), A[1], B[2])); Sum.push_back(SE.getMulExpr(A[0], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 3), A[3], B[1])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 6), A[2], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 3), A[1], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 3), A[3], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 3), A[2], B[3])); Sum.push_back(SE.getMulExpr(A[3], B[3])); EXPECT_EQ(Product->getOperand(3), SE.getAddExpr(Sum)); Sum.clear(); Sum.push_back(SE.getMulExpr(A[4], B[0])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 4), A[3], B[1])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 6), A[2], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 4), A[1], B[3])); Sum.push_back(SE.getMulExpr(A[0], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 4), A[4], B[1])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 12), A[3], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 12), A[2], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 4), A[1], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 6), A[4], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 12), A[3], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 6), A[2], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 4), A[4], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 4), A[3], B[4])); Sum.push_back(SE.getMulExpr(A[4], B[4])); EXPECT_EQ(Product->getOperand(4), SE.getAddExpr(Sum)); Sum.clear(); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 5), A[4], B[1])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 10), A[3], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 10), A[2], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 5), A[1], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 20), A[4], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 30), A[3], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 20), A[2], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 30), A[4], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 30), A[3], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 20), A[4], B[4])); EXPECT_EQ(Product->getOperand(5), SE.getAddExpr(Sum)); Sum.clear(); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 15), A[4], B[2])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 20), A[3], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 15), A[2], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 60), A[4], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 60), A[3], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 90), A[4], B[4])); EXPECT_EQ(Product->getOperand(6), SE.getAddExpr(Sum)); Sum.clear(); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 35), A[4], B[3])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 35), A[3], B[4])); Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 140), A[4], B[4])); EXPECT_EQ(Product->getOperand(7), SE.getAddExpr(Sum)); Sum.clear(); #endif Sum.push_back(SE.getMulExpr(SE.getConstant(Ty, 70), A[4], B[4])); EXPECT_EQ(Product->getOperand(8), SE.getAddExpr(Sum)); } } // end anonymous namespace } // end namespace llvm
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Analysis/LazyCallGraphTest.cpp
//===- LazyCallGraphTest.cpp - Unit tests for the lazy CG analysis --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LazyCallGraph.h" #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Function.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" #include <memory> using namespace llvm; namespace { std::unique_ptr<Module> parseAssembly(const char *Assembly) { SMDiagnostic Error; std::unique_ptr<Module> M = parseAssemblyString(Assembly, Error, getGlobalContext()); std::string ErrMsg; raw_string_ostream OS(ErrMsg); Error.print("", OS); // A failure here means that the test itself is buggy. if (!M) report_fatal_error(OS.str().c_str()); return M; } /* IR forming a call graph with a diamond of triangle-shaped SCCs: d1 / \ d3--d2 / \ b1 c1 / \ / \ b3--b2 c3--c2 \ / a1 / \ a3--a2 All call edges go up between SCCs, and clockwise around the SCC. */ static const char DiamondOfTriangles[] = "define void @a1() {\n" "entry:\n" " call void @a2()\n" " call void @b2()\n" " call void @c3()\n" " ret void\n" "}\n" "define void @a2() {\n" "entry:\n" " call void @a3()\n" " ret void\n" "}\n" "define void @a3() {\n" "entry:\n" " call void @a1()\n" " ret void\n" "}\n" "define void @b1() {\n" "entry:\n" " call void @b2()\n" " call void @d3()\n" " ret void\n" "}\n" "define void @b2() {\n" "entry:\n" " call void @b3()\n" " ret void\n" "}\n" "define void @b3() {\n" "entry:\n" " call void @b1()\n" " ret void\n" "}\n" "define void @c1() {\n" "entry:\n" " call void @c2()\n" " call void @d2()\n" " ret void\n" "}\n" "define void @c2() {\n" "entry:\n" " call void @c3()\n" " ret void\n" "}\n" "define void @c3() {\n" "entry:\n" " call void @c1()\n" " ret void\n" "}\n" "define void @d1() {\n" "entry:\n" " call void @d2()\n" " ret void\n" "}\n" "define void @d2() {\n" "entry:\n" " call void @d3()\n" " ret void\n" "}\n" "define void @d3() {\n" "entry:\n" " call void @d1()\n" " ret void\n" "}\n"; TEST(LazyCallGraphTest, BasicGraphFormation) { std::unique_ptr<Module> M = parseAssembly(DiamondOfTriangles); LazyCallGraph CG(*M); // The order of the entry nodes should be stable w.r.t. the source order of // the IR, and everything in our module is an entry node, so just directly // build variables for each node. auto I = CG.begin(); LazyCallGraph::Node &A1 = *I++; EXPECT_EQ("a1", A1.getFunction().getName()); LazyCallGraph::Node &A2 = *I++; EXPECT_EQ("a2", A2.getFunction().getName()); LazyCallGraph::Node &A3 = *I++; EXPECT_EQ("a3", A3.getFunction().getName()); LazyCallGraph::Node &B1 = *I++; EXPECT_EQ("b1", B1.getFunction().getName()); LazyCallGraph::Node &B2 = *I++; EXPECT_EQ("b2", B2.getFunction().getName()); LazyCallGraph::Node &B3 = *I++; EXPECT_EQ("b3", B3.getFunction().getName()); LazyCallGraph::Node &C1 = *I++; EXPECT_EQ("c1", C1.getFunction().getName()); LazyCallGraph::Node &C2 = *I++; EXPECT_EQ("c2", C2.getFunction().getName()); LazyCallGraph::Node &C3 = *I++; EXPECT_EQ("c3", C3.getFunction().getName()); LazyCallGraph::Node &D1 = *I++; EXPECT_EQ("d1", D1.getFunction().getName()); LazyCallGraph::Node &D2 = *I++; EXPECT_EQ("d2", D2.getFunction().getName()); LazyCallGraph::Node &D3 = *I++; EXPECT_EQ("d3", D3.getFunction().getName()); EXPECT_EQ(CG.end(), I); // Build vectors and sort them for the rest of the assertions to make them // independent of order. std::vector<std::string> Nodes; for (LazyCallGraph::Node &N : A1) Nodes.push_back(N.getFunction().getName()); std::sort(Nodes.begin(), Nodes.end()); EXPECT_EQ("a2", Nodes[0]); EXPECT_EQ("b2", Nodes[1]); EXPECT_EQ("c3", Nodes[2]); Nodes.clear(); EXPECT_EQ(A2.end(), std::next(A2.begin())); EXPECT_EQ("a3", A2.begin()->getFunction().getName()); EXPECT_EQ(A3.end(), std::next(A3.begin())); EXPECT_EQ("a1", A3.begin()->getFunction().getName()); for (LazyCallGraph::Node &N : B1) Nodes.push_back(N.getFunction().getName()); std::sort(Nodes.begin(), Nodes.end()); EXPECT_EQ("b2", Nodes[0]); EXPECT_EQ("d3", Nodes[1]); Nodes.clear(); EXPECT_EQ(B2.end(), std::next(B2.begin())); EXPECT_EQ("b3", B2.begin()->getFunction().getName()); EXPECT_EQ(B3.end(), std::next(B3.begin())); EXPECT_EQ("b1", B3.begin()->getFunction().getName()); for (LazyCallGraph::Node &N : C1) Nodes.push_back(N.getFunction().getName()); std::sort(Nodes.begin(), Nodes.end()); EXPECT_EQ("c2", Nodes[0]); EXPECT_EQ("d2", Nodes[1]); Nodes.clear(); EXPECT_EQ(C2.end(), std::next(C2.begin())); EXPECT_EQ("c3", C2.begin()->getFunction().getName()); EXPECT_EQ(C3.end(), std::next(C3.begin())); EXPECT_EQ("c1", C3.begin()->getFunction().getName()); EXPECT_EQ(D1.end(), std::next(D1.begin())); EXPECT_EQ("d2", D1.begin()->getFunction().getName()); EXPECT_EQ(D2.end(), std::next(D2.begin())); EXPECT_EQ("d3", D2.begin()->getFunction().getName()); EXPECT_EQ(D3.end(), std::next(D3.begin())); EXPECT_EQ("d1", D3.begin()->getFunction().getName()); // Now lets look at the SCCs. auto SCCI = CG.postorder_scc_begin(); LazyCallGraph::SCC &D = *SCCI++; for (LazyCallGraph::Node *N : D) Nodes.push_back(N->getFunction().getName()); std::sort(Nodes.begin(), Nodes.end()); EXPECT_EQ(3u, Nodes.size()); EXPECT_EQ("d1", Nodes[0]); EXPECT_EQ("d2", Nodes[1]); EXPECT_EQ("d3", Nodes[2]); Nodes.clear(); EXPECT_FALSE(D.isParentOf(D)); EXPECT_FALSE(D.isChildOf(D)); EXPECT_FALSE(D.isAncestorOf(D)); EXPECT_FALSE(D.isDescendantOf(D)); LazyCallGraph::SCC &C = *SCCI++; for (LazyCallGraph::Node *N : C) Nodes.push_back(N->getFunction().getName()); std::sort(Nodes.begin(), Nodes.end()); EXPECT_EQ(3u, Nodes.size()); EXPECT_EQ("c1", Nodes[0]); EXPECT_EQ("c2", Nodes[1]); EXPECT_EQ("c3", Nodes[2]); Nodes.clear(); EXPECT_TRUE(C.isParentOf(D)); EXPECT_FALSE(C.isChildOf(D)); EXPECT_TRUE(C.isAncestorOf(D)); EXPECT_FALSE(C.isDescendantOf(D)); LazyCallGraph::SCC &B = *SCCI++; for (LazyCallGraph::Node *N : B) Nodes.push_back(N->getFunction().getName()); std::sort(Nodes.begin(), Nodes.end()); EXPECT_EQ(3u, Nodes.size()); EXPECT_EQ("b1", Nodes[0]); EXPECT_EQ("b2", Nodes[1]); EXPECT_EQ("b3", Nodes[2]); Nodes.clear(); EXPECT_TRUE(B.isParentOf(D)); EXPECT_FALSE(B.isChildOf(D)); EXPECT_TRUE(B.isAncestorOf(D)); EXPECT_FALSE(B.isDescendantOf(D)); EXPECT_FALSE(B.isAncestorOf(C)); EXPECT_FALSE(C.isAncestorOf(B)); LazyCallGraph::SCC &A = *SCCI++; for (LazyCallGraph::Node *N : A) Nodes.push_back(N->getFunction().getName()); std::sort(Nodes.begin(), Nodes.end()); EXPECT_EQ(3u, Nodes.size()); EXPECT_EQ("a1", Nodes[0]); EXPECT_EQ("a2", Nodes[1]); EXPECT_EQ("a3", Nodes[2]); Nodes.clear(); EXPECT_TRUE(A.isParentOf(B)); EXPECT_TRUE(A.isParentOf(C)); EXPECT_FALSE(A.isParentOf(D)); EXPECT_TRUE(A.isAncestorOf(B)); EXPECT_TRUE(A.isAncestorOf(C)); EXPECT_TRUE(A.isAncestorOf(D)); EXPECT_EQ(CG.postorder_scc_end(), SCCI); } static Function &lookupFunction(Module &M, StringRef Name) { for (Function &F : M) if (F.getName() == Name) return F; report_fatal_error("Couldn't find function!"); } TEST(LazyCallGraphTest, BasicGraphMutation) { std::unique_ptr<Module> M = parseAssembly( "define void @a() {\n" "entry:\n" " call void @b()\n" " call void @c()\n" " ret void\n" "}\n" "define void @b() {\n" "entry:\n" " ret void\n" "}\n" "define void @c() {\n" "entry:\n" " ret void\n" "}\n"); LazyCallGraph CG(*M); LazyCallGraph::Node &A = CG.get(lookupFunction(*M, "a")); LazyCallGraph::Node &B = CG.get(lookupFunction(*M, "b")); EXPECT_EQ(2, std::distance(A.begin(), A.end())); EXPECT_EQ(0, std::distance(B.begin(), B.end())); CG.insertEdge(B, lookupFunction(*M, "c")); EXPECT_EQ(1, std::distance(B.begin(), B.end())); LazyCallGraph::Node &C = *B.begin(); EXPECT_EQ(0, std::distance(C.begin(), C.end())); CG.insertEdge(C, B.getFunction()); EXPECT_EQ(1, std::distance(C.begin(), C.end())); EXPECT_EQ(&B, &*C.begin()); CG.insertEdge(C, C.getFunction()); EXPECT_EQ(2, std::distance(C.begin(), C.end())); EXPECT_EQ(&B, &*C.begin()); EXPECT_EQ(&C, &*std::next(C.begin())); CG.removeEdge(C, B.getFunction()); EXPECT_EQ(1, std::distance(C.begin(), C.end())); EXPECT_EQ(&C, &*C.begin()); CG.removeEdge(C, C.getFunction()); EXPECT_EQ(0, std::distance(C.begin(), C.end())); CG.removeEdge(B, C.getFunction()); EXPECT_EQ(0, std::distance(B.begin(), B.end())); } TEST(LazyCallGraphTest, MultiArmSCC) { // Two interlocking cycles. The really useful thing about this SCC is that it // will require Tarjan's DFS to backtrack and finish processing all of the // children of each node in the SCC. std::unique_ptr<Module> M = parseAssembly( "define void @a() {\n" "entry:\n" " call void @b()\n" " call void @d()\n" " ret void\n" "}\n" "define void @b() {\n" "entry:\n" " call void @c()\n" " ret void\n" "}\n" "define void @c() {\n" "entry:\n" " call void @a()\n" " ret void\n" "}\n" "define void @d() {\n" "entry:\n" " call void @e()\n" " ret void\n" "}\n" "define void @e() {\n" "entry:\n" " call void @a()\n" " ret void\n" "}\n"); LazyCallGraph CG(*M); // Force the graph to be fully expanded. auto SCCI = CG.postorder_scc_begin(); LazyCallGraph::SCC &SCC = *SCCI++; EXPECT_EQ(CG.postorder_scc_end(), SCCI); LazyCallGraph::Node &A = *CG.lookup(lookupFunction(*M, "a")); LazyCallGraph::Node &B = *CG.lookup(lookupFunction(*M, "b")); LazyCallGraph::Node &C = *CG.lookup(lookupFunction(*M, "c")); LazyCallGraph::Node &D = *CG.lookup(lookupFunction(*M, "d")); LazyCallGraph::Node &E = *CG.lookup(lookupFunction(*M, "e")); EXPECT_EQ(&SCC, CG.lookupSCC(A)); EXPECT_EQ(&SCC, CG.lookupSCC(B)); EXPECT_EQ(&SCC, CG.lookupSCC(C)); EXPECT_EQ(&SCC, CG.lookupSCC(D)); EXPECT_EQ(&SCC, CG.lookupSCC(E)); } TEST(LazyCallGraphTest, OutgoingSCCEdgeInsertion) { std::unique_ptr<Module> M = parseAssembly( "define void @a() {\n" "entry:\n" " call void @b()\n" " call void @c()\n" " ret void\n" "}\n" "define void @b() {\n" "entry:\n" " call void @d()\n" " ret void\n" "}\n" "define void @c() {\n" "entry:\n" " call void @d()\n" " ret void\n" "}\n" "define void @d() {\n" "entry:\n" " ret void\n" "}\n"); LazyCallGraph CG(*M); // Force the graph to be fully expanded. for (LazyCallGraph::SCC &C : CG.postorder_sccs()) (void)C; LazyCallGraph::Node &A = *CG.lookup(lookupFunction(*M, "a")); LazyCallGraph::Node &B = *CG.lookup(lookupFunction(*M, "b")); LazyCallGraph::Node &C = *CG.lookup(lookupFunction(*M, "c")); LazyCallGraph::Node &D = *CG.lookup(lookupFunction(*M, "d")); LazyCallGraph::SCC &AC = *CG.lookupSCC(A); LazyCallGraph::SCC &BC = *CG.lookupSCC(B); LazyCallGraph::SCC &CC = *CG.lookupSCC(C); LazyCallGraph::SCC &DC = *CG.lookupSCC(D); EXPECT_TRUE(AC.isAncestorOf(BC)); EXPECT_TRUE(AC.isAncestorOf(CC)); EXPECT_TRUE(AC.isAncestorOf(DC)); EXPECT_TRUE(DC.isDescendantOf(AC)); EXPECT_TRUE(DC.isDescendantOf(BC)); EXPECT_TRUE(DC.isDescendantOf(CC)); EXPECT_EQ(2, std::distance(A.begin(), A.end())); AC.insertOutgoingEdge(A, D); EXPECT_EQ(3, std::distance(A.begin(), A.end())); EXPECT_TRUE(AC.isParentOf(DC)); EXPECT_EQ(&AC, CG.lookupSCC(A)); EXPECT_EQ(&BC, CG.lookupSCC(B)); EXPECT_EQ(&CC, CG.lookupSCC(C)); EXPECT_EQ(&DC, CG.lookupSCC(D)); } TEST(LazyCallGraphTest, IncomingSCCEdgeInsertion) { // We want to ensure we can add edges even across complex diamond graphs, so // we use the diamond of triangles graph defined above. The ascii diagram is // repeated here for easy reference. // // d1 | // / \ | // d3--d2 | // / \ | // b1 c1 | // / \ / \ | // b3--b2 c3--c2 | // \ / | // a1 | // / \ | // a3--a2 | // std::unique_ptr<Module> M = parseAssembly(DiamondOfTriangles); LazyCallGraph CG(*M); // Force the graph to be fully expanded. for (LazyCallGraph::SCC &C : CG.postorder_sccs()) (void)C; LazyCallGraph::Node &A1 = *CG.lookup(lookupFunction(*M, "a1")); LazyCallGraph::Node &A2 = *CG.lookup(lookupFunction(*M, "a2")); LazyCallGraph::Node &A3 = *CG.lookup(lookupFunction(*M, "a3")); LazyCallGraph::Node &B1 = *CG.lookup(lookupFunction(*M, "b1")); LazyCallGraph::Node &B2 = *CG.lookup(lookupFunction(*M, "b2")); LazyCallGraph::Node &B3 = *CG.lookup(lookupFunction(*M, "b3")); LazyCallGraph::Node &C1 = *CG.lookup(lookupFunction(*M, "c1")); LazyCallGraph::Node &C2 = *CG.lookup(lookupFunction(*M, "c2")); LazyCallGraph::Node &C3 = *CG.lookup(lookupFunction(*M, "c3")); LazyCallGraph::Node &D1 = *CG.lookup(lookupFunction(*M, "d1")); LazyCallGraph::Node &D2 = *CG.lookup(lookupFunction(*M, "d2")); LazyCallGraph::Node &D3 = *CG.lookup(lookupFunction(*M, "d3")); LazyCallGraph::SCC &AC = *CG.lookupSCC(A1); LazyCallGraph::SCC &BC = *CG.lookupSCC(B1); LazyCallGraph::SCC &CC = *CG.lookupSCC(C1); LazyCallGraph::SCC &DC = *CG.lookupSCC(D1); ASSERT_EQ(&AC, CG.lookupSCC(A2)); ASSERT_EQ(&AC, CG.lookupSCC(A3)); ASSERT_EQ(&BC, CG.lookupSCC(B2)); ASSERT_EQ(&BC, CG.lookupSCC(B3)); ASSERT_EQ(&CC, CG.lookupSCC(C2)); ASSERT_EQ(&CC, CG.lookupSCC(C3)); ASSERT_EQ(&DC, CG.lookupSCC(D2)); ASSERT_EQ(&DC, CG.lookupSCC(D3)); ASSERT_EQ(1, std::distance(D2.begin(), D2.end())); // Add an edge to make the graph: // // d1 | // / \ | // d3--d2---. | // / \ | | // b1 c1 | | // / \ / \ / | // b3--b2 c3--c2 | // \ / | // a1 | // / \ | // a3--a2 | CC.insertIncomingEdge(D2, C2); // Make sure we connected the nodes. EXPECT_EQ(2, std::distance(D2.begin(), D2.end())); // Make sure we have the correct nodes in the SCC sets. EXPECT_EQ(&AC, CG.lookupSCC(A1)); EXPECT_EQ(&AC, CG.lookupSCC(A2)); EXPECT_EQ(&AC, CG.lookupSCC(A3)); EXPECT_EQ(&BC, CG.lookupSCC(B1)); EXPECT_EQ(&BC, CG.lookupSCC(B2)); EXPECT_EQ(&BC, CG.lookupSCC(B3)); EXPECT_EQ(&CC, CG.lookupSCC(C1)); EXPECT_EQ(&CC, CG.lookupSCC(C2)); EXPECT_EQ(&CC, CG.lookupSCC(C3)); EXPECT_EQ(&CC, CG.lookupSCC(D1)); EXPECT_EQ(&CC, CG.lookupSCC(D2)); EXPECT_EQ(&CC, CG.lookupSCC(D3)); // And that ancestry tests have been updated. EXPECT_TRUE(AC.isParentOf(BC)); EXPECT_TRUE(AC.isParentOf(CC)); EXPECT_FALSE(AC.isAncestorOf(DC)); EXPECT_FALSE(BC.isAncestorOf(DC)); EXPECT_FALSE(CC.isAncestorOf(DC)); } TEST(LazyCallGraphTest, IncomingSCCEdgeInsertionMidTraversal) { // This is the same fundamental test as the previous, but we perform it // having only partially walked the SCCs of the graph. std::unique_ptr<Module> M = parseAssembly(DiamondOfTriangles); LazyCallGraph CG(*M); // Walk the SCCs until we find the one containing 'c1'. auto SCCI = CG.postorder_scc_begin(), SCCE = CG.postorder_scc_end(); ASSERT_NE(SCCI, SCCE); LazyCallGraph::SCC &DC = *SCCI; ASSERT_NE(&DC, nullptr); ++SCCI; ASSERT_NE(SCCI, SCCE); LazyCallGraph::SCC &CC = *SCCI; ASSERT_NE(&CC, nullptr); ASSERT_EQ(nullptr, CG.lookup(lookupFunction(*M, "a1"))); ASSERT_EQ(nullptr, CG.lookup(lookupFunction(*M, "a2"))); ASSERT_EQ(nullptr, CG.lookup(lookupFunction(*M, "a3"))); ASSERT_EQ(nullptr, CG.lookup(lookupFunction(*M, "b1"))); ASSERT_EQ(nullptr, CG.lookup(lookupFunction(*M, "b2"))); ASSERT_EQ(nullptr, CG.lookup(lookupFunction(*M, "b3"))); LazyCallGraph::Node &C1 = *CG.lookup(lookupFunction(*M, "c1")); LazyCallGraph::Node &C2 = *CG.lookup(lookupFunction(*M, "c2")); LazyCallGraph::Node &C3 = *CG.lookup(lookupFunction(*M, "c3")); LazyCallGraph::Node &D1 = *CG.lookup(lookupFunction(*M, "d1")); LazyCallGraph::Node &D2 = *CG.lookup(lookupFunction(*M, "d2")); LazyCallGraph::Node &D3 = *CG.lookup(lookupFunction(*M, "d3")); ASSERT_EQ(&CC, CG.lookupSCC(C1)); ASSERT_EQ(&CC, CG.lookupSCC(C2)); ASSERT_EQ(&CC, CG.lookupSCC(C3)); ASSERT_EQ(&DC, CG.lookupSCC(D1)); ASSERT_EQ(&DC, CG.lookupSCC(D2)); ASSERT_EQ(&DC, CG.lookupSCC(D3)); ASSERT_EQ(1, std::distance(D2.begin(), D2.end())); CC.insertIncomingEdge(D2, C2); EXPECT_EQ(2, std::distance(D2.begin(), D2.end())); // Make sure we have the correct nodes in the SCC sets. EXPECT_EQ(&CC, CG.lookupSCC(C1)); EXPECT_EQ(&CC, CG.lookupSCC(C2)); EXPECT_EQ(&CC, CG.lookupSCC(C3)); EXPECT_EQ(&CC, CG.lookupSCC(D1)); EXPECT_EQ(&CC, CG.lookupSCC(D2)); EXPECT_EQ(&CC, CG.lookupSCC(D3)); // Check that we can form the last two SCCs now in a coherent way. ++SCCI; EXPECT_NE(SCCI, SCCE); LazyCallGraph::SCC &BC = *SCCI; EXPECT_NE(&BC, nullptr); EXPECT_EQ(&BC, CG.lookupSCC(*CG.lookup(lookupFunction(*M, "b1")))); EXPECT_EQ(&BC, CG.lookupSCC(*CG.lookup(lookupFunction(*M, "b2")))); EXPECT_EQ(&BC, CG.lookupSCC(*CG.lookup(lookupFunction(*M, "b3")))); ++SCCI; EXPECT_NE(SCCI, SCCE); LazyCallGraph::SCC &AC = *SCCI; EXPECT_NE(&AC, nullptr); EXPECT_EQ(&AC, CG.lookupSCC(*CG.lookup(lookupFunction(*M, "a1")))); EXPECT_EQ(&AC, CG.lookupSCC(*CG.lookup(lookupFunction(*M, "a2")))); EXPECT_EQ(&AC, CG.lookupSCC(*CG.lookup(lookupFunction(*M, "a3")))); ++SCCI; EXPECT_EQ(SCCI, SCCE); } TEST(LazyCallGraphTest, InterSCCEdgeRemoval) { std::unique_ptr<Module> M = parseAssembly( "define void @a() {\n" "entry:\n" " call void @b()\n" " ret void\n" "}\n" "define void @b() {\n" "entry:\n" " ret void\n" "}\n"); LazyCallGraph CG(*M); // Force the graph to be fully expanded. for (LazyCallGraph::SCC &C : CG.postorder_sccs()) (void)C; LazyCallGraph::Node &A = *CG.lookup(lookupFunction(*M, "a")); LazyCallGraph::Node &B = *CG.lookup(lookupFunction(*M, "b")); LazyCallGraph::SCC &AC = *CG.lookupSCC(A); LazyCallGraph::SCC &BC = *CG.lookupSCC(B); EXPECT_EQ("b", A.begin()->getFunction().getName()); EXPECT_EQ(B.end(), B.begin()); EXPECT_EQ(&AC, &*BC.parent_begin()); AC.removeInterSCCEdge(A, B); EXPECT_EQ(A.end(), A.begin()); EXPECT_EQ(B.end(), B.begin()); EXPECT_EQ(BC.parent_end(), BC.parent_begin()); } TEST(LazyCallGraphTest, IntraSCCEdgeInsertion) { std::unique_ptr<Module> M1 = parseAssembly( "define void @a() {\n" "entry:\n" " call void @b()\n" " ret void\n" "}\n" "define void @b() {\n" "entry:\n" " call void @c()\n" " ret void\n" "}\n" "define void @c() {\n" "entry:\n" " call void @a()\n" " ret void\n" "}\n"); LazyCallGraph CG1(*M1); // Force the graph to be fully expanded. auto SCCI = CG1.postorder_scc_begin(); LazyCallGraph::SCC &SCC = *SCCI++; EXPECT_EQ(CG1.postorder_scc_end(), SCCI); LazyCallGraph::Node &A = *CG1.lookup(lookupFunction(*M1, "a")); LazyCallGraph::Node &B = *CG1.lookup(lookupFunction(*M1, "b")); LazyCallGraph::Node &C = *CG1.lookup(lookupFunction(*M1, "c")); EXPECT_EQ(&SCC, CG1.lookupSCC(A)); EXPECT_EQ(&SCC, CG1.lookupSCC(B)); EXPECT_EQ(&SCC, CG1.lookupSCC(C)); // Insert an edge from 'a' to 'c'. Nothing changes about the SCCs. SCC.insertIntraSCCEdge(A, C); EXPECT_EQ(2, std::distance(A.begin(), A.end())); EXPECT_EQ(&SCC, CG1.lookupSCC(A)); EXPECT_EQ(&SCC, CG1.lookupSCC(B)); EXPECT_EQ(&SCC, CG1.lookupSCC(C)); // Insert a self edge from 'a' back to 'a'. SCC.insertIntraSCCEdge(A, A); EXPECT_EQ(3, std::distance(A.begin(), A.end())); EXPECT_EQ(&SCC, CG1.lookupSCC(A)); EXPECT_EQ(&SCC, CG1.lookupSCC(B)); EXPECT_EQ(&SCC, CG1.lookupSCC(C)); } TEST(LazyCallGraphTest, IntraSCCEdgeRemoval) { // A nice fully connected (including self-edges) SCC. std::unique_ptr<Module> M1 = parseAssembly( "define void @a() {\n" "entry:\n" " call void @a()\n" " call void @b()\n" " call void @c()\n" " ret void\n" "}\n" "define void @b() {\n" "entry:\n" " call void @a()\n" " call void @b()\n" " call void @c()\n" " ret void\n" "}\n" "define void @c() {\n" "entry:\n" " call void @a()\n" " call void @b()\n" " call void @c()\n" " ret void\n" "}\n"); LazyCallGraph CG1(*M1); // Force the graph to be fully expanded. auto SCCI = CG1.postorder_scc_begin(); LazyCallGraph::SCC &SCC = *SCCI++; EXPECT_EQ(CG1.postorder_scc_end(), SCCI); LazyCallGraph::Node &A = *CG1.lookup(lookupFunction(*M1, "a")); LazyCallGraph::Node &B = *CG1.lookup(lookupFunction(*M1, "b")); LazyCallGraph::Node &C = *CG1.lookup(lookupFunction(*M1, "c")); EXPECT_EQ(&SCC, CG1.lookupSCC(A)); EXPECT_EQ(&SCC, CG1.lookupSCC(B)); EXPECT_EQ(&SCC, CG1.lookupSCC(C)); // Remove the edge from b -> a, which should leave the 3 functions still in // a single connected component because of a -> b -> c -> a. SmallVector<LazyCallGraph::SCC *, 1> NewSCCs = SCC.removeIntraSCCEdge(B, A); EXPECT_EQ(0u, NewSCCs.size()); EXPECT_EQ(&SCC, CG1.lookupSCC(A)); EXPECT_EQ(&SCC, CG1.lookupSCC(B)); EXPECT_EQ(&SCC, CG1.lookupSCC(C)); // Remove the edge from c -> a, which should leave 'a' in the original SCC // and form a new SCC for 'b' and 'c'. NewSCCs = SCC.removeIntraSCCEdge(C, A); EXPECT_EQ(1u, NewSCCs.size()); EXPECT_EQ(&SCC, CG1.lookupSCC(A)); EXPECT_EQ(1, std::distance(SCC.begin(), SCC.end())); LazyCallGraph::SCC *SCC2 = CG1.lookupSCC(B); EXPECT_EQ(SCC2, CG1.lookupSCC(C)); EXPECT_EQ(SCC2, NewSCCs[0]); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Analysis/CMakeLists.txt
set(LLVM_LINK_COMPONENTS IPA Analysis AsmParser Core Support ) add_llvm_unittest(AnalysisTests AliasAnalysisTest.cpp CallGraphTest.cpp CFGTest.cpp LazyCallGraphTest.cpp ScalarEvolutionTest.cpp MixedTBAATest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Analysis/CFGTest.cpp
//===- CFGTest.cpp - CFG tests --------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/CFG.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace { // This fixture assists in running the isPotentiallyReachable utility four ways // and ensuring it produces the correct answer each time. class IsPotentiallyReachableTest : public testing::Test { protected: void ParseAssembly(const char *Assembly) { SMDiagnostic Error; M = parseAssemblyString(Assembly, Error, getGlobalContext()); std::string errMsg; raw_string_ostream os(errMsg); Error.print("", os); // A failure here means that the test itself is buggy. if (!M) report_fatal_error(os.str().c_str()); Function *F = M->getFunction("test"); if (F == nullptr) report_fatal_error("Test must have a function named @test"); A = B = nullptr; for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) { if (I->hasName()) { if (I->getName() == "A") A = &*I; else if (I->getName() == "B") B = &*I; } } if (A == nullptr) report_fatal_error("@test must have an instruction %A"); if (B == nullptr) report_fatal_error("@test must have an instruction %B"); } void ExpectPath(bool ExpectedResult) { static char ID; class IsPotentiallyReachableTestPass : public FunctionPass { public: IsPotentiallyReachableTestPass(bool ExpectedResult, Instruction *A, Instruction *B) : FunctionPass(ID), ExpectedResult(ExpectedResult), A(A), B(B) {} static int initialize() { PassInfo *PI = new PassInfo("isPotentiallyReachable testing pass", "", &ID, nullptr, true, true); PassRegistry::getPassRegistry()->registerPass(*PI, false); initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry()); initializeDominatorTreeWrapperPassPass( *PassRegistry::getPassRegistry()); return 0; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); AU.addRequired<LoopInfoWrapperPass>(); AU.addRequired<DominatorTreeWrapperPass>(); } bool runOnFunction(Function &F) override { if (!F.hasName() || F.getName() != "test") return false; LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); EXPECT_EQ(isPotentiallyReachable(A, B, nullptr, nullptr), ExpectedResult); EXPECT_EQ(isPotentiallyReachable(A, B, DT, nullptr), ExpectedResult); EXPECT_EQ(isPotentiallyReachable(A, B, nullptr, LI), ExpectedResult); EXPECT_EQ(isPotentiallyReachable(A, B, DT, LI), ExpectedResult); return false; } bool ExpectedResult; Instruction *A, *B; }; static int initialize = IsPotentiallyReachableTestPass::initialize(); (void)initialize; IsPotentiallyReachableTestPass *P = new IsPotentiallyReachableTestPass(ExpectedResult, A, B); legacy::PassManager PM; PM.add(P); PM.run(*M); } std::unique_ptr<Module> M; Instruction *A, *B; }; } TEST_F(IsPotentiallyReachableTest, SameBlockNoPath) { ParseAssembly( "define void @test() {\n" "entry:\n" " bitcast i8 undef to i8\n" " %B = bitcast i8 undef to i8\n" " bitcast i8 undef to i8\n" " bitcast i8 undef to i8\n" " %A = bitcast i8 undef to i8\n" " ret void\n" "}\n"); ExpectPath(false); } TEST_F(IsPotentiallyReachableTest, SameBlockPath) { ParseAssembly( "define void @test() {\n" "entry:\n" " %A = bitcast i8 undef to i8\n" " bitcast i8 undef to i8\n" " bitcast i8 undef to i8\n" " %B = bitcast i8 undef to i8\n" " ret void\n" "}\n"); ExpectPath(true); } TEST_F(IsPotentiallyReachableTest, SameBlockNoLoop) { ParseAssembly( "define void @test() {\n" "entry:\n" " br label %middle\n" "middle:\n" " %B = bitcast i8 undef to i8\n" " bitcast i8 undef to i8\n" " bitcast i8 undef to i8\n" " %A = bitcast i8 undef to i8\n" " br label %nextblock\n" "nextblock:\n" " ret void\n" "}\n"); ExpectPath(false); } TEST_F(IsPotentiallyReachableTest, StraightNoPath) { ParseAssembly( "define void @test() {\n" "entry:\n" " %B = bitcast i8 undef to i8\n" " br label %exit\n" "exit:\n" " %A = bitcast i8 undef to i8\n" " ret void\n" "}"); ExpectPath(false); } TEST_F(IsPotentiallyReachableTest, StraightPath) { ParseAssembly( "define void @test() {\n" "entry:\n" " %A = bitcast i8 undef to i8\n" " br label %exit\n" "exit:\n" " %B = bitcast i8 undef to i8\n" " ret void\n" "}"); ExpectPath(true); } TEST_F(IsPotentiallyReachableTest, DestUnreachable) { ParseAssembly( "define void @test() {\n" "entry:\n" " br label %midblock\n" "midblock:\n" " %A = bitcast i8 undef to i8\n" " ret void\n" "unreachable:\n" " %B = bitcast i8 undef to i8\n" " br label %midblock\n" "}"); ExpectPath(false); } TEST_F(IsPotentiallyReachableTest, BranchToReturn) { ParseAssembly( "define void @test(i1 %x) {\n" "entry:\n" " %A = bitcast i8 undef to i8\n" " br i1 %x, label %block1, label %block2\n" "block1:\n" " ret void\n" "block2:\n" " %B = bitcast i8 undef to i8\n" " ret void\n" "}"); ExpectPath(true); } TEST_F(IsPotentiallyReachableTest, SimpleLoop1) { ParseAssembly( "declare i1 @switch()\n" "\n" "define void @test() {\n" "entry:\n" " br label %loop\n" "loop:\n" " %B = bitcast i8 undef to i8\n" " %A = bitcast i8 undef to i8\n" " %x = call i1 @switch()\n" " br i1 %x, label %loop, label %exit\n" "exit:\n" " ret void\n" "}"); ExpectPath(true); } TEST_F(IsPotentiallyReachableTest, SimpleLoop2) { ParseAssembly( "declare i1 @switch()\n" "\n" "define void @test() {\n" "entry:\n" " %B = bitcast i8 undef to i8\n" " br label %loop\n" "loop:\n" " %A = bitcast i8 undef to i8\n" " %x = call i1 @switch()\n" " br i1 %x, label %loop, label %exit\n" "exit:\n" " ret void\n" "}"); ExpectPath(false); } TEST_F(IsPotentiallyReachableTest, SimpleLoop3) { ParseAssembly( "declare i1 @switch()\n" "\n" "define void @test() {\n" "entry:\n" " br label %loop\n" "loop:\n" " %B = bitcast i8 undef to i8\n" " %x = call i1 @switch()\n" " br i1 %x, label %loop, label %exit\n" "exit:\n" " %A = bitcast i8 undef to i8\n" " ret void\n" "}"); ExpectPath(false); } TEST_F(IsPotentiallyReachableTest, OneLoopAfterTheOther1) { ParseAssembly( "declare i1 @switch()\n" "\n" "define void @test() {\n" "entry:\n" " br label %loop1\n" "loop1:\n" " %A = bitcast i8 undef to i8\n" " %x = call i1 @switch()\n" " br i1 %x, label %loop1, label %loop1exit\n" "loop1exit:\n" " br label %loop2\n" "loop2:\n" " %B = bitcast i8 undef to i8\n" " %y = call i1 @switch()\n" " br i1 %x, label %loop2, label %loop2exit\n" "loop2exit:" " ret void\n" "}"); ExpectPath(true); } TEST_F(IsPotentiallyReachableTest, OneLoopAfterTheOther2) { ParseAssembly( "declare i1 @switch()\n" "\n" "define void @test() {\n" "entry:\n" " br label %loop1\n" "loop1:\n" " %B = bitcast i8 undef to i8\n" " %x = call i1 @switch()\n" " br i1 %x, label %loop1, label %loop1exit\n" "loop1exit:\n" " br label %loop2\n" "loop2:\n" " %A = bitcast i8 undef to i8\n" " %y = call i1 @switch()\n" " br i1 %x, label %loop2, label %loop2exit\n" "loop2exit:" " ret void\n" "}"); ExpectPath(false); } TEST_F(IsPotentiallyReachableTest, OneLoopAfterTheOtherInsideAThirdLoop) { ParseAssembly( "declare i1 @switch()\n" "\n" "define void @test() {\n" "entry:\n" " br label %outerloop3\n" "outerloop3:\n" " br label %innerloop1\n" "innerloop1:\n" " %B = bitcast i8 undef to i8\n" " %x = call i1 @switch()\n" " br i1 %x, label %innerloop1, label %innerloop1exit\n" "innerloop1exit:\n" " br label %innerloop2\n" "innerloop2:\n" " %A = bitcast i8 undef to i8\n" " %y = call i1 @switch()\n" " br i1 %x, label %innerloop2, label %innerloop2exit\n" "innerloop2exit:" " ;; In outer loop3 now.\n" " %z = call i1 @switch()\n" " br i1 %z, label %outerloop3, label %exit\n" "exit:\n" " ret void\n" "}"); ExpectPath(true); } static const char *BranchInsideLoopIR = "declare i1 @switch()\n" "\n" "define void @test() {\n" "entry:\n" " br label %loop\n" "loop:\n" " %x = call i1 @switch()\n" " br i1 %x, label %nextloopblock, label %exit\n" "nextloopblock:\n" " %y = call i1 @switch()\n" " br i1 %y, label %left, label %right\n" "left:\n" " %A = bitcast i8 undef to i8\n" " br label %loop\n" "right:\n" " %B = bitcast i8 undef to i8\n" " br label %loop\n" "exit:\n" " ret void\n" "}"; TEST_F(IsPotentiallyReachableTest, BranchInsideLoop) { ParseAssembly(BranchInsideLoopIR); ExpectPath(true); } TEST_F(IsPotentiallyReachableTest, ModifyTest) { ParseAssembly(BranchInsideLoopIR); succ_iterator S = succ_begin(++M->getFunction("test")->begin()); BasicBlock *OldBB = S[0]; S[0] = S[1]; ExpectPath(false); S[0] = OldBB; ExpectPath(true); } // HLSL Change Begin namespace { class CFGTest : public testing::Test { protected: void ParseAssembly(const char *Assembly) { SMDiagnostic Error; M = parseAssemblyString(Assembly, Error, getGlobalContext()); std::string errMsg; raw_string_ostream os(errMsg); Error.print("", os); // A failure here means that the test itself is buggy. if (!M) report_fatal_error(os.str().c_str()); Function *F = M->getFunction("test"); if (F == nullptr) report_fatal_error("Test must have a function named @test"); } std::unique_ptr<Module> M; }; } // namespace TEST_F(CFGTest, SuccIteratorPlusEquals) { ParseAssembly(BranchInsideLoopIR); // br label %loop auto iter = M->getFunction("test")->begin(); succ_iterator S = succ_begin(iter); S += 1; EXPECT_EQ(S, succ_end(iter)); // br i1 %x, label %nextloopblock, label %exit ++iter; S = succ_begin(iter); S += 2; EXPECT_EQ(S, succ_end(iter)); // br i1 %y, label %left, label %right ++iter; S = succ_begin(iter); S += 2; EXPECT_EQ(S, succ_end(iter)); // br label %loop ++iter; S = succ_begin(iter); S += 1; EXPECT_EQ(S, succ_end(iter)); // br label %loop ++iter; S = succ_begin(iter); S += 1; EXPECT_EQ(S, succ_end(iter)); // Done ++iter; S = succ_begin(iter); EXPECT_EQ(S, succ_end(iter)); } // HLSL Change End
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Linker/LinkModulesTest.cpp
//===- llvm/unittest/Linker/LinkModulesTest.cpp - IRBuilder tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/AsmParser/Parser.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "llvm/Linker/Linker.h" #include "llvm/Support/SourceMgr.h" #include "llvm-c/Linker.h" #include "gtest/gtest.h" using namespace llvm; namespace { class LinkModuleTest : public testing::Test { protected: void SetUp() override { M.reset(new Module("MyModule", Ctx)); FunctionType *FTy = FunctionType::get( Type::getInt8PtrTy(Ctx), Type::getInt32Ty(Ctx), false /*=isVarArg*/); F = Function::Create(FTy, Function::ExternalLinkage, "ba_func", M.get()); F->setCallingConv(CallingConv::C); EntryBB = BasicBlock::Create(Ctx, "entry", F); SwitchCase1BB = BasicBlock::Create(Ctx, "switch.case.1", F); SwitchCase2BB = BasicBlock::Create(Ctx, "switch.case.2", F); ExitBB = BasicBlock::Create(Ctx, "exit", F); AT = ArrayType::get(Type::getInt8PtrTy(Ctx), 3); GV = new GlobalVariable(*M.get(), AT, false /*=isConstant*/, GlobalValue::InternalLinkage, nullptr,"switch.bas"); // Global Initializer std::vector<Constant *> Init; Constant *SwitchCase1BA = BlockAddress::get(SwitchCase1BB); Init.push_back(SwitchCase1BA); Constant *SwitchCase2BA = BlockAddress::get(SwitchCase2BB); Init.push_back(SwitchCase2BA); ConstantInt *One = ConstantInt::get(Type::getInt32Ty(Ctx), 1); Constant *OnePtr = ConstantExpr::getCast(Instruction::IntToPtr, One, Type::getInt8PtrTy(Ctx)); Init.push_back(OnePtr); GV->setInitializer(ConstantArray::get(AT, Init)); } void TearDown() override { M.reset(); } LLVMContext Ctx; std::unique_ptr<Module> M; Function *F; ArrayType *AT; GlobalVariable *GV; BasicBlock *EntryBB; BasicBlock *SwitchCase1BB; BasicBlock *SwitchCase2BB; BasicBlock *ExitBB; }; TEST_F(LinkModuleTest, BlockAddress) { IRBuilder<> Builder(EntryBB); std::vector<Value *> GEPIndices; GEPIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ctx), 0)); GEPIndices.push_back(F->arg_begin()); Value *GEP = Builder.CreateGEP(AT, GV, GEPIndices, "switch.gep"); Value *Load = Builder.CreateLoad(GEP, "switch.load"); Builder.CreateRet(Load); Builder.SetInsertPoint(SwitchCase1BB); Builder.CreateBr(ExitBB); Builder.SetInsertPoint(SwitchCase2BB); Builder.CreateBr(ExitBB); Builder.SetInsertPoint(ExitBB); Builder.CreateRet(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx))); Module *LinkedModule = new Module("MyModuleLinked", Ctx); Linker::LinkModules(LinkedModule, M.get()); // Delete the original module. M.reset(); // Check that the global "@switch.bas" is well-formed. const GlobalVariable *LinkedGV = LinkedModule->getNamedGlobal("switch.bas"); const Constant *Init = LinkedGV->getInitializer(); // @switch.bas = internal global [3 x i8*] // [i8* blockaddress(@ba_func, %switch.case.1), // i8* blockaddress(@ba_func, %switch.case.2), // i8* inttoptr (i32 1 to i8*)] ArrayType *AT = ArrayType::get(Type::getInt8PtrTy(Ctx), 3); EXPECT_EQ(AT, Init->getType()); Value *Elem = Init->getOperand(0); ASSERT_TRUE(isa<BlockAddress>(Elem)); EXPECT_EQ(cast<BlockAddress>(Elem)->getFunction(), LinkedModule->getFunction("ba_func")); EXPECT_EQ(cast<BlockAddress>(Elem)->getBasicBlock()->getParent(), LinkedModule->getFunction("ba_func")); Elem = Init->getOperand(1); ASSERT_TRUE(isa<BlockAddress>(Elem)); EXPECT_EQ(cast<BlockAddress>(Elem)->getFunction(), LinkedModule->getFunction("ba_func")); EXPECT_EQ(cast<BlockAddress>(Elem)->getBasicBlock()->getParent(), LinkedModule->getFunction("ba_func")); delete LinkedModule; } static Module *getExternal(LLVMContext &Ctx, StringRef FuncName) { // Create a module with an empty externally-linked function Module *M = new Module("ExternalModule", Ctx); FunctionType *FTy = FunctionType::get( Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false /*=isVarArgs*/); Function *F = Function::Create(FTy, Function::ExternalLinkage, FuncName, M); F->setCallingConv(CallingConv::C); BasicBlock *BB = BasicBlock::Create(Ctx, "", F); IRBuilder<> Builder(BB); Builder.CreateRetVoid(); return M; } static Module *getInternal(LLVMContext &Ctx) { Module *InternalM = new Module("InternalModule", Ctx); FunctionType *FTy = FunctionType::get( Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false /*=isVarArgs*/); Function *F = Function::Create(FTy, Function::InternalLinkage, "bar", InternalM); F->setCallingConv(CallingConv::C); BasicBlock *BB = BasicBlock::Create(Ctx, "", F); IRBuilder<> Builder(BB); Builder.CreateRetVoid(); StructType *STy = StructType::create(Ctx, PointerType::get(FTy, 0)); GlobalVariable *GV = new GlobalVariable(*InternalM, STy, false /*=isConstant*/, GlobalValue::InternalLinkage, nullptr, "g"); GV->setInitializer(ConstantStruct::get(STy, F)); return InternalM; } TEST_F(LinkModuleTest, EmptyModule) { std::unique_ptr<Module> InternalM(getInternal(Ctx)); std::unique_ptr<Module> EmptyM(new Module("EmptyModule1", Ctx)); Linker::LinkModules(EmptyM.get(), InternalM.get()); } TEST_F(LinkModuleTest, EmptyModule2) { std::unique_ptr<Module> InternalM(getInternal(Ctx)); std::unique_ptr<Module> EmptyM(new Module("EmptyModule1", Ctx)); Linker::LinkModules(InternalM.get(), EmptyM.get()); } TEST_F(LinkModuleTest, TypeMerge) { LLVMContext C; SMDiagnostic Err; const char *M1Str = "%t = type {i32}\n" "@t1 = weak global %t zeroinitializer\n"; std::unique_ptr<Module> M1 = parseAssemblyString(M1Str, Err, C); const char *M2Str = "%t = type {i32}\n" "@t2 = weak global %t zeroinitializer\n"; std::unique_ptr<Module> M2 = parseAssemblyString(M2Str, Err, C); Linker::LinkModules(M1.get(), M2.get(), [](const llvm::DiagnosticInfo &){}); EXPECT_EQ(M1->getNamedGlobal("t1")->getType(), M1->getNamedGlobal("t2")->getType()); } TEST_F(LinkModuleTest, CAPISuccess) { std::unique_ptr<Module> DestM(getExternal(Ctx, "foo")); std::unique_ptr<Module> SourceM(getExternal(Ctx, "bar")); char *errout = nullptr; LLVMBool result = LLVMLinkModules(wrap(DestM.get()), wrap(SourceM.get()), LLVMLinkerDestroySource, &errout); EXPECT_EQ(0, result); EXPECT_EQ(nullptr, errout); // "bar" is present in destination module EXPECT_NE(nullptr, DestM->getFunction("bar")); } TEST_F(LinkModuleTest, CAPIFailure) { // Symbol clash between two modules std::unique_ptr<Module> DestM(getExternal(Ctx, "foo")); std::unique_ptr<Module> SourceM(getExternal(Ctx, "foo")); char *errout = nullptr; LLVMBool result = LLVMLinkModules(wrap(DestM.get()), wrap(SourceM.get()), LLVMLinkerDestroySource, &errout); EXPECT_EQ(1, result); EXPECT_STREQ("Linking globals named 'foo': symbol multiply defined!", errout); LLVMDisposeMessage(errout); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Linker/CMakeLists.txt
set(LLVM_LINK_COMPONENTS AsmParser core linker ) set(LinkerSources LinkModulesTest.cpp ) add_llvm_unittest(LinkerTests ${LinkerSources} )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/CodeGen/CMakeLists.txt
set(LLVM_LINK_COMPONENTS AsmPrinter Support ) set(CodeGenSources DIEHashTest.cpp ) add_llvm_unittest(CodeGenTests ${CodeGenSources} )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/CodeGen/DIEHashTest.cpp
//===- llvm/unittest/DebugInfo/DWARFFormValueTest.cpp ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/DIE.h" #include "../lib/CodeGen/AsmPrinter/DIEHash.h" #include "llvm/ADT/STLExtras.h" #include "llvm/CodeGen/DwarfStringPoolEntry.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/Format.h" #include "gtest/gtest.h" using namespace llvm; namespace { // Test fixture class DIEHashTest : public testing::Test { public: BumpPtrAllocator Alloc; private: StringMap<DwarfStringPoolEntry> Pool; public: DIEString getString(StringRef S) { DwarfStringPoolEntry Entry = {nullptr, 1, 1}; return DIEString( DwarfStringPoolEntryRef(*Pool.insert(std::make_pair(S, Entry)).first)); } }; TEST_F(DIEHashTest, Data1) { DIEHash Hash; DIE &Die = *DIE::get(Alloc, dwarf::DW_TAG_base_type); DIEInteger Size(4); Die.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Size); uint64_t MD5Res = Hash.computeTypeSignature(Die); ASSERT_EQ(0x1AFE116E83701108ULL, MD5Res); } // struct {}; TEST_F(DIEHashTest, TrivialType) { DIE &Unnamed = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); Unnamed.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); // Line and file number are ignored. Unnamed.addValue(Alloc, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, One); Unnamed.addValue(Alloc, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, One); uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed); // The exact same hash GCC produces for this DIE. ASSERT_EQ(0x715305ce6cfd9ad1ULL, MD5Res); } // struct foo { }; TEST_F(DIEHashTest, NamedType) { DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); DIEString FooStr = getString("foo"); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); uint64_t MD5Res = DIEHash().computeTypeSignature(Foo); // The exact same hash GCC produces for this DIE. ASSERT_EQ(0xd566dbd2ca5265ffULL, MD5Res); } // namespace space { struct foo { }; } TEST_F(DIEHashTest, NamespacedType) { DIE &CU = *DIE::get(Alloc, dwarf::DW_TAG_compile_unit); auto Space = DIE::get(Alloc, dwarf::DW_TAG_namespace); DIEInteger One(1); DIEString SpaceStr = getString("space"); Space->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, SpaceStr); // DW_AT_declaration is ignored. Space->addValue(Alloc, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, One); // sibling? auto Foo = DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEString FooStr = getString("foo"); Foo->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); Foo->addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); DIE &N = *Foo; Space->addChild(std::move(Foo)); CU.addChild(std::move(Space)); uint64_t MD5Res = DIEHash().computeTypeSignature(N); // The exact same hash GCC produces for this DIE. ASSERT_EQ(0x7b80381fd17f1e33ULL, MD5Res); } // struct { int member; }; TEST_F(DIEHashTest, TypeWithMember) { DIE &Unnamed = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger Four(4); Unnamed.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Four); DIE &Int = *DIE::get(Alloc, dwarf::DW_TAG_base_type); DIEString IntStr = getString("int"); Int.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, IntStr); Int.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Four); DIEInteger Five(5); Int.addValue(Alloc, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Five); DIEEntry IntRef(Int); auto Member = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString MemberStr = getString("member"); Member->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemberStr); DIEInteger Zero(0); Member->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); Member->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IntRef); Unnamed.addChild(std::move(Member)); uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed); ASSERT_EQ(0x5646aa436b7e07c6ULL, MD5Res); } // struct foo { int mem1, mem2; }; TEST_F(DIEHashTest, ReusedType) { DIE &Unnamed = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger Eight(8); Unnamed.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEInteger Four(4); DIE &Int = *DIE::get(Alloc, dwarf::DW_TAG_base_type); DIEString IntStr = getString("int"); Int.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, IntStr); Int.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Four); DIEInteger Five(5); Int.addValue(Alloc, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Five); DIEEntry IntRef(Int); auto Mem1 = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString Mem1Str = getString("mem1"); Mem1->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, Mem1Str); DIEInteger Zero(0); Mem1->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); Mem1->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IntRef); Unnamed.addChild(std::move(Mem1)); auto Mem2 = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString Mem2Str = getString("mem2"); Mem2->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, Mem2Str); Mem2->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Four); Mem2->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IntRef); Unnamed.addChild(std::move(Mem2)); uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed); ASSERT_EQ(0x3a7dc3ed7b76b2f8ULL, MD5Res); } // struct foo { static foo f; }; TEST_F(DIEHashTest, RecursiveType) { DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); DIEString FooStr = getString("foo"); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString MemStr = getString("mem"); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); DIEEntry FooRef(Foo); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooRef); // DW_AT_external and DW_AT_declaration are ignored anyway, so skip them. Foo.addChild(std::move(Mem)); uint64_t MD5Res = DIEHash().computeTypeSignature(Foo); ASSERT_EQ(0x73d8b25aef227b06ULL, MD5Res); } // struct foo { foo *mem; }; TEST_F(DIEHashTest, Pointer) { DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger Eight(8); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEString FooStr = getString("foo"); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString MemStr = getString("mem"); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); DIEInteger Zero(0); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &FooPtr = *DIE::get(Alloc, dwarf::DW_TAG_pointer_type); FooPtr.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEEntry FooRef(Foo); FooPtr.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooRef); DIEEntry FooPtrRef(FooPtr); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooPtrRef); Foo.addChild(std::move(Mem)); uint64_t MD5Res = DIEHash().computeTypeSignature(Foo); ASSERT_EQ(0x74ea73862e8708d2ULL, MD5Res); } // struct foo { foo &mem; }; TEST_F(DIEHashTest, Reference) { DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger Eight(8); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEString FooStr = getString("foo"); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString MemStr = getString("mem"); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); DIEInteger Zero(0); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &FooRef = *DIE::get(Alloc, dwarf::DW_TAG_reference_type); FooRef.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEEntry FooEntry(Foo); FooRef.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooEntry); DIE &FooRefConst = *DIE::get(Alloc, dwarf::DW_TAG_const_type); DIEEntry FooRefRef(FooRef); FooRefConst.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooRefRef); DIEEntry FooRefConstRef(FooRefConst); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooRefConstRef); Foo.addChild(std::move(Mem)); uint64_t MD5Res = DIEHash().computeTypeSignature(Foo); ASSERT_EQ(0xa0b15f467ad4525bULL, MD5Res); } // struct foo { foo &&mem; }; TEST_F(DIEHashTest, RValueReference) { DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger Eight(8); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEString FooStr = getString("foo"); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString MemStr = getString("mem"); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); DIEInteger Zero(0); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &FooRef = *DIE::get(Alloc, dwarf::DW_TAG_rvalue_reference_type); FooRef.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEEntry FooEntry(Foo); FooRef.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooEntry); DIE &FooRefConst = *DIE::get(Alloc, dwarf::DW_TAG_const_type); DIEEntry FooRefRef(FooRef); FooRefConst.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooRefRef); DIEEntry FooRefConstRef(FooRefConst); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooRefConstRef); Foo.addChild(std::move(Mem)); uint64_t MD5Res = DIEHash().computeTypeSignature(Foo); ASSERT_EQ(0xad211c8c3b31e57ULL, MD5Res); } // struct foo { foo foo::*mem; }; TEST_F(DIEHashTest, PtrToMember) { DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger Eight(8); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEString FooStr = getString("foo"); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString MemStr = getString("mem"); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); DIEInteger Zero(0); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &PtrToFooMem = *DIE::get(Alloc, dwarf::DW_TAG_ptr_to_member_type); DIEEntry FooEntry(Foo); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FooEntry); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, FooEntry); DIEEntry PtrToFooMemRef(PtrToFooMem); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, PtrToFooMemRef); Foo.addChild(std::move(Mem)); uint64_t MD5Res = DIEHash().computeTypeSignature(Foo); ASSERT_EQ(0x852e0c9ff7c04ebULL, MD5Res); } // Check that the hash for a pointer-to-member matches regardless of whether the // pointed-to type is a declaration or a definition. // // struct bar; // { }; // struct foo { bar foo::*mem; }; TEST_F(DIEHashTest, PtrToMemberDeclDefMatch) { DIEInteger Zero(0); DIEInteger One(1); DIEInteger Eight(8); DIEString FooStr = getString("foo"); DIEString BarStr = getString("bar"); DIEString MemStr = getString("mem"); uint64_t MD5ResDecl; { DIE &Bar = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Bar.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, BarStr); Bar.addValue(Alloc, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, One); DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &PtrToFooMem = *DIE::get(Alloc, dwarf::DW_TAG_ptr_to_member_type); DIEEntry BarEntry(Bar); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, BarEntry); DIEEntry FooEntry(Foo); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, FooEntry); DIEEntry PtrToFooMemRef(PtrToFooMem); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, PtrToFooMemRef); Foo.addChild(std::move(Mem)); MD5ResDecl = DIEHash().computeTypeSignature(Foo); } uint64_t MD5ResDef; { DIE &Bar = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Bar.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, BarStr); Bar.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &PtrToFooMem = *DIE::get(Alloc, dwarf::DW_TAG_ptr_to_member_type); DIEEntry BarEntry(Bar); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, BarEntry); DIEEntry FooEntry(Foo); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, FooEntry); DIEEntry PtrToFooMemRef(PtrToFooMem); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, PtrToFooMemRef); Foo.addChild(std::move(Mem)); MD5ResDef = DIEHash().computeTypeSignature(Foo); } ASSERT_EQ(MD5ResDef, MD5ResDecl); } // Check that the hash for a pointer-to-member matches regardless of whether the // pointed-to type is a declaration or a definition. // // struct bar; // { }; // struct foo { bar bar::*mem; }; TEST_F(DIEHashTest, PtrToMemberDeclDefMisMatch) { DIEInteger Zero(0); DIEInteger One(1); DIEInteger Eight(8); DIEString FooStr = getString("foo"); DIEString BarStr = getString("bar"); DIEString MemStr = getString("mem"); uint64_t MD5ResDecl; { DIE &Bar = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Bar.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, BarStr); Bar.addValue(Alloc, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, One); DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &PtrToFooMem = *DIE::get(Alloc, dwarf::DW_TAG_ptr_to_member_type); DIEEntry BarEntry(Bar); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, BarEntry); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, BarEntry); DIEEntry PtrToFooMemRef(PtrToFooMem); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, PtrToFooMemRef); Foo.addChild(std::move(Mem)); MD5ResDecl = DIEHash().computeTypeSignature(Foo); } uint64_t MD5ResDef; { DIE &Bar = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Bar.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, BarStr); Bar.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &PtrToFooMem = *DIE::get(Alloc, dwarf::DW_TAG_ptr_to_member_type); DIEEntry BarEntry(Bar); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, BarEntry); PtrToFooMem.addValue(Alloc, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, BarEntry); DIEEntry PtrToFooMemRef(PtrToFooMem); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, PtrToFooMemRef); Foo.addChild(std::move(Mem)); MD5ResDef = DIEHash().computeTypeSignature(Foo); } // FIXME: This seems to be a bug in the DWARF type hashing specification that // only uses the brief name hashing for types referenced via DW_AT_type. In // this case the type is referenced via DW_AT_containing_type and full hashing // causes a hash to differ when the containing type is a declaration in one TU // and a definition in another. ASSERT_NE(MD5ResDef, MD5ResDecl); } // struct { } a; // struct foo { decltype(a) mem; }; TEST_F(DIEHashTest, RefUnnamedType) { DIEInteger Zero(0); DIEInteger One(1); DIEInteger Eight(8); DIEString FooStr = getString("foo"); DIEString MemStr = getString("mem"); DIE &Unnamed = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Unnamed.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); DIE &Foo = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); Foo.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); Foo.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); auto Mem = DIE::get(Alloc, dwarf::DW_TAG_member); Mem->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, MemStr); Mem->addValue(Alloc, dwarf::DW_AT_data_member_location, dwarf::DW_FORM_data1, Zero); DIE &UnnamedPtr = *DIE::get(Alloc, dwarf::DW_TAG_pointer_type); UnnamedPtr.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Eight); DIEEntry UnnamedRef(Unnamed); UnnamedPtr.addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, UnnamedRef); DIEEntry UnnamedPtrRef(UnnamedPtr); Mem->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, UnnamedPtrRef); Foo.addChild(std::move(Mem)); uint64_t MD5Res = DIEHash().computeTypeSignature(Foo); ASSERT_EQ(0x954e026f01c02529ULL, MD5Res); } // struct { struct foo { }; }; TEST_F(DIEHashTest, NestedType) { DIE &Unnamed = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); Unnamed.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); auto Foo = DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEString FooStr = getString("foo"); Foo->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FooStr); Foo->addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); Unnamed.addChild(std::move(Foo)); uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed); // The exact same hash GCC produces for this DIE. ASSERT_EQ(0xde8a3b7b43807f4aULL, MD5Res); } // struct { static void func(); }; TEST_F(DIEHashTest, MemberFunc) { DIE &Unnamed = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); Unnamed.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); auto Func = DIE::get(Alloc, dwarf::DW_TAG_subprogram); DIEString FuncStr = getString("func"); Func->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FuncStr); Unnamed.addChild(std::move(Func)); uint64_t MD5Res = DIEHash().computeTypeSignature(Unnamed); // The exact same hash GCC produces for this DIE. ASSERT_EQ(0xd36a1b6dfb604ba0ULL, MD5Res); } // struct A { // static void func(); // }; TEST_F(DIEHashTest, MemberFuncFlag) { DIE &A = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); DIEString AStr = getString("A"); A.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, AStr); A.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); A.addValue(Alloc, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, One); A.addValue(Alloc, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, One); auto Func = DIE::get(Alloc, dwarf::DW_TAG_subprogram); DIEString FuncStr = getString("func"); DIEString FuncLinkage = getString("_ZN1A4funcEv"); DIEInteger Two(2); Func->addValue(Alloc, dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, One); Func->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FuncStr); Func->addValue(Alloc, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, One); Func->addValue(Alloc, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, Two); Func->addValue(Alloc, dwarf::DW_AT_linkage_name, dwarf::DW_FORM_strp, FuncLinkage); Func->addValue(Alloc, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, One); A.addChild(std::move(Func)); uint64_t MD5Res = DIEHash().computeTypeSignature(A); // The exact same hash GCC produces for this DIE. ASSERT_EQ(0x8f78211ddce3df10ULL, MD5Res); } // Derived from: // struct A { // const static int PI = -3; // }; // A a; TEST_F(DIEHashTest, MemberSdata) { DIE &A = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); DIEString AStr = getString("A"); A.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, AStr); A.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); A.addValue(Alloc, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, One); A.addValue(Alloc, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, One); DIEInteger Four(4); DIEInteger Five(5); DIEString FStr = getString("int"); DIE &IntTyDIE = *DIE::get(Alloc, dwarf::DW_TAG_base_type); IntTyDIE.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Four); IntTyDIE.addValue(Alloc, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Five); IntTyDIE.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FStr); DIEEntry IntTy(IntTyDIE); auto PITyDIE = DIE::get(Alloc, dwarf::DW_TAG_const_type); PITyDIE->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IntTy); DIEEntry PITy(*PITyDIE); auto PI = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString PIStr = getString("PI"); DIEInteger Two(2); DIEInteger NegThree(-3); PI->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, PIStr); PI->addValue(Alloc, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, One); PI->addValue(Alloc, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, Two); PI->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, PITy); PI->addValue(Alloc, dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, One); PI->addValue(Alloc, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, One); PI->addValue(Alloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, NegThree); A.addChild(std::move(PI)); uint64_t MD5Res = DIEHash().computeTypeSignature(A); ASSERT_EQ(0x9a216000dd3788a7ULL, MD5Res); } // Derived from: // struct A { // const static float PI = 3.14; // }; // A a; TEST_F(DIEHashTest, MemberBlock) { DIE &A = *DIE::get(Alloc, dwarf::DW_TAG_structure_type); DIEInteger One(1); DIEString AStr = getString("A"); A.addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, AStr); A.addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, One); A.addValue(Alloc, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, One); A.addValue(Alloc, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, One); DIEInteger Four(4); DIEString FStr = getString("float"); auto FloatTyDIE = DIE::get(Alloc, dwarf::DW_TAG_base_type); FloatTyDIE->addValue(Alloc, dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, Four); FloatTyDIE->addValue(Alloc, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Four); FloatTyDIE->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, FStr); DIEEntry FloatTy(*FloatTyDIE); auto PITyDIE = DIE::get(Alloc, dwarf::DW_TAG_const_type); PITyDIE->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, FloatTy); DIEEntry PITy(*PITyDIE); auto PI = DIE::get(Alloc, dwarf::DW_TAG_member); DIEString PIStr = getString("PI"); DIEInteger Two(2); PI->addValue(Alloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp, PIStr); PI->addValue(Alloc, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data1, One); PI->addValue(Alloc, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data1, Two); PI->addValue(Alloc, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, PITy); PI->addValue(Alloc, dwarf::DW_AT_external, dwarf::DW_FORM_flag_present, One); PI->addValue(Alloc, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag_present, One); DIEBlock PIBlock; DIEInteger Blk1(0xc3); DIEInteger Blk2(0xf5); DIEInteger Blk3(0x48); DIEInteger Blk4(0x40); PIBlock.addValue(Alloc, (dwarf::Attribute)0, dwarf::DW_FORM_data1, Blk1); PIBlock.addValue(Alloc, (dwarf::Attribute)0, dwarf::DW_FORM_data1, Blk2); PIBlock.addValue(Alloc, (dwarf::Attribute)0, dwarf::DW_FORM_data1, Blk3); PIBlock.addValue(Alloc, (dwarf::Attribute)0, dwarf::DW_FORM_data1, Blk4); PI->addValue(Alloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_block1, &PIBlock); A.addChild(std::move(PI)); uint64_t MD5Res = DIEHash().computeTypeSignature(A); ASSERT_EQ(0x493af53ad3d3f651ULL, MD5Res); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Bitcode/BitReaderTest.cpp
//===- llvm/unittest/Bitcode/BitReaderTest.cpp - Tests for BitReader ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallString.h" #include "llvm/ADT/STLExtras.h" #include "llvm/AsmParser/Parser.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Support/DataStream.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; namespace { std::unique_ptr<Module> parseAssembly(const char *Assembly) { SMDiagnostic Error; std::unique_ptr<Module> M = parseAssemblyString(Assembly, Error, getGlobalContext()); std::string ErrMsg; raw_string_ostream OS(ErrMsg); Error.print("", OS); // A failure here means that the test itself is buggy. if (!M) report_fatal_error(OS.str().c_str()); return M; } static void writeModuleToBuffer(std::unique_ptr<Module> Mod, SmallVectorImpl<char> &Buffer) { raw_svector_ostream OS(Buffer); WriteBitcodeToFile(Mod.get(), OS); } static std::unique_ptr<Module> getLazyModuleFromAssembly(LLVMContext &Context, SmallString<1024> &Mem, const char *Assembly) { writeModuleToBuffer(parseAssembly(Assembly), Mem); std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(Mem.str(), "test", false); ErrorOr<std::unique_ptr<Module>> ModuleOrErr = getLazyBitcodeModule(std::move(Buffer), Context); return std::move(ModuleOrErr.get()); } class BufferDataStreamer : public DataStreamer { std::unique_ptr<MemoryBuffer> Buffer; unsigned Pos = 0; size_t GetBytes(unsigned char *Out, size_t Len) override { StringRef Buf = Buffer->getBuffer(); size_t Left = Buf.size() - Pos; Len = std::min(Left, Len); memcpy(Out, Buffer->getBuffer().substr(Pos).data(), Len); Pos += Len; return Len; } public: BufferDataStreamer(std::unique_ptr<MemoryBuffer> Buffer) : Buffer(std::move(Buffer)) {} }; static std::unique_ptr<Module> getStreamedModuleFromAssembly(LLVMContext &Context, SmallString<1024> &Mem, const char *Assembly) { writeModuleToBuffer(parseAssembly(Assembly), Mem); std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(Mem.str(), "test", false); auto Streamer = llvm::make_unique<BufferDataStreamer>(std::move(Buffer)); ErrorOr<std::unique_ptr<Module>> ModuleOrErr = getStreamedBitcodeModule("test", std::move(Streamer), Context); return std::move(ModuleOrErr.get()); } TEST(BitReaderTest, MateralizeForwardRefWithStream) { SmallString<1024> Mem; LLVMContext Context; std::unique_ptr<Module> M = getStreamedModuleFromAssembly( Context, Mem, "@table = constant i8* blockaddress(@func, %bb)\n" "define void @func() {\n" " unreachable\n" "bb:\n" " unreachable\n" "}\n"); EXPECT_FALSE(M->getFunction("func")->empty()); } TEST(BitReaderTest, DematerializeFunctionPreservesLinkageType) { SmallString<1024> Mem; LLVMContext Context; std::unique_ptr<Module> M = getLazyModuleFromAssembly( Context, Mem, "define internal i32 @func() {\n" "ret i32 0\n" "}\n"); EXPECT_FALSE(verifyModule(*M, &dbgs())); M->getFunction("func")->materialize(); EXPECT_FALSE(M->getFunction("func")->empty()); EXPECT_TRUE(M->getFunction("func")->getLinkage() == GlobalValue::InternalLinkage); // Check that the linkage type is preserved after dematerialization. M->getFunction("func")->dematerialize(); EXPECT_TRUE(M->getFunction("func")->empty()); EXPECT_TRUE(M->getFunction("func")->getLinkage() == GlobalValue::InternalLinkage); EXPECT_FALSE(verifyModule(*M, &dbgs())); } // Tests that lazy evaluation can parse functions out of order. TEST(BitReaderTest, MaterializeFunctionsOutOfOrder) { SmallString<1024> Mem; LLVMContext Context; std::unique_ptr<Module> M = getLazyModuleFromAssembly( Context, Mem, "define void @f() {\n" " unreachable\n" "}\n" "define void @g() {\n" " unreachable\n" "}\n" "define void @h() {\n" " unreachable\n" "}\n" "define void @j() {\n" " unreachable\n" "}\n"); EXPECT_FALSE(verifyModule(*M, &dbgs())); Function *F = M->getFunction("f"); Function *G = M->getFunction("g"); Function *H = M->getFunction("h"); Function *J = M->getFunction("j"); // Initially all functions are not materialized (no basic blocks). EXPECT_TRUE(F->empty()); EXPECT_TRUE(G->empty()); EXPECT_TRUE(H->empty()); EXPECT_TRUE(J->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Materialize h. H->materialize(); EXPECT_TRUE(F->empty()); EXPECT_TRUE(G->empty()); EXPECT_FALSE(H->empty()); EXPECT_TRUE(J->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Materialize g. G->materialize(); EXPECT_TRUE(F->empty()); EXPECT_FALSE(G->empty()); EXPECT_FALSE(H->empty()); EXPECT_TRUE(J->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Materialize j. J->materialize(); EXPECT_TRUE(F->empty()); EXPECT_FALSE(G->empty()); EXPECT_FALSE(H->empty()); EXPECT_FALSE(J->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Materialize f. F->materialize(); EXPECT_FALSE(F->empty()); EXPECT_FALSE(G->empty()); EXPECT_FALSE(H->empty()); EXPECT_FALSE(J->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); } TEST(BitReaderTest, MaterializeFunctionsForBlockAddr) { // PR11677 SmallString<1024> Mem; LLVMContext Context; std::unique_ptr<Module> M = getLazyModuleFromAssembly( Context, Mem, "@table = constant i8* blockaddress(@func, %bb)\n" "define void @func() {\n" " unreachable\n" "bb:\n" " unreachable\n" "}\n"); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Try (and fail) to dematerialize @func. M->getFunction("func")->dematerialize(); EXPECT_FALSE(M->getFunction("func")->empty()); } TEST(BitReaderTest, MaterializeFunctionsForBlockAddrInFunctionBefore) { SmallString<1024> Mem; LLVMContext Context; std::unique_ptr<Module> M = getLazyModuleFromAssembly( Context, Mem, "define i8* @before() {\n" " ret i8* blockaddress(@func, %bb)\n" "}\n" "define void @other() {\n" " unreachable\n" "}\n" "define void @func() {\n" " unreachable\n" "bb:\n" " unreachable\n" "}\n"); EXPECT_TRUE(M->getFunction("before")->empty()); EXPECT_TRUE(M->getFunction("func")->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Materialize @before, pulling in @func. EXPECT_FALSE(M->getFunction("before")->materialize()); EXPECT_FALSE(M->getFunction("func")->empty()); EXPECT_TRUE(M->getFunction("other")->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Try (and fail) to dematerialize @func. M->getFunction("func")->dematerialize(); EXPECT_FALSE(M->getFunction("func")->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); } TEST(BitReaderTest, MaterializeFunctionsForBlockAddrInFunctionAfter) { SmallString<1024> Mem; LLVMContext Context; std::unique_ptr<Module> M = getLazyModuleFromAssembly( Context, Mem, "define void @func() {\n" " unreachable\n" "bb:\n" " unreachable\n" "}\n" "define void @other() {\n" " unreachable\n" "}\n" "define i8* @after() {\n" " ret i8* blockaddress(@func, %bb)\n" "}\n"); EXPECT_TRUE(M->getFunction("after")->empty()); EXPECT_TRUE(M->getFunction("func")->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Materialize @after, pulling in @func. EXPECT_FALSE(M->getFunction("after")->materialize()); EXPECT_FALSE(M->getFunction("func")->empty()); EXPECT_TRUE(M->getFunction("other")->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); // Try (and fail) to dematerialize @func. M->getFunction("func")->dematerialize(); EXPECT_FALSE(M->getFunction("func")->empty()); EXPECT_FALSE(verifyModule(*M, &dbgs())); } } // end namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Bitcode/CMakeLists.txt
set(LLVM_LINK_COMPONENTS AsmParser BitReader BitWriter Core Support ) add_llvm_unittest(BitcodeTests BitReaderTest.cpp BitstreamReaderTest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Bitcode/BitstreamReaderTest.cpp
//===- BitstreamReaderTest.cpp - Tests for BitstreamReader ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Bitcode/BitstreamReader.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(BitstreamReaderTest, AtEndOfStream) { uint8_t Bytes[4] = { 0x00, 0x01, 0x02, 0x03 }; BitstreamReader Reader(std::begin(Bytes), std::end(Bytes)); BitstreamCursor Cursor(Reader); EXPECT_FALSE(Cursor.AtEndOfStream()); (void)Cursor.Read(8); EXPECT_FALSE(Cursor.AtEndOfStream()); (void)Cursor.Read(24); EXPECT_TRUE(Cursor.AtEndOfStream()); Cursor.JumpToBit(0); EXPECT_FALSE(Cursor.AtEndOfStream()); Cursor.JumpToBit(32); EXPECT_TRUE(Cursor.AtEndOfStream()); } TEST(BitstreamReaderTest, AtEndOfStreamJump) { uint8_t Bytes[4] = { 0x00, 0x01, 0x02, 0x03 }; BitstreamReader Reader(std::begin(Bytes), std::end(Bytes)); BitstreamCursor Cursor(Reader); Cursor.JumpToBit(32); EXPECT_TRUE(Cursor.AtEndOfStream()); } TEST(BitstreamReaderTest, AtEndOfStreamEmpty) { uint8_t Dummy = 0xFF; BitstreamReader Reader(&Dummy, &Dummy); BitstreamCursor Cursor(Reader); EXPECT_TRUE(Cursor.AtEndOfStream()); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/DxcSupport/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Support dxcSupport ) add_clang_unittest(DxcSupportTests WinAdapterTest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/DxcSupport/WinAdapterTest.cpp
//===- unittests/Basic/WinAdapterTest.cpp -- Windows Adapter tests --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef _WIN32 #include "dxc/Support/WinFunctions.h" #include "dxc/Support/WinIncludes.h" #include "gtest/gtest.h" #include <string.h> namespace { // Check that WArgV. TEST(WArgVTest, suppressAndTrap) { int argc = 2; std::wstring data[] = {L"a", L"b"}; const wchar_t *ref_argv[] = {data[0].c_str(), data[1].c_str()}; { const char *argv[] = {"a", "b"}; WArgV ArgV(argc, argv); const wchar_t **wargv = ArgV.argv(); for (int i = 0; i < argc; ++i) { EXPECT_EQ(0, std::wcscmp(ref_argv[i], wargv[i])); } } } } // namespace #endif
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ProfileData/InstrProfTest.cpp
//===- unittest/ProfileData/InstrProfTest.cpp -------------------------------=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/ProfileData/InstrProfWriter.h" #include "gtest/gtest.h" #include <cstdarg> using namespace llvm; static ::testing::AssertionResult NoError(std::error_code EC) { if (!EC) return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "error " << EC.value() << ": " << EC.message(); } static ::testing::AssertionResult ErrorEquals(std::error_code Expected, std::error_code Found) { if (Expected == Found) return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "error " << Found.value() << ": " << Found.message(); } namespace { struct InstrProfTest : ::testing::Test { InstrProfWriter Writer; std::unique_ptr<IndexedInstrProfReader> Reader; void readProfile(std::unique_ptr<MemoryBuffer> Profile) { auto ReaderOrErr = IndexedInstrProfReader::create(std::move(Profile)); ASSERT_TRUE(NoError(ReaderOrErr.getError())); Reader = std::move(ReaderOrErr.get()); } }; TEST_F(InstrProfTest, write_and_read_empty_profile) { auto Profile = Writer.writeBuffer(); readProfile(std::move(Profile)); ASSERT_TRUE(Reader->begin() == Reader->end()); } TEST_F(InstrProfTest, write_and_read_one_function) { Writer.addFunctionCounts("foo", 0x1234, {1, 2, 3, 4}); auto Profile = Writer.writeBuffer(); readProfile(std::move(Profile)); auto I = Reader->begin(), E = Reader->end(); ASSERT_TRUE(I != E); ASSERT_EQ(StringRef("foo"), I->Name); ASSERT_EQ(0x1234U, I->Hash); ASSERT_EQ(4U, I->Counts.size()); ASSERT_EQ(1U, I->Counts[0]); ASSERT_EQ(2U, I->Counts[1]); ASSERT_EQ(3U, I->Counts[2]); ASSERT_EQ(4U, I->Counts[3]); ASSERT_TRUE(++I == E); } TEST_F(InstrProfTest, get_function_counts) { Writer.addFunctionCounts("foo", 0x1234, {1, 2}); Writer.addFunctionCounts("foo", 0x1235, {3, 4}); auto Profile = Writer.writeBuffer(); readProfile(std::move(Profile)); std::vector<uint64_t> Counts; ASSERT_TRUE(NoError(Reader->getFunctionCounts("foo", 0x1234, Counts))); ASSERT_EQ(2U, Counts.size()); ASSERT_EQ(1U, Counts[0]); ASSERT_EQ(2U, Counts[1]); ASSERT_TRUE(NoError(Reader->getFunctionCounts("foo", 0x1235, Counts))); ASSERT_EQ(2U, Counts.size()); ASSERT_EQ(3U, Counts[0]); ASSERT_EQ(4U, Counts[1]); std::error_code EC; EC = Reader->getFunctionCounts("foo", 0x5678, Counts); ASSERT_TRUE(ErrorEquals(instrprof_error::hash_mismatch, EC)); EC = Reader->getFunctionCounts("bar", 0x1234, Counts); ASSERT_TRUE(ErrorEquals(instrprof_error::unknown_function, EC)); } TEST_F(InstrProfTest, get_max_function_count) { Writer.addFunctionCounts("foo", 0x1234, {1ULL << 31, 2}); Writer.addFunctionCounts("bar", 0, {1ULL << 63}); Writer.addFunctionCounts("baz", 0x5678, {0, 0, 0, 0}); auto Profile = Writer.writeBuffer(); readProfile(std::move(Profile)); ASSERT_EQ(1ULL << 63, Reader->getMaximumFunctionCount()); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ProfileData/CoverageMappingTest.cpp
//===- unittest/ProfileData/CoverageMappingTest.cpp -------------------------=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/ProfileData/CoverageMappingReader.h" #include "llvm/ProfileData/CoverageMappingWriter.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/ProfileData/InstrProfWriter.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <sstream> using namespace llvm; using namespace coverage; static ::testing::AssertionResult NoError(std::error_code EC) { if (!EC) return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "error " << EC.value() << ": " << EC.message(); } namespace llvm { namespace coverage { void PrintTo(const Counter &C, ::std::ostream *os) { if (C.isZero()) *os << "Zero"; else if (C.isExpression()) *os << "Expression " << C.getExpressionID(); else *os << "Counter " << C.getCounterID(); } void PrintTo(const CoverageSegment &S, ::std::ostream *os) { *os << "CoverageSegment(" << S.Line << ", " << S.Col << ", "; if (S.HasCount) *os << S.Count << ", "; *os << (S.IsRegionEntry ? "true" : "false") << ")"; } } } namespace { struct OneFunctionCoverageReader : CoverageMappingReader { StringRef Name; uint64_t Hash; std::vector<StringRef> Filenames; ArrayRef<CounterMappingRegion> Regions; bool Done; OneFunctionCoverageReader(StringRef Name, uint64_t Hash, ArrayRef<StringRef> Filenames, ArrayRef<CounterMappingRegion> Regions) : Name(Name), Hash(Hash), Filenames(Filenames), Regions(Regions), Done(false) {} std::error_code readNextRecord(CoverageMappingRecord &Record) override { if (Done) return instrprof_error::eof; Done = true; Record.FunctionName = Name; Record.FunctionHash = Hash; Record.Filenames = Filenames; Record.Expressions = {}; Record.MappingRegions = Regions; return instrprof_error::success; } }; struct CoverageMappingTest : ::testing::Test { StringMap<unsigned> Files; unsigned NextFile; std::vector<CounterMappingRegion> InputCMRs; std::vector<StringRef> OutputFiles; std::vector<CounterExpression> OutputExpressions; std::vector<CounterMappingRegion> OutputCMRs; InstrProfWriter ProfileWriter; std::unique_ptr<IndexedInstrProfReader> ProfileReader; std::unique_ptr<CoverageMapping> LoadedCoverage; void SetUp() override { NextFile = 0; } unsigned getFile(StringRef Name) { auto R = Files.find(Name); if (R != Files.end()) return R->second; Files[Name] = NextFile; return NextFile++; } void addCMR(Counter C, StringRef File, unsigned LS, unsigned CS, unsigned LE, unsigned CE) { InputCMRs.push_back( CounterMappingRegion::makeRegion(C, getFile(File), LS, CS, LE, CE)); } void addExpansionCMR(StringRef File, StringRef ExpandedFile, unsigned LS, unsigned CS, unsigned LE, unsigned CE) { InputCMRs.push_back(CounterMappingRegion::makeExpansion( getFile(File), getFile(ExpandedFile), LS, CS, LE, CE)); } std::string writeCoverageRegions() { SmallVector<unsigned, 8> FileIDs; for (const auto &E : Files) FileIDs.push_back(E.getValue()); std::string Coverage; llvm::raw_string_ostream OS(Coverage); CoverageMappingWriter(FileIDs, None, InputCMRs).write(OS); return OS.str(); } void readCoverageRegions(std::string Coverage) { SmallVector<StringRef, 8> Filenames; for (const auto &E : Files) Filenames.push_back(E.getKey()); RawCoverageMappingReader Reader(Coverage, Filenames, OutputFiles, OutputExpressions, OutputCMRs); ASSERT_TRUE(NoError(Reader.read())); } void readProfCounts() { auto Profile = ProfileWriter.writeBuffer(); auto ReaderOrErr = IndexedInstrProfReader::create(std::move(Profile)); ASSERT_TRUE(NoError(ReaderOrErr.getError())); ProfileReader = std::move(ReaderOrErr.get()); } void loadCoverageMapping(StringRef FuncName, uint64_t Hash) { std::string Regions = writeCoverageRegions(); readCoverageRegions(Regions); SmallVector<StringRef, 8> Filenames; for (const auto &E : Files) Filenames.push_back(E.getKey()); OneFunctionCoverageReader CovReader(FuncName, Hash, Filenames, OutputCMRs); auto CoverageOrErr = CoverageMapping::load(CovReader, *ProfileReader); ASSERT_TRUE(NoError(CoverageOrErr.getError())); LoadedCoverage = std::move(CoverageOrErr.get()); } }; TEST_F(CoverageMappingTest, basic_write_read) { addCMR(Counter::getCounter(0), "foo", 1, 1, 1, 1); addCMR(Counter::getCounter(1), "foo", 2, 1, 2, 2); addCMR(Counter::getZero(), "foo", 3, 1, 3, 4); addCMR(Counter::getCounter(2), "foo", 4, 1, 4, 8); addCMR(Counter::getCounter(3), "bar", 1, 2, 3, 4); std::string Coverage = writeCoverageRegions(); readCoverageRegions(Coverage); size_t N = makeArrayRef(InputCMRs).size(); ASSERT_EQ(N, OutputCMRs.size()); for (size_t I = 0; I < N; ++I) { ASSERT_EQ(InputCMRs[I].Count, OutputCMRs[I].Count); ASSERT_EQ(InputCMRs[I].FileID, OutputCMRs[I].FileID); ASSERT_EQ(InputCMRs[I].startLoc(), OutputCMRs[I].startLoc()); ASSERT_EQ(InputCMRs[I].endLoc(), OutputCMRs[I].endLoc()); ASSERT_EQ(InputCMRs[I].Kind, OutputCMRs[I].Kind); } } TEST_F(CoverageMappingTest, expansion_gets_first_counter) { addCMR(Counter::getCounter(1), "foo", 10, 1, 10, 2); // This starts earlier in "foo", so the expansion should get its counter. addCMR(Counter::getCounter(2), "foo", 1, 1, 20, 1); addExpansionCMR("bar", "foo", 3, 3, 3, 3); std::string Coverage = writeCoverageRegions(); readCoverageRegions(Coverage); ASSERT_EQ(CounterMappingRegion::ExpansionRegion, OutputCMRs[2].Kind); ASSERT_EQ(Counter::getCounter(2), OutputCMRs[2].Count); ASSERT_EQ(3U, OutputCMRs[2].LineStart); } TEST_F(CoverageMappingTest, basic_coverage_iteration) { ProfileWriter.addFunctionCounts("func", 0x1234, {30, 20, 10, 0}); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7); addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1); addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(7U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 20, true), Segments[0]); ASSERT_EQ(CoverageSegment(4, 7, 30, false), Segments[1]); ASSERT_EQ(CoverageSegment(5, 8, 10, true), Segments[2]); ASSERT_EQ(CoverageSegment(9, 1, 30, false), Segments[3]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[4]); ASSERT_EQ(CoverageSegment(10, 10, 0, true), Segments[5]); ASSERT_EQ(CoverageSegment(11, 11, false), Segments[6]); } TEST_F(CoverageMappingTest, uncovered_function) { readProfCounts(); addCMR(Counter::getZero(), "file1", 1, 2, 3, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(2U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 2, 0, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 4, false), Segments[1]); } TEST_F(CoverageMappingTest, uncovered_function_with_mapping) { readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(3U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 0, true), Segments[0]); ASSERT_EQ(CoverageSegment(4, 7, 0, false), Segments[1]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[2]); } TEST_F(CoverageMappingTest, combine_regions) { ProfileWriter.addFunctionCounts("func", 0x1234, {10, 20, 30}); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4); addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(4U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 3, 50, true), Segments[1]); ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]); } TEST_F(CoverageMappingTest, dont_combine_expansions) { ProfileWriter.addFunctionCounts("func", 0x1234, {10, 20}); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4); addCMR(Counter::getCounter(1), "include1", 6, 6, 7, 7); addExpansionCMR("file1", "include1", 3, 3, 4, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(4U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 3, 20, true), Segments[1]); ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]); } TEST_F(CoverageMappingTest, strip_filename_prefix) { ProfileWriter.addFunctionCounts("file1:func", 0x1234, {10}); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); loadCoverageMapping("file1:func", 0x1234); std::vector<std::string> Names; for (const auto &Func : LoadedCoverage->getCoveredFunctions()) Names.push_back(Func.Name); ASSERT_EQ(1U, Names.size()); ASSERT_EQ("func", Names[0]); } } // end anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/ProfileData/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Core ProfileData Support ) add_llvm_unittest(ProfileDataTests CoverageMappingTest.cpp InstrProfTest.cpp )
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/LEB128Test.cpp
//===- llvm/unittest/Support/LEB128Test.cpp - LEB128 function tests -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/raw_ostream.h" #include <string> using namespace llvm; namespace { TEST(LEB128Test, EncodeSLEB128) { #define EXPECT_SLEB128_EQ(EXPECTED, VALUE) \ do { \ /* encodeSLEB128(uint64_t, raw_ostream &) */ \ std::string Expected(EXPECTED, sizeof(EXPECTED) - 1); \ std::string Actual; \ raw_string_ostream Stream(Actual); \ encodeSLEB128(VALUE, Stream); \ Stream.flush(); \ EXPECT_EQ(Expected, Actual); \ } while (0) // Encode SLEB128 EXPECT_SLEB128_EQ("\x00", 0); EXPECT_SLEB128_EQ("\x01", 1); EXPECT_SLEB128_EQ("\x7f", -1); EXPECT_SLEB128_EQ("\x3f", 63); EXPECT_SLEB128_EQ("\x41", -63); EXPECT_SLEB128_EQ("\x40", -64); EXPECT_SLEB128_EQ("\xbf\x7f", -65); EXPECT_SLEB128_EQ("\xc0\x00", 64); #undef EXPECT_SLEB128_EQ } TEST(LEB128Test, EncodeULEB128) { #define EXPECT_ULEB128_EQ(EXPECTED, VALUE, PAD) \ do { \ std::string Expected(EXPECTED, sizeof(EXPECTED) - 1); \ \ /* encodeULEB128(uint64_t, raw_ostream &, unsigned) */ \ std::string Actual1; \ raw_string_ostream Stream(Actual1); \ encodeULEB128(VALUE, Stream, PAD); \ Stream.flush(); \ EXPECT_EQ(Expected, Actual1); \ \ /* encodeULEB128(uint64_t, uint8_t *, unsigned) */ \ uint8_t Buffer[32]; \ unsigned Size = encodeULEB128(VALUE, Buffer, PAD); \ std::string Actual2(reinterpret_cast<const char *>(Buffer), Size); \ EXPECT_EQ(Expected, Actual2); \ } while (0) // Encode ULEB128 EXPECT_ULEB128_EQ("\x00", 0, 0); EXPECT_ULEB128_EQ("\x01", 1, 0); EXPECT_ULEB128_EQ("\x3f", 63, 0); EXPECT_ULEB128_EQ("\x40", 64, 0); EXPECT_ULEB128_EQ("\x7f", 0x7f, 0); EXPECT_ULEB128_EQ("\x80\x01", 0x80, 0); EXPECT_ULEB128_EQ("\x81\x01", 0x81, 0); EXPECT_ULEB128_EQ("\x90\x01", 0x90, 0); EXPECT_ULEB128_EQ("\xff\x01", 0xff, 0); EXPECT_ULEB128_EQ("\x80\x02", 0x100, 0); EXPECT_ULEB128_EQ("\x81\x02", 0x101, 0); // Encode ULEB128 with some extra padding bytes EXPECT_ULEB128_EQ("\x80\x00", 0, 1); EXPECT_ULEB128_EQ("\x80\x80\x00", 0, 2); EXPECT_ULEB128_EQ("\xff\x00", 0x7f, 1); EXPECT_ULEB128_EQ("\xff\x80\x00", 0x7f, 2); EXPECT_ULEB128_EQ("\x80\x81\x00", 0x80, 1); EXPECT_ULEB128_EQ("\x80\x81\x80\x00", 0x80, 2); #undef EXPECT_ULEB128_EQ } TEST(LEB128Test, DecodeULEB128) { #define EXPECT_DECODE_ULEB128_EQ(EXPECTED, VALUE) \ do { \ unsigned ActualSize = 0; \ uint64_t Actual = decodeULEB128(reinterpret_cast<const uint8_t *>(VALUE), \ &ActualSize); \ EXPECT_EQ(sizeof(VALUE) - 1, ActualSize); \ EXPECT_EQ(EXPECTED, Actual); \ } while (0) // Decode ULEB128 EXPECT_DECODE_ULEB128_EQ(0u, "\x00"); EXPECT_DECODE_ULEB128_EQ(1u, "\x01"); EXPECT_DECODE_ULEB128_EQ(63u, "\x3f"); EXPECT_DECODE_ULEB128_EQ(64u, "\x40"); EXPECT_DECODE_ULEB128_EQ(0x7fu, "\x7f"); EXPECT_DECODE_ULEB128_EQ(0x80u, "\x80\x01"); EXPECT_DECODE_ULEB128_EQ(0x81u, "\x81\x01"); EXPECT_DECODE_ULEB128_EQ(0x90u, "\x90\x01"); EXPECT_DECODE_ULEB128_EQ(0xffu, "\xff\x01"); EXPECT_DECODE_ULEB128_EQ(0x100u, "\x80\x02"); EXPECT_DECODE_ULEB128_EQ(0x101u, "\x81\x02"); EXPECT_DECODE_ULEB128_EQ(4294975616ULL, "\x80\xc1\x80\x80\x10"); // Decode ULEB128 with extra padding bytes EXPECT_DECODE_ULEB128_EQ(0u, "\x80\x00"); EXPECT_DECODE_ULEB128_EQ(0u, "\x80\x80\x00"); EXPECT_DECODE_ULEB128_EQ(0x7fu, "\xff\x00"); EXPECT_DECODE_ULEB128_EQ(0x7fu, "\xff\x80\x00"); EXPECT_DECODE_ULEB128_EQ(0x80u, "\x80\x81\x00"); EXPECT_DECODE_ULEB128_EQ(0x80u, "\x80\x81\x80\x00"); #undef EXPECT_DECODE_ULEB128_EQ } TEST(LEB128Test, DecodeSLEB128) { #define EXPECT_DECODE_SLEB128_EQ(EXPECTED, VALUE) \ do { \ unsigned ActualSize = 0; \ int64_t Actual = decodeSLEB128(reinterpret_cast<const uint8_t *>(VALUE), \ &ActualSize); \ EXPECT_EQ(sizeof(VALUE) - 1, ActualSize); \ EXPECT_EQ(EXPECTED, Actual); \ } while (0) // Decode SLEB128 EXPECT_DECODE_SLEB128_EQ(0L, "\x00"); EXPECT_DECODE_SLEB128_EQ(1L, "\x01"); EXPECT_DECODE_SLEB128_EQ(63L, "\x3f"); EXPECT_DECODE_SLEB128_EQ(-64L, "\x40"); EXPECT_DECODE_SLEB128_EQ(-63L, "\x41"); EXPECT_DECODE_SLEB128_EQ(-1L, "\x7f"); EXPECT_DECODE_SLEB128_EQ(128L, "\x80\x01"); EXPECT_DECODE_SLEB128_EQ(129L, "\x81\x01"); EXPECT_DECODE_SLEB128_EQ(-129L, "\xff\x7e"); EXPECT_DECODE_SLEB128_EQ(-128L, "\x80\x7f"); EXPECT_DECODE_SLEB128_EQ(-127L, "\x81\x7f"); EXPECT_DECODE_SLEB128_EQ(64L, "\xc0\x00"); EXPECT_DECODE_SLEB128_EQ(-12345L, "\xc7\x9f\x7f"); // Decode unnormalized SLEB128 with extra padding bytes. EXPECT_DECODE_SLEB128_EQ(0L, "\x80\x00"); EXPECT_DECODE_SLEB128_EQ(0L, "\x80\x80\x00"); EXPECT_DECODE_SLEB128_EQ(0x7fL, "\xff\x00"); EXPECT_DECODE_SLEB128_EQ(0x7fL, "\xff\x80\x00"); EXPECT_DECODE_SLEB128_EQ(0x80L, "\x80\x81\x00"); EXPECT_DECODE_SLEB128_EQ(0x80L, "\x80\x81\x80\x00"); #undef EXPECT_DECODE_SLEB128_EQ } TEST(LEB128Test, SLEB128Size) { // Positive Value Testing Plan: // (1) 128 ^ n - 1 ........ need (n+1) bytes // (2) 128 ^ n ............ need (n+1) bytes // (3) 128 ^ n * 63 ....... need (n+1) bytes // (4) 128 ^ n * 64 - 1 ... need (n+1) bytes // (5) 128 ^ n * 64 ....... need (n+2) bytes EXPECT_EQ(1u, getSLEB128Size(0x0LL)); EXPECT_EQ(1u, getSLEB128Size(0x1LL)); EXPECT_EQ(1u, getSLEB128Size(0x3fLL)); EXPECT_EQ(1u, getSLEB128Size(0x3fLL)); EXPECT_EQ(2u, getSLEB128Size(0x40LL)); EXPECT_EQ(2u, getSLEB128Size(0x7fLL)); EXPECT_EQ(2u, getSLEB128Size(0x80LL)); EXPECT_EQ(2u, getSLEB128Size(0x1f80LL)); EXPECT_EQ(2u, getSLEB128Size(0x1fffLL)); EXPECT_EQ(3u, getSLEB128Size(0x2000LL)); EXPECT_EQ(3u, getSLEB128Size(0x3fffLL)); EXPECT_EQ(3u, getSLEB128Size(0x4000LL)); EXPECT_EQ(3u, getSLEB128Size(0xfc000LL)); EXPECT_EQ(3u, getSLEB128Size(0xfffffLL)); EXPECT_EQ(4u, getSLEB128Size(0x100000LL)); EXPECT_EQ(4u, getSLEB128Size(0x1fffffLL)); EXPECT_EQ(4u, getSLEB128Size(0x200000LL)); EXPECT_EQ(4u, getSLEB128Size(0x7e00000LL)); EXPECT_EQ(4u, getSLEB128Size(0x7ffffffLL)); EXPECT_EQ(5u, getSLEB128Size(0x8000000LL)); EXPECT_EQ(5u, getSLEB128Size(0xfffffffLL)); EXPECT_EQ(5u, getSLEB128Size(0x10000000LL)); EXPECT_EQ(5u, getSLEB128Size(0x3f0000000LL)); EXPECT_EQ(5u, getSLEB128Size(0x3ffffffffLL)); EXPECT_EQ(6u, getSLEB128Size(0x400000000LL)); EXPECT_EQ(6u, getSLEB128Size(0x7ffffffffLL)); EXPECT_EQ(6u, getSLEB128Size(0x800000000LL)); EXPECT_EQ(6u, getSLEB128Size(0x1f800000000LL)); EXPECT_EQ(6u, getSLEB128Size(0x1ffffffffffLL)); EXPECT_EQ(7u, getSLEB128Size(0x20000000000LL)); EXPECT_EQ(7u, getSLEB128Size(0x3ffffffffffLL)); EXPECT_EQ(7u, getSLEB128Size(0x40000000000LL)); EXPECT_EQ(7u, getSLEB128Size(0xfc0000000000LL)); EXPECT_EQ(7u, getSLEB128Size(0xffffffffffffLL)); EXPECT_EQ(8u, getSLEB128Size(0x1000000000000LL)); EXPECT_EQ(8u, getSLEB128Size(0x1ffffffffffffLL)); EXPECT_EQ(8u, getSLEB128Size(0x2000000000000LL)); EXPECT_EQ(8u, getSLEB128Size(0x7e000000000000LL)); EXPECT_EQ(8u, getSLEB128Size(0x7fffffffffffffLL)); EXPECT_EQ(9u, getSLEB128Size(0x80000000000000LL)); EXPECT_EQ(9u, getSLEB128Size(0xffffffffffffffLL)); EXPECT_EQ(9u, getSLEB128Size(0x100000000000000LL)); EXPECT_EQ(9u, getSLEB128Size(0x3f00000000000000LL)); EXPECT_EQ(9u, getSLEB128Size(0x3fffffffffffffffLL)); EXPECT_EQ(10u, getSLEB128Size(0x4000000000000000LL)); EXPECT_EQ(10u, getSLEB128Size(0x7fffffffffffffffLL)); EXPECT_EQ(10u, getSLEB128Size(INT64_MAX)); // Negative Value Testing Plan: // (1) - 128 ^ n - 1 ........ need (n+1) bytes // (2) - 128 ^ n ............ need (n+1) bytes // (3) - 128 ^ n * 63 ....... need (n+1) bytes // (4) - 128 ^ n * 64 ....... need (n+1) bytes (different from positive one) // (5) - 128 ^ n * 65 - 1 ... need (n+2) bytes (if n > 0) // (6) - 128 ^ n * 65 ....... need (n+2) bytes EXPECT_EQ(1u, getSLEB128Size(0x0LL)); EXPECT_EQ(1u, getSLEB128Size(-0x1LL)); EXPECT_EQ(1u, getSLEB128Size(-0x3fLL)); EXPECT_EQ(1u, getSLEB128Size(-0x40LL)); EXPECT_EQ(1u, getSLEB128Size(-0x40LL)); // special case EXPECT_EQ(2u, getSLEB128Size(-0x41LL)); EXPECT_EQ(2u, getSLEB128Size(-0x7fLL)); EXPECT_EQ(2u, getSLEB128Size(-0x80LL)); EXPECT_EQ(2u, getSLEB128Size(-0x1f80LL)); EXPECT_EQ(2u, getSLEB128Size(-0x2000LL)); EXPECT_EQ(3u, getSLEB128Size(-0x207fLL)); EXPECT_EQ(3u, getSLEB128Size(-0x2080LL)); EXPECT_EQ(3u, getSLEB128Size(-0x3fffLL)); EXPECT_EQ(3u, getSLEB128Size(-0x4000LL)); EXPECT_EQ(3u, getSLEB128Size(-0xfc000LL)); EXPECT_EQ(3u, getSLEB128Size(-0x100000LL)); EXPECT_EQ(4u, getSLEB128Size(-0x103fffLL)); EXPECT_EQ(4u, getSLEB128Size(-0x104000LL)); EXPECT_EQ(4u, getSLEB128Size(-0x1fffffLL)); EXPECT_EQ(4u, getSLEB128Size(-0x200000LL)); EXPECT_EQ(4u, getSLEB128Size(-0x7e00000LL)); EXPECT_EQ(4u, getSLEB128Size(-0x8000000LL)); EXPECT_EQ(5u, getSLEB128Size(-0x81fffffLL)); EXPECT_EQ(5u, getSLEB128Size(-0x8200000LL)); EXPECT_EQ(5u, getSLEB128Size(-0xfffffffLL)); EXPECT_EQ(5u, getSLEB128Size(-0x10000000LL)); EXPECT_EQ(5u, getSLEB128Size(-0x3f0000000LL)); EXPECT_EQ(5u, getSLEB128Size(-0x400000000LL)); EXPECT_EQ(6u, getSLEB128Size(-0x40fffffffLL)); EXPECT_EQ(6u, getSLEB128Size(-0x410000000LL)); EXPECT_EQ(6u, getSLEB128Size(-0x7ffffffffLL)); EXPECT_EQ(6u, getSLEB128Size(-0x800000000LL)); EXPECT_EQ(6u, getSLEB128Size(-0x1f800000000LL)); EXPECT_EQ(6u, getSLEB128Size(-0x20000000000LL)); EXPECT_EQ(7u, getSLEB128Size(-0x207ffffffffLL)); EXPECT_EQ(7u, getSLEB128Size(-0x20800000000LL)); EXPECT_EQ(7u, getSLEB128Size(-0x3ffffffffffLL)); EXPECT_EQ(7u, getSLEB128Size(-0x40000000000LL)); EXPECT_EQ(7u, getSLEB128Size(-0xfc0000000000LL)); EXPECT_EQ(7u, getSLEB128Size(-0x1000000000000LL)); EXPECT_EQ(8u, getSLEB128Size(-0x103ffffffffffLL)); EXPECT_EQ(8u, getSLEB128Size(-0x1040000000000LL)); EXPECT_EQ(8u, getSLEB128Size(-0x1ffffffffffffLL)); EXPECT_EQ(8u, getSLEB128Size(-0x2000000000000LL)); EXPECT_EQ(8u, getSLEB128Size(-0x7e000000000000LL)); EXPECT_EQ(8u, getSLEB128Size(-0x80000000000000LL)); EXPECT_EQ(9u, getSLEB128Size(-0x81ffffffffffffLL)); EXPECT_EQ(9u, getSLEB128Size(-0x82000000000000LL)); EXPECT_EQ(9u, getSLEB128Size(-0xffffffffffffffLL)); EXPECT_EQ(9u, getSLEB128Size(-0x100000000000000LL)); EXPECT_EQ(9u, getSLEB128Size(-0x3f00000000000000LL)); EXPECT_EQ(9u, getSLEB128Size(-0x4000000000000000LL)); EXPECT_EQ(10u, getSLEB128Size(-0x40ffffffffffffffLL)); EXPECT_EQ(10u, getSLEB128Size(-0x4100000000000000LL)); EXPECT_EQ(10u, getSLEB128Size(-0x7fffffffffffffffLL)); EXPECT_EQ(10u, getSLEB128Size(-0x8000000000000000LL)); EXPECT_EQ(10u, getSLEB128Size(INT64_MIN)); } TEST(LEB128Test, ULEB128Size) { // Testing Plan: // (1) 128 ^ n ............ need (n+1) bytes // (2) 128 ^ n * 64 ....... need (n+1) bytes // (3) 128 ^ (n+1) - 1 .... need (n+1) bytes EXPECT_EQ(1u, getULEB128Size(0)); // special case EXPECT_EQ(1u, getULEB128Size(0x1ULL)); EXPECT_EQ(1u, getULEB128Size(0x40ULL)); EXPECT_EQ(1u, getULEB128Size(0x7fULL)); EXPECT_EQ(2u, getULEB128Size(0x80ULL)); EXPECT_EQ(2u, getULEB128Size(0x2000ULL)); EXPECT_EQ(2u, getULEB128Size(0x3fffULL)); EXPECT_EQ(3u, getULEB128Size(0x4000ULL)); EXPECT_EQ(3u, getULEB128Size(0x100000ULL)); EXPECT_EQ(3u, getULEB128Size(0x1fffffULL)); EXPECT_EQ(4u, getULEB128Size(0x200000ULL)); EXPECT_EQ(4u, getULEB128Size(0x8000000ULL)); EXPECT_EQ(4u, getULEB128Size(0xfffffffULL)); EXPECT_EQ(5u, getULEB128Size(0x10000000ULL)); EXPECT_EQ(5u, getULEB128Size(0x400000000ULL)); EXPECT_EQ(5u, getULEB128Size(0x7ffffffffULL)); EXPECT_EQ(6u, getULEB128Size(0x800000000ULL)); EXPECT_EQ(6u, getULEB128Size(0x20000000000ULL)); EXPECT_EQ(6u, getULEB128Size(0x3ffffffffffULL)); EXPECT_EQ(7u, getULEB128Size(0x40000000000ULL)); EXPECT_EQ(7u, getULEB128Size(0x1000000000000ULL)); EXPECT_EQ(7u, getULEB128Size(0x1ffffffffffffULL)); EXPECT_EQ(8u, getULEB128Size(0x2000000000000ULL)); EXPECT_EQ(8u, getULEB128Size(0x80000000000000ULL)); EXPECT_EQ(8u, getULEB128Size(0xffffffffffffffULL)); EXPECT_EQ(9u, getULEB128Size(0x100000000000000ULL)); EXPECT_EQ(9u, getULEB128Size(0x4000000000000000ULL)); EXPECT_EQ(9u, getULEB128Size(0x7fffffffffffffffULL)); EXPECT_EQ(10u, getULEB128Size(0x8000000000000000ULL)); EXPECT_EQ(10u, getULEB128Size(UINT64_MAX)); } } // anonymous namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/EndianTest.cpp
//===- unittests/Support/EndianTest.cpp - Endian.h tests ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/Endian.h" #include "llvm/Support/DataTypes.h" #include "gtest/gtest.h" #include <cstdlib> #include <ctime> using namespace llvm; using namespace support; #undef max namespace { TEST(Endian, Read) { // These are 5 bytes so we can be sure at least one of the reads is unaligned. unsigned char bigval[] = {0x00, 0x01, 0x02, 0x03, 0x04}; unsigned char littleval[] = {0x00, 0x04, 0x03, 0x02, 0x01}; int32_t BigAsHost = 0x00010203; EXPECT_EQ(BigAsHost, (endian::read<int32_t, big, unaligned>(bigval))); int32_t LittleAsHost = 0x02030400; EXPECT_EQ(LittleAsHost,(endian::read<int32_t, little, unaligned>(littleval))); EXPECT_EQ((endian::read<int32_t, big, unaligned>(bigval + 1)), (endian::read<int32_t, little, unaligned>(littleval + 1))); } TEST(Endian, Write) { unsigned char data[5]; endian::write<int32_t, big, unaligned>(data, -1362446643); EXPECT_EQ(data[0], 0xAE); EXPECT_EQ(data[1], 0xCA); EXPECT_EQ(data[2], 0xB6); EXPECT_EQ(data[3], 0xCD); endian::write<int32_t, big, unaligned>(data + 1, -1362446643); EXPECT_EQ(data[1], 0xAE); EXPECT_EQ(data[2], 0xCA); EXPECT_EQ(data[3], 0xB6); EXPECT_EQ(data[4], 0xCD); endian::write<int32_t, little, unaligned>(data, -1362446643); EXPECT_EQ(data[0], 0xCD); EXPECT_EQ(data[1], 0xB6); EXPECT_EQ(data[2], 0xCA); EXPECT_EQ(data[3], 0xAE); endian::write<int32_t, little, unaligned>(data + 1, -1362446643); EXPECT_EQ(data[1], 0xCD); EXPECT_EQ(data[2], 0xB6); EXPECT_EQ(data[3], 0xCA); EXPECT_EQ(data[4], 0xAE); } TEST(Endian, PackedEndianSpecificIntegral) { // These are 5 bytes so we can be sure at least one of the reads is unaligned. unsigned char big[] = {0x00, 0x01, 0x02, 0x03, 0x04}; unsigned char little[] = {0x00, 0x04, 0x03, 0x02, 0x01}; big32_t *big_val = reinterpret_cast<big32_t *>(big + 1); little32_t *little_val = reinterpret_cast<little32_t *>(little + 1); EXPECT_EQ(*big_val, *little_val); } } // end anon namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/ScaledNumberTest.cpp
//===- llvm/unittest/Support/ScaledNumberTest.cpp - ScaledPair tests -----==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/ScaledNumber.h" #include "llvm/Support/DataTypes.h" #include "gtest/gtest.h" using namespace llvm; using namespace llvm::ScaledNumbers; namespace { template <class UIntT> struct ScaledPair { UIntT D; int S; ScaledPair(const std::pair<UIntT, int16_t> &F) : D(F.first), S(F.second) {} ScaledPair(UIntT D, int S) : D(D), S(S) {} bool operator==(const ScaledPair<UIntT> &X) const { return D == X.D && S == X.S; } }; template <class UIntT> bool operator==(const std::pair<UIntT, int16_t> &L, const ScaledPair<UIntT> &R) { return ScaledPair<UIntT>(L) == R; } template <class UIntT> void PrintTo(const ScaledPair<UIntT> &F, ::std::ostream *os) { *os << F.D << "*2^" << F.S; } typedef ScaledPair<uint32_t> SP32; typedef ScaledPair<uint64_t> SP64; TEST(ScaledNumberHelpersTest, getRounded) { EXPECT_EQ(getRounded32(0, 0, false), SP32(0, 0)); EXPECT_EQ(getRounded32(0, 0, true), SP32(1, 0)); EXPECT_EQ(getRounded32(20, 21, true), SP32(21, 21)); EXPECT_EQ(getRounded32(UINT32_MAX, 0, false), SP32(UINT32_MAX, 0)); EXPECT_EQ(getRounded32(UINT32_MAX, 0, true), SP32(1 << 31, 1)); EXPECT_EQ(getRounded64(0, 0, false), SP64(0, 0)); EXPECT_EQ(getRounded64(0, 0, true), SP64(1, 0)); EXPECT_EQ(getRounded64(20, 21, true), SP64(21, 21)); EXPECT_EQ(getRounded64(UINT32_MAX, 0, false), SP64(UINT32_MAX, 0)); EXPECT_EQ(getRounded64(UINT32_MAX, 0, true), SP64(UINT64_C(1) << 32, 0)); EXPECT_EQ(getRounded64(UINT64_MAX, 0, false), SP64(UINT64_MAX, 0)); EXPECT_EQ(getRounded64(UINT64_MAX, 0, true), SP64(UINT64_C(1) << 63, 1)); } TEST(ScaledNumberHelpersTest, getAdjusted) { const uint64_t Max32In64 = UINT32_MAX; EXPECT_EQ(getAdjusted32(0), SP32(0, 0)); EXPECT_EQ(getAdjusted32(0, 5), SP32(0, 5)); EXPECT_EQ(getAdjusted32(UINT32_MAX), SP32(UINT32_MAX, 0)); EXPECT_EQ(getAdjusted32(Max32In64 << 1), SP32(UINT32_MAX, 1)); EXPECT_EQ(getAdjusted32(Max32In64 << 1, 1), SP32(UINT32_MAX, 2)); EXPECT_EQ(getAdjusted32(Max32In64 << 31), SP32(UINT32_MAX, 31)); EXPECT_EQ(getAdjusted32(Max32In64 << 32), SP32(UINT32_MAX, 32)); EXPECT_EQ(getAdjusted32(Max32In64 + 1), SP32(1u << 31, 1)); EXPECT_EQ(getAdjusted32(UINT64_MAX), SP32(1u << 31, 33)); EXPECT_EQ(getAdjusted64(0), SP64(0, 0)); EXPECT_EQ(getAdjusted64(0, 5), SP64(0, 5)); EXPECT_EQ(getAdjusted64(UINT32_MAX), SP64(UINT32_MAX, 0)); EXPECT_EQ(getAdjusted64(Max32In64 << 1), SP64(Max32In64 << 1, 0)); EXPECT_EQ(getAdjusted64(Max32In64 << 1, 1), SP64(Max32In64 << 1, 1)); EXPECT_EQ(getAdjusted64(Max32In64 << 31), SP64(Max32In64 << 31, 0)); EXPECT_EQ(getAdjusted64(Max32In64 << 32), SP64(Max32In64 << 32, 0)); EXPECT_EQ(getAdjusted64(Max32In64 + 1), SP64(Max32In64 + 1, 0)); EXPECT_EQ(getAdjusted64(UINT64_MAX), SP64(UINT64_MAX, 0)); } TEST(ScaledNumberHelpersTest, getProduct) { // Zero. EXPECT_EQ(SP32(0, 0), getProduct32(0, 0)); EXPECT_EQ(SP32(0, 0), getProduct32(0, 1)); EXPECT_EQ(SP32(0, 0), getProduct32(0, 33)); // Basic. EXPECT_EQ(SP32(6, 0), getProduct32(2, 3)); EXPECT_EQ(SP32(UINT16_MAX / 3 * UINT16_MAX / 5 * 2, 0), getProduct32(UINT16_MAX / 3, UINT16_MAX / 5 * 2)); // Overflow, no loss of precision. // ==> 0xf00010 * 0x1001 // ==> 0xf00f00000 + 0x10010 // ==> 0xf00f10010 // ==> 0xf00f1001 * 2^4 EXPECT_EQ(SP32(0xf00f1001, 4), getProduct32(0xf00010, 0x1001)); // Overflow, loss of precision, rounds down. // ==> 0xf000070 * 0x1001 // ==> 0xf00f000000 + 0x70070 // ==> 0xf00f070070 // ==> 0xf00f0700 * 2^8 EXPECT_EQ(SP32(0xf00f0700, 8), getProduct32(0xf000070, 0x1001)); // Overflow, loss of precision, rounds up. // ==> 0xf000080 * 0x1001 // ==> 0xf00f000000 + 0x80080 // ==> 0xf00f080080 // ==> 0xf00f0801 * 2^8 EXPECT_EQ(SP32(0xf00f0801, 8), getProduct32(0xf000080, 0x1001)); // Reverse operand order. EXPECT_EQ(SP32(0, 0), getProduct32(1, 0)); EXPECT_EQ(SP32(0, 0), getProduct32(33, 0)); EXPECT_EQ(SP32(6, 0), getProduct32(3, 2)); EXPECT_EQ(SP32(UINT16_MAX / 3 * UINT16_MAX / 5 * 2, 0), getProduct32(UINT16_MAX / 5 * 2, UINT16_MAX / 3)); EXPECT_EQ(SP32(0xf00f1001, 4), getProduct32(0x1001, 0xf00010)); EXPECT_EQ(SP32(0xf00f0700, 8), getProduct32(0x1001, 0xf000070)); EXPECT_EQ(SP32(0xf00f0801, 8), getProduct32(0x1001, 0xf000080)); // Round to overflow. EXPECT_EQ(SP64(UINT64_C(1) << 63, 64), getProduct64(UINT64_C(10376293541461622786), UINT64_C(16397105843297379211))); // Big number with rounding. EXPECT_EQ(SP64(UINT64_C(9223372036854775810), 64), getProduct64(UINT64_C(18446744073709551556), UINT64_C(9223372036854775840))); } TEST(ScaledNumberHelpersTest, getQuotient) { // Zero. EXPECT_EQ(SP32(0, 0), getQuotient32(0, 0)); EXPECT_EQ(SP32(0, 0), getQuotient32(0, 1)); EXPECT_EQ(SP32(0, 0), getQuotient32(0, 73)); EXPECT_EQ(SP32(UINT32_MAX, MaxScale), getQuotient32(1, 0)); EXPECT_EQ(SP32(UINT32_MAX, MaxScale), getQuotient32(6, 0)); // Powers of two. EXPECT_EQ(SP32(1u << 31, -31), getQuotient32(1, 1)); EXPECT_EQ(SP32(1u << 31, -30), getQuotient32(2, 1)); EXPECT_EQ(SP32(1u << 31, -33), getQuotient32(4, 16)); EXPECT_EQ(SP32(7u << 29, -29), getQuotient32(7, 1)); EXPECT_EQ(SP32(7u << 29, -30), getQuotient32(7, 2)); EXPECT_EQ(SP32(7u << 29, -33), getQuotient32(7, 16)); // Divide evenly. EXPECT_EQ(SP32(3u << 30, -30), getQuotient32(9, 3)); EXPECT_EQ(SP32(9u << 28, -28), getQuotient32(63, 7)); // Divide unevenly. EXPECT_EQ(SP32(0xaaaaaaab, -33), getQuotient32(1, 3)); EXPECT_EQ(SP32(0xd5555555, -31), getQuotient32(5, 3)); // 64-bit division is hard to test, since divide64 doesn't canonicalize its // output. However, this is the algorithm the implementation uses: // // - Shift divisor right. // - If we have 1 (power of 2), return early -- not canonicalized. // - Shift dividend left. // - 64-bit integer divide. // - If there's a remainder, continue with long division. // // TODO: require less knowledge about the implementation in the test. // Zero. EXPECT_EQ(SP64(0, 0), getQuotient64(0, 0)); EXPECT_EQ(SP64(0, 0), getQuotient64(0, 1)); EXPECT_EQ(SP64(0, 0), getQuotient64(0, 73)); EXPECT_EQ(SP64(UINT64_MAX, MaxScale), getQuotient64(1, 0)); EXPECT_EQ(SP64(UINT64_MAX, MaxScale), getQuotient64(6, 0)); // Powers of two. EXPECT_EQ(SP64(1, 0), getQuotient64(1, 1)); EXPECT_EQ(SP64(2, 0), getQuotient64(2, 1)); EXPECT_EQ(SP64(4, -4), getQuotient64(4, 16)); EXPECT_EQ(SP64(7, 0), getQuotient64(7, 1)); EXPECT_EQ(SP64(7, -1), getQuotient64(7, 2)); EXPECT_EQ(SP64(7, -4), getQuotient64(7, 16)); // Divide evenly. EXPECT_EQ(SP64(UINT64_C(3) << 60, -60), getQuotient64(9, 3)); EXPECT_EQ(SP64(UINT64_C(9) << 58, -58), getQuotient64(63, 7)); // Divide unevenly. EXPECT_EQ(SP64(0xaaaaaaaaaaaaaaab, -65), getQuotient64(1, 3)); EXPECT_EQ(SP64(0xd555555555555555, -63), getQuotient64(5, 3)); } TEST(ScaledNumberHelpersTest, getLg) { EXPECT_EQ(0, getLg(UINT32_C(1), 0)); EXPECT_EQ(1, getLg(UINT32_C(1), 1)); EXPECT_EQ(1, getLg(UINT32_C(2), 0)); EXPECT_EQ(3, getLg(UINT32_C(1), 3)); EXPECT_EQ(3, getLg(UINT32_C(7), 0)); EXPECT_EQ(3, getLg(UINT32_C(8), 0)); EXPECT_EQ(3, getLg(UINT32_C(9), 0)); EXPECT_EQ(3, getLg(UINT32_C(64), -3)); EXPECT_EQ(31, getLg((UINT32_MAX >> 1) + 2, 0)); EXPECT_EQ(32, getLg(UINT32_MAX, 0)); EXPECT_EQ(-1, getLg(UINT32_C(1), -1)); EXPECT_EQ(-1, getLg(UINT32_C(2), -2)); EXPECT_EQ(INT32_MIN, getLg(UINT32_C(0), -1)); EXPECT_EQ(INT32_MIN, getLg(UINT32_C(0), 0)); EXPECT_EQ(INT32_MIN, getLg(UINT32_C(0), 1)); EXPECT_EQ(0, getLg(UINT64_C(1), 0)); EXPECT_EQ(1, getLg(UINT64_C(1), 1)); EXPECT_EQ(1, getLg(UINT64_C(2), 0)); EXPECT_EQ(3, getLg(UINT64_C(1), 3)); EXPECT_EQ(3, getLg(UINT64_C(7), 0)); EXPECT_EQ(3, getLg(UINT64_C(8), 0)); EXPECT_EQ(3, getLg(UINT64_C(9), 0)); EXPECT_EQ(3, getLg(UINT64_C(64), -3)); EXPECT_EQ(63, getLg((UINT64_MAX >> 1) + 2, 0)); EXPECT_EQ(64, getLg(UINT64_MAX, 0)); EXPECT_EQ(-1, getLg(UINT64_C(1), -1)); EXPECT_EQ(-1, getLg(UINT64_C(2), -2)); EXPECT_EQ(INT32_MIN, getLg(UINT64_C(0), -1)); EXPECT_EQ(INT32_MIN, getLg(UINT64_C(0), 0)); EXPECT_EQ(INT32_MIN, getLg(UINT64_C(0), 1)); } TEST(ScaledNumberHelpersTest, getLgFloor) { EXPECT_EQ(0, getLgFloor(UINT32_C(1), 0)); EXPECT_EQ(1, getLgFloor(UINT32_C(1), 1)); EXPECT_EQ(1, getLgFloor(UINT32_C(2), 0)); EXPECT_EQ(2, getLgFloor(UINT32_C(7), 0)); EXPECT_EQ(3, getLgFloor(UINT32_C(1), 3)); EXPECT_EQ(3, getLgFloor(UINT32_C(8), 0)); EXPECT_EQ(3, getLgFloor(UINT32_C(9), 0)); EXPECT_EQ(3, getLgFloor(UINT32_C(64), -3)); EXPECT_EQ(31, getLgFloor((UINT32_MAX >> 1) + 2, 0)); EXPECT_EQ(31, getLgFloor(UINT32_MAX, 0)); EXPECT_EQ(INT32_MIN, getLgFloor(UINT32_C(0), -1)); EXPECT_EQ(INT32_MIN, getLgFloor(UINT32_C(0), 0)); EXPECT_EQ(INT32_MIN, getLgFloor(UINT32_C(0), 1)); EXPECT_EQ(0, getLgFloor(UINT64_C(1), 0)); EXPECT_EQ(1, getLgFloor(UINT64_C(1), 1)); EXPECT_EQ(1, getLgFloor(UINT64_C(2), 0)); EXPECT_EQ(2, getLgFloor(UINT64_C(7), 0)); EXPECT_EQ(3, getLgFloor(UINT64_C(1), 3)); EXPECT_EQ(3, getLgFloor(UINT64_C(8), 0)); EXPECT_EQ(3, getLgFloor(UINT64_C(9), 0)); EXPECT_EQ(3, getLgFloor(UINT64_C(64), -3)); EXPECT_EQ(63, getLgFloor((UINT64_MAX >> 1) + 2, 0)); EXPECT_EQ(63, getLgFloor(UINT64_MAX, 0)); EXPECT_EQ(INT32_MIN, getLgFloor(UINT64_C(0), -1)); EXPECT_EQ(INT32_MIN, getLgFloor(UINT64_C(0), 0)); EXPECT_EQ(INT32_MIN, getLgFloor(UINT64_C(0), 1)); } TEST(ScaledNumberHelpersTest, getLgCeiling) { EXPECT_EQ(0, getLgCeiling(UINT32_C(1), 0)); EXPECT_EQ(1, getLgCeiling(UINT32_C(1), 1)); EXPECT_EQ(1, getLgCeiling(UINT32_C(2), 0)); EXPECT_EQ(3, getLgCeiling(UINT32_C(1), 3)); EXPECT_EQ(3, getLgCeiling(UINT32_C(7), 0)); EXPECT_EQ(3, getLgCeiling(UINT32_C(8), 0)); EXPECT_EQ(3, getLgCeiling(UINT32_C(64), -3)); EXPECT_EQ(4, getLgCeiling(UINT32_C(9), 0)); EXPECT_EQ(32, getLgCeiling(UINT32_MAX, 0)); EXPECT_EQ(32, getLgCeiling((UINT32_MAX >> 1) + 2, 0)); EXPECT_EQ(INT32_MIN, getLgCeiling(UINT32_C(0), -1)); EXPECT_EQ(INT32_MIN, getLgCeiling(UINT32_C(0), 0)); EXPECT_EQ(INT32_MIN, getLgCeiling(UINT32_C(0), 1)); EXPECT_EQ(0, getLgCeiling(UINT64_C(1), 0)); EXPECT_EQ(1, getLgCeiling(UINT64_C(1), 1)); EXPECT_EQ(1, getLgCeiling(UINT64_C(2), 0)); EXPECT_EQ(3, getLgCeiling(UINT64_C(1), 3)); EXPECT_EQ(3, getLgCeiling(UINT64_C(7), 0)); EXPECT_EQ(3, getLgCeiling(UINT64_C(8), 0)); EXPECT_EQ(3, getLgCeiling(UINT64_C(64), -3)); EXPECT_EQ(4, getLgCeiling(UINT64_C(9), 0)); EXPECT_EQ(64, getLgCeiling((UINT64_MAX >> 1) + 2, 0)); EXPECT_EQ(64, getLgCeiling(UINT64_MAX, 0)); EXPECT_EQ(INT32_MIN, getLgCeiling(UINT64_C(0), -1)); EXPECT_EQ(INT32_MIN, getLgCeiling(UINT64_C(0), 0)); EXPECT_EQ(INT32_MIN, getLgCeiling(UINT64_C(0), 1)); } TEST(ScaledNumberHelpersTest, compare) { EXPECT_EQ(0, compare(UINT32_C(0), 0, UINT32_C(0), 1)); EXPECT_EQ(0, compare(UINT32_C(0), 0, UINT32_C(0), -10)); EXPECT_EQ(0, compare(UINT32_C(0), 0, UINT32_C(0), 20)); EXPECT_EQ(0, compare(UINT32_C(8), 0, UINT32_C(64), -3)); EXPECT_EQ(0, compare(UINT32_C(8), 0, UINT32_C(32), -2)); EXPECT_EQ(0, compare(UINT32_C(8), 0, UINT32_C(16), -1)); EXPECT_EQ(0, compare(UINT32_C(8), 0, UINT32_C(8), 0)); EXPECT_EQ(0, compare(UINT32_C(8), 0, UINT32_C(4), 1)); EXPECT_EQ(0, compare(UINT32_C(8), 0, UINT32_C(2), 2)); EXPECT_EQ(0, compare(UINT32_C(8), 0, UINT32_C(1), 3)); EXPECT_EQ(-1, compare(UINT32_C(0), 0, UINT32_C(1), 3)); EXPECT_EQ(-1, compare(UINT32_C(7), 0, UINT32_C(1), 3)); EXPECT_EQ(-1, compare(UINT32_C(7), 0, UINT32_C(64), -3)); EXPECT_EQ(1, compare(UINT32_C(9), 0, UINT32_C(1), 3)); EXPECT_EQ(1, compare(UINT32_C(9), 0, UINT32_C(64), -3)); EXPECT_EQ(1, compare(UINT32_C(9), 0, UINT32_C(0), 0)); EXPECT_EQ(0, compare(UINT64_C(0), 0, UINT64_C(0), 1)); EXPECT_EQ(0, compare(UINT64_C(0), 0, UINT64_C(0), -10)); EXPECT_EQ(0, compare(UINT64_C(0), 0, UINT64_C(0), 20)); EXPECT_EQ(0, compare(UINT64_C(8), 0, UINT64_C(64), -3)); EXPECT_EQ(0, compare(UINT64_C(8), 0, UINT64_C(32), -2)); EXPECT_EQ(0, compare(UINT64_C(8), 0, UINT64_C(16), -1)); EXPECT_EQ(0, compare(UINT64_C(8), 0, UINT64_C(8), 0)); EXPECT_EQ(0, compare(UINT64_C(8), 0, UINT64_C(4), 1)); EXPECT_EQ(0, compare(UINT64_C(8), 0, UINT64_C(2), 2)); EXPECT_EQ(0, compare(UINT64_C(8), 0, UINT64_C(1), 3)); EXPECT_EQ(-1, compare(UINT64_C(0), 0, UINT64_C(1), 3)); EXPECT_EQ(-1, compare(UINT64_C(7), 0, UINT64_C(1), 3)); EXPECT_EQ(-1, compare(UINT64_C(7), 0, UINT64_C(64), -3)); EXPECT_EQ(1, compare(UINT64_C(9), 0, UINT64_C(1), 3)); EXPECT_EQ(1, compare(UINT64_C(9), 0, UINT64_C(64), -3)); EXPECT_EQ(1, compare(UINT64_C(9), 0, UINT64_C(0), 0)); EXPECT_EQ(-1, compare(UINT64_MAX, 0, UINT64_C(1), 64)); } TEST(ScaledNumberHelpersTest, matchScales) { #define MATCH_SCALES(T, LDIn, LSIn, RDIn, RSIn, LDOut, RDOut, SOut) \ do { \ T LDx = LDIn; \ T RDx = RDIn; \ T LDy = LDOut; \ T RDy = RDOut; \ int16_t LSx = LSIn; \ int16_t RSx = RSIn; \ int16_t Sy = SOut; \ \ EXPECT_EQ(SOut, matchScales(LDx, LSx, RDx, RSx)); \ EXPECT_EQ(LDy, LDx); \ EXPECT_EQ(RDy, RDx); \ if (LDy) \ EXPECT_EQ(Sy, LSx); \ if (RDy) \ EXPECT_EQ(Sy, RSx); \ } while (false) MATCH_SCALES(uint32_t, 0, 0, 0, 0, 0, 0, 0); MATCH_SCALES(uint32_t, 0, 50, 7, 1, 0, 7, 1); MATCH_SCALES(uint32_t, UINT32_C(1) << 31, 1, 9, 0, UINT32_C(1) << 31, 4, 1); MATCH_SCALES(uint32_t, UINT32_C(1) << 31, 2, 9, 0, UINT32_C(1) << 31, 2, 2); MATCH_SCALES(uint32_t, UINT32_C(1) << 31, 3, 9, 0, UINT32_C(1) << 31, 1, 3); MATCH_SCALES(uint32_t, UINT32_C(1) << 31, 4, 9, 0, UINT32_C(1) << 31, 0, 4); MATCH_SCALES(uint32_t, UINT32_C(1) << 30, 4, 9, 0, UINT32_C(1) << 31, 1, 3); MATCH_SCALES(uint32_t, UINT32_C(1) << 29, 4, 9, 0, UINT32_C(1) << 31, 2, 2); MATCH_SCALES(uint32_t, UINT32_C(1) << 28, 4, 9, 0, UINT32_C(1) << 31, 4, 1); MATCH_SCALES(uint32_t, UINT32_C(1) << 27, 4, 9, 0, UINT32_C(1) << 31, 9, 0); MATCH_SCALES(uint32_t, 7, 1, 0, 50, 7, 0, 1); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 31, 1, 4, UINT32_C(1) << 31, 1); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 31, 2, 2, UINT32_C(1) << 31, 2); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 31, 3, 1, UINT32_C(1) << 31, 3); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 31, 4, 0, UINT32_C(1) << 31, 4); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 30, 4, 1, UINT32_C(1) << 31, 3); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 29, 4, 2, UINT32_C(1) << 31, 2); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 28, 4, 4, UINT32_C(1) << 31, 1); MATCH_SCALES(uint32_t, 9, 0, UINT32_C(1) << 27, 4, 9, UINT32_C(1) << 31, 0); MATCH_SCALES(uint64_t, 0, 0, 0, 0, 0, 0, 0); MATCH_SCALES(uint64_t, 0, 100, 7, 1, 0, 7, 1); MATCH_SCALES(uint64_t, UINT64_C(1) << 63, 1, 9, 0, UINT64_C(1) << 63, 4, 1); MATCH_SCALES(uint64_t, UINT64_C(1) << 63, 2, 9, 0, UINT64_C(1) << 63, 2, 2); MATCH_SCALES(uint64_t, UINT64_C(1) << 63, 3, 9, 0, UINT64_C(1) << 63, 1, 3); MATCH_SCALES(uint64_t, UINT64_C(1) << 63, 4, 9, 0, UINT64_C(1) << 63, 0, 4); MATCH_SCALES(uint64_t, UINT64_C(1) << 62, 4, 9, 0, UINT64_C(1) << 63, 1, 3); MATCH_SCALES(uint64_t, UINT64_C(1) << 61, 4, 9, 0, UINT64_C(1) << 63, 2, 2); MATCH_SCALES(uint64_t, UINT64_C(1) << 60, 4, 9, 0, UINT64_C(1) << 63, 4, 1); MATCH_SCALES(uint64_t, UINT64_C(1) << 59, 4, 9, 0, UINT64_C(1) << 63, 9, 0); MATCH_SCALES(uint64_t, 7, 1, 0, 100, 7, 0, 1); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 63, 1, 4, UINT64_C(1) << 63, 1); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 63, 2, 2, UINT64_C(1) << 63, 2); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 63, 3, 1, UINT64_C(1) << 63, 3); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 63, 4, 0, UINT64_C(1) << 63, 4); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 62, 4, 1, UINT64_C(1) << 63, 3); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 61, 4, 2, UINT64_C(1) << 63, 2); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 60, 4, 4, UINT64_C(1) << 63, 1); MATCH_SCALES(uint64_t, 9, 0, UINT64_C(1) << 59, 4, 9, UINT64_C(1) << 63, 0); } TEST(ScaledNumberHelpersTest, getSum) { // Zero. EXPECT_EQ(SP32(1, 0), getSum32(0, 0, 1, 0)); EXPECT_EQ(SP32(8, -3), getSum32(0, 0, 8, -3)); EXPECT_EQ(SP32(UINT32_MAX, 0), getSum32(0, 0, UINT32_MAX, 0)); // Basic. EXPECT_EQ(SP32(2, 0), getSum32(1, 0, 1, 0)); EXPECT_EQ(SP32(3, 0), getSum32(1, 0, 2, 0)); EXPECT_EQ(SP32(67, 0), getSum32(7, 0, 60, 0)); // Different scales. EXPECT_EQ(SP32(3, 0), getSum32(1, 0, 1, 1)); EXPECT_EQ(SP32(4, 0), getSum32(2, 0, 1, 1)); // Loss of precision. EXPECT_EQ(SP32(UINT32_C(1) << 31, 1), getSum32(1, 32, 1, 0)); EXPECT_EQ(SP32(UINT32_C(1) << 31, -31), getSum32(1, -32, 1, 0)); // Not quite loss of precision. EXPECT_EQ(SP32((UINT32_C(1) << 31) + 1, 1), getSum32(1, 32, 1, 1)); EXPECT_EQ(SP32((UINT32_C(1) << 31) + 1, -32), getSum32(1, -32, 1, -1)); // Overflow. EXPECT_EQ(SP32(UINT32_C(1) << 31, 1), getSum32(1, 0, UINT32_MAX, 0)); // Reverse operand order. EXPECT_EQ(SP32(1, 0), getSum32(1, 0, 0, 0)); EXPECT_EQ(SP32(8, -3), getSum32(8, -3, 0, 0)); EXPECT_EQ(SP32(UINT32_MAX, 0), getSum32(UINT32_MAX, 0, 0, 0)); EXPECT_EQ(SP32(3, 0), getSum32(2, 0, 1, 0)); EXPECT_EQ(SP32(67, 0), getSum32(60, 0, 7, 0)); EXPECT_EQ(SP32(3, 0), getSum32(1, 1, 1, 0)); EXPECT_EQ(SP32(4, 0), getSum32(1, 1, 2, 0)); EXPECT_EQ(SP32(UINT32_C(1) << 31, 1), getSum32(1, 0, 1, 32)); EXPECT_EQ(SP32(UINT32_C(1) << 31, -31), getSum32(1, 0, 1, -32)); EXPECT_EQ(SP32((UINT32_C(1) << 31) + 1, 1), getSum32(1, 1, 1, 32)); EXPECT_EQ(SP32((UINT32_C(1) << 31) + 1, -32), getSum32(1, -1, 1, -32)); EXPECT_EQ(SP32(UINT32_C(1) << 31, 1), getSum32(UINT32_MAX, 0, 1, 0)); // Zero. EXPECT_EQ(SP64(1, 0), getSum64(0, 0, 1, 0)); EXPECT_EQ(SP64(8, -3), getSum64(0, 0, 8, -3)); EXPECT_EQ(SP64(UINT64_MAX, 0), getSum64(0, 0, UINT64_MAX, 0)); // Basic. EXPECT_EQ(SP64(2, 0), getSum64(1, 0, 1, 0)); EXPECT_EQ(SP64(3, 0), getSum64(1, 0, 2, 0)); EXPECT_EQ(SP64(67, 0), getSum64(7, 0, 60, 0)); // Different scales. EXPECT_EQ(SP64(3, 0), getSum64(1, 0, 1, 1)); EXPECT_EQ(SP64(4, 0), getSum64(2, 0, 1, 1)); // Loss of precision. EXPECT_EQ(SP64(UINT64_C(1) << 63, 1), getSum64(1, 64, 1, 0)); EXPECT_EQ(SP64(UINT64_C(1) << 63, -63), getSum64(1, -64, 1, 0)); // Not quite loss of precision. EXPECT_EQ(SP64((UINT64_C(1) << 63) + 1, 1), getSum64(1, 64, 1, 1)); EXPECT_EQ(SP64((UINT64_C(1) << 63) + 1, -64), getSum64(1, -64, 1, -1)); // Overflow. EXPECT_EQ(SP64(UINT64_C(1) << 63, 1), getSum64(1, 0, UINT64_MAX, 0)); // Reverse operand order. EXPECT_EQ(SP64(1, 0), getSum64(1, 0, 0, 0)); EXPECT_EQ(SP64(8, -3), getSum64(8, -3, 0, 0)); EXPECT_EQ(SP64(UINT64_MAX, 0), getSum64(UINT64_MAX, 0, 0, 0)); EXPECT_EQ(SP64(3, 0), getSum64(2, 0, 1, 0)); EXPECT_EQ(SP64(67, 0), getSum64(60, 0, 7, 0)); EXPECT_EQ(SP64(3, 0), getSum64(1, 1, 1, 0)); EXPECT_EQ(SP64(4, 0), getSum64(1, 1, 2, 0)); EXPECT_EQ(SP64(UINT64_C(1) << 63, 1), getSum64(1, 0, 1, 64)); EXPECT_EQ(SP64(UINT64_C(1) << 63, -63), getSum64(1, 0, 1, -64)); EXPECT_EQ(SP64((UINT64_C(1) << 63) + 1, 1), getSum64(1, 1, 1, 64)); EXPECT_EQ(SP64((UINT64_C(1) << 63) + 1, -64), getSum64(1, -1, 1, -64)); EXPECT_EQ(SP64(UINT64_C(1) << 63, 1), getSum64(UINT64_MAX, 0, 1, 0)); } TEST(ScaledNumberHelpersTest, getDifference) { // Basic. EXPECT_EQ(SP32(0, 0), getDifference32(1, 0, 1, 0)); EXPECT_EQ(SP32(1, 0), getDifference32(2, 0, 1, 0)); EXPECT_EQ(SP32(53, 0), getDifference32(60, 0, 7, 0)); // Equals "0", different scales. EXPECT_EQ(SP32(0, 0), getDifference32(2, 0, 1, 1)); // Subtract "0". EXPECT_EQ(SP32(1, 0), getDifference32(1, 0, 0, 0)); EXPECT_EQ(SP32(8, -3), getDifference32(8, -3, 0, 0)); EXPECT_EQ(SP32(UINT32_MAX, 0), getDifference32(UINT32_MAX, 0, 0, 0)); // Loss of precision. EXPECT_EQ(SP32((UINT32_C(1) << 31) + 1, 1), getDifference32((UINT32_C(1) << 31) + 1, 1, 1, 0)); EXPECT_EQ(SP32((UINT32_C(1) << 31) + 1, -31), getDifference32((UINT32_C(1) << 31) + 1, -31, 1, -32)); // Not quite loss of precision. EXPECT_EQ(SP32(UINT32_MAX, 0), getDifference32(1, 32, 1, 0)); EXPECT_EQ(SP32(UINT32_MAX, -32), getDifference32(1, 0, 1, -32)); // Saturate to "0". EXPECT_EQ(SP32(0, 0), getDifference32(0, 0, 1, 0)); EXPECT_EQ(SP32(0, 0), getDifference32(0, 0, 8, -3)); EXPECT_EQ(SP32(0, 0), getDifference32(0, 0, UINT32_MAX, 0)); EXPECT_EQ(SP32(0, 0), getDifference32(7, 0, 60, 0)); EXPECT_EQ(SP32(0, 0), getDifference32(1, 0, 1, 1)); EXPECT_EQ(SP32(0, 0), getDifference32(1, -32, 1, 0)); EXPECT_EQ(SP32(0, 0), getDifference32(1, -32, 1, -1)); // Regression tests for cases that failed during bringup. EXPECT_EQ(SP32(UINT32_C(1) << 26, -31), getDifference32(1, 0, UINT32_C(31) << 27, -32)); // Basic. EXPECT_EQ(SP64(0, 0), getDifference64(1, 0, 1, 0)); EXPECT_EQ(SP64(1, 0), getDifference64(2, 0, 1, 0)); EXPECT_EQ(SP64(53, 0), getDifference64(60, 0, 7, 0)); // Equals "0", different scales. EXPECT_EQ(SP64(0, 0), getDifference64(2, 0, 1, 1)); // Subtract "0". EXPECT_EQ(SP64(1, 0), getDifference64(1, 0, 0, 0)); EXPECT_EQ(SP64(8, -3), getDifference64(8, -3, 0, 0)); EXPECT_EQ(SP64(UINT64_MAX, 0), getDifference64(UINT64_MAX, 0, 0, 0)); // Loss of precision. EXPECT_EQ(SP64((UINT64_C(1) << 63) + 1, 1), getDifference64((UINT64_C(1) << 63) + 1, 1, 1, 0)); EXPECT_EQ(SP64((UINT64_C(1) << 63) + 1, -63), getDifference64((UINT64_C(1) << 63) + 1, -63, 1, -64)); // Not quite loss of precision. EXPECT_EQ(SP64(UINT64_MAX, 0), getDifference64(1, 64, 1, 0)); EXPECT_EQ(SP64(UINT64_MAX, -64), getDifference64(1, 0, 1, -64)); // Saturate to "0". EXPECT_EQ(SP64(0, 0), getDifference64(0, 0, 1, 0)); EXPECT_EQ(SP64(0, 0), getDifference64(0, 0, 8, -3)); EXPECT_EQ(SP64(0, 0), getDifference64(0, 0, UINT64_MAX, 0)); EXPECT_EQ(SP64(0, 0), getDifference64(7, 0, 60, 0)); EXPECT_EQ(SP64(0, 0), getDifference64(1, 0, 1, 1)); EXPECT_EQ(SP64(0, 0), getDifference64(1, -64, 1, 0)); EXPECT_EQ(SP64(0, 0), getDifference64(1, -64, 1, -1)); } TEST(ScaledNumberHelpersTest, arithmeticOperators) { EXPECT_EQ(ScaledNumber<uint32_t>(10, 0), ScaledNumber<uint32_t>(1, 3) + ScaledNumber<uint32_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint32_t>(6, 0), ScaledNumber<uint32_t>(1, 3) - ScaledNumber<uint32_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint32_t>(2, 3), ScaledNumber<uint32_t>(1, 3) * ScaledNumber<uint32_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint32_t>(1, 2), ScaledNumber<uint32_t>(1, 3) / ScaledNumber<uint32_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint32_t>(1, 2), ScaledNumber<uint32_t>(1, 3) >> 1); EXPECT_EQ(ScaledNumber<uint32_t>(1, 4), ScaledNumber<uint32_t>(1, 3) << 1); EXPECT_EQ(ScaledNumber<uint64_t>(10, 0), ScaledNumber<uint64_t>(1, 3) + ScaledNumber<uint64_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint64_t>(6, 0), ScaledNumber<uint64_t>(1, 3) - ScaledNumber<uint64_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint64_t>(2, 3), ScaledNumber<uint64_t>(1, 3) * ScaledNumber<uint64_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint64_t>(1, 2), ScaledNumber<uint64_t>(1, 3) / ScaledNumber<uint64_t>(1, 1)); EXPECT_EQ(ScaledNumber<uint64_t>(1, 2), ScaledNumber<uint64_t>(1, 3) >> 1); EXPECT_EQ(ScaledNumber<uint64_t>(1, 4), ScaledNumber<uint64_t>(1, 3) << 1); } TEST(ScaledNumberHelpersTest, toIntBug) { ScaledNumber<uint32_t> n(1, 0); EXPECT_EQ(1u, (n * n).toInt<uint32_t>()); } } // end namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/DataExtractorTest.cpp
//===- llvm/unittest/Support/DataExtractorTest.cpp - DataExtractor tests --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/DataExtractor.h" using namespace llvm; namespace { const char numberData[] = "\x80\x90\xFF\xFF\x80\x00\x00\x00"; const char stringData[] = "hellohello\0hello"; const char leb128data[] = "\xA6\x49"; const char bigleb128data[] = "\xAA\xA9\xFF\xAA\xFF\xAA\xFF\x4A"; TEST(DataExtractorTest, OffsetOverflow) { DataExtractor DE(StringRef(numberData, sizeof(numberData)-1), false, 8); EXPECT_FALSE(DE.isValidOffsetForDataOfSize(-2U, 5)); } TEST(DataExtractorTest, UnsignedNumbers) { DataExtractor DE(StringRef(numberData, sizeof(numberData)-1), false, 8); uint32_t offset = 0; EXPECT_EQ(0x80U, DE.getU8(&offset)); EXPECT_EQ(1U, offset); offset = 0; EXPECT_EQ(0x8090U, DE.getU16(&offset)); EXPECT_EQ(2U, offset); offset = 0; EXPECT_EQ(0x8090FFFFU, DE.getU32(&offset)); EXPECT_EQ(4U, offset); offset = 0; EXPECT_EQ(0x8090FFFF80000000ULL, DE.getU64(&offset)); EXPECT_EQ(8U, offset); offset = 0; EXPECT_EQ(0x8090FFFF80000000ULL, DE.getAddress(&offset)); EXPECT_EQ(8U, offset); offset = 0; uint32_t data[2]; EXPECT_EQ(data, DE.getU32(&offset, data, 2)); EXPECT_EQ(0x8090FFFFU, data[0]); EXPECT_EQ(0x80000000U, data[1]); EXPECT_EQ(8U, offset); offset = 0; // Now for little endian. DE = DataExtractor(StringRef(numberData, sizeof(numberData)-1), true, 4); EXPECT_EQ(0x9080U, DE.getU16(&offset)); EXPECT_EQ(2U, offset); offset = 0; EXPECT_EQ(0xFFFF9080U, DE.getU32(&offset)); EXPECT_EQ(4U, offset); offset = 0; EXPECT_EQ(0x80FFFF9080ULL, DE.getU64(&offset)); EXPECT_EQ(8U, offset); offset = 0; EXPECT_EQ(0xFFFF9080U, DE.getAddress(&offset)); EXPECT_EQ(4U, offset); offset = 0; EXPECT_EQ(data, DE.getU32(&offset, data, 2)); EXPECT_EQ(0xFFFF9080U, data[0]); EXPECT_EQ(0x80U, data[1]); EXPECT_EQ(8U, offset); } TEST(DataExtractorTest, SignedNumbers) { DataExtractor DE(StringRef(numberData, sizeof(numberData)-1), false, 8); uint32_t offset = 0; EXPECT_EQ(-128, DE.getSigned(&offset, 1)); EXPECT_EQ(1U, offset); offset = 0; EXPECT_EQ(-32624, DE.getSigned(&offset, 2)); EXPECT_EQ(2U, offset); offset = 0; EXPECT_EQ(-2137980929, DE.getSigned(&offset, 4)); EXPECT_EQ(4U, offset); offset = 0; EXPECT_EQ(-9182558167379214336LL, DE.getSigned(&offset, 8)); EXPECT_EQ(8U, offset); } TEST(DataExtractorTest, Strings) { DataExtractor DE(StringRef(stringData, sizeof(stringData)-1), false, 8); uint32_t offset = 0; EXPECT_EQ(stringData, DE.getCStr(&offset)); EXPECT_EQ(11U, offset); EXPECT_EQ(nullptr, DE.getCStr(&offset)); EXPECT_EQ(11U, offset); } TEST(DataExtractorTest, LEB128) { DataExtractor DE(StringRef(leb128data, sizeof(leb128data)-1), false, 8); uint32_t offset = 0; EXPECT_EQ(9382ULL, DE.getULEB128(&offset)); EXPECT_EQ(2U, offset); offset = 0; EXPECT_EQ(-7002LL, DE.getSLEB128(&offset)); EXPECT_EQ(2U, offset); DataExtractor BDE(StringRef(bigleb128data, sizeof(bigleb128data)-1), false,8); offset = 0; EXPECT_EQ(42218325750568106ULL, BDE.getULEB128(&offset)); EXPECT_EQ(8U, offset); offset = 0; EXPECT_EQ(-29839268287359830LL, BDE.getSLEB128(&offset)); EXPECT_EQ(8U, offset); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/EndianStreamTest.cpp
//===- unittests/Support/EndianStreamTest.cpp - EndianStream.h tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallString.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/DataTypes.h" #include "gtest/gtest.h" using namespace llvm; using namespace support; namespace { TEST(EndianStream, WriteInt32LE) { SmallString<16> data; { raw_svector_ostream OS(data); endian::Writer<little> LE(OS); LE.write(static_cast<int32_t>(-1362446643)); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0xCD); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0xB6); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0xCA); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0xAE); } TEST(EndianStream, WriteInt32BE) { SmallVector<char, 16> data; { raw_svector_ostream OS(data); endian::Writer<big> BE(OS); BE.write(static_cast<int32_t>(-1362446643)); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0xAE); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0xCA); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0xB6); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0xCD); } TEST(EndianStream, WriteFloatLE) { SmallString<16> data; { raw_svector_ostream OS(data); endian::Writer<little> LE(OS); LE.write(12345.0f); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0x00); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0xE4); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0x40); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0x46); } TEST(EndianStream, WriteFloatBE) { SmallVector<char, 16> data; { raw_svector_ostream OS(data); endian::Writer<big> BE(OS); BE.write(12345.0f); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0x46); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0x40); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0xE4); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0x00); } TEST(EndianStream, WriteInt64LE) { SmallString<16> data; { raw_svector_ostream OS(data); endian::Writer<little> LE(OS); LE.write(static_cast<int64_t>(-136244664332342323)); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0xCD); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0xAB); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0xED); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0x1B); EXPECT_EQ(static_cast<uint8_t>(data[4]), 0x33); EXPECT_EQ(static_cast<uint8_t>(data[5]), 0xF6); EXPECT_EQ(static_cast<uint8_t>(data[6]), 0x1B); EXPECT_EQ(static_cast<uint8_t>(data[7]), 0xFE); } TEST(EndianStream, WriteInt64BE) { SmallVector<char, 16> data; { raw_svector_ostream OS(data); endian::Writer<big> BE(OS); BE.write(static_cast<int64_t>(-136244664332342323)); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0xFE); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0x1B); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0xF6); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0x33); EXPECT_EQ(static_cast<uint8_t>(data[4]), 0x1B); EXPECT_EQ(static_cast<uint8_t>(data[5]), 0xED); EXPECT_EQ(static_cast<uint8_t>(data[6]), 0xAB); EXPECT_EQ(static_cast<uint8_t>(data[7]), 0xCD); } TEST(EndianStream, WriteDoubleLE) { SmallString<16> data; { raw_svector_ostream OS(data); endian::Writer<little> LE(OS); LE.write(-2349214918.58107); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0x20); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0x98); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0xD2); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0x98); EXPECT_EQ(static_cast<uint8_t>(data[4]), 0xC5); EXPECT_EQ(static_cast<uint8_t>(data[5]), 0x80); EXPECT_EQ(static_cast<uint8_t>(data[6]), 0xE1); EXPECT_EQ(static_cast<uint8_t>(data[7]), 0xC1); } TEST(EndianStream, WriteDoubleBE) { SmallVector<char, 16> data; { raw_svector_ostream OS(data); endian::Writer<big> BE(OS); BE.write(-2349214918.58107); } EXPECT_EQ(static_cast<uint8_t>(data[0]), 0xC1); EXPECT_EQ(static_cast<uint8_t>(data[1]), 0xE1); EXPECT_EQ(static_cast<uint8_t>(data[2]), 0x80); EXPECT_EQ(static_cast<uint8_t>(data[3]), 0xC5); EXPECT_EQ(static_cast<uint8_t>(data[4]), 0x98); EXPECT_EQ(static_cast<uint8_t>(data[5]), 0xD2); EXPECT_EQ(static_cast<uint8_t>(data[6]), 0x98); EXPECT_EQ(static_cast<uint8_t>(data[7]), 0x20); } } // end anon namespace
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/SpecialCaseListTest.cpp
//===- SpecialCaseListTest.cpp - Unit tests for SpecialCaseList -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SpecialCaseList.h" #include "gtest/gtest.h" using namespace llvm; namespace { class SpecialCaseListTest : public ::testing::Test { protected: std::unique_ptr<SpecialCaseList> makeSpecialCaseList(StringRef List, std::string &Error) { std::unique_ptr<MemoryBuffer> MB = MemoryBuffer::getMemBuffer(List); return SpecialCaseList::create(MB.get(), Error); } std::unique_ptr<SpecialCaseList> makeSpecialCaseList(StringRef List) { std::string Error; auto SCL = makeSpecialCaseList(List, Error); assert(SCL); assert(Error == ""); return SCL; } std::string makeSpecialCaseListFile(StringRef Contents) { int FD; SmallString<64> Path; sys::fs::createTemporaryFile("SpecialCaseListTest", "temp", FD, Path); raw_fd_ostream OF(FD, true, true); OF << Contents; OF.close(); return Path.str(); } }; TEST_F(SpecialCaseListTest, Basic) { std::unique_ptr<SpecialCaseList> SCL = makeSpecialCaseList("# This is a comment.\n" "\n" "src:hello\n" "src:bye\n" "src:hi=category\n" "src:z*=category\n"); EXPECT_TRUE(SCL->inSection("src", "hello")); EXPECT_TRUE(SCL->inSection("src", "bye")); EXPECT_TRUE(SCL->inSection("src", "hi", "category")); EXPECT_TRUE(SCL->inSection("src", "zzzz", "category")); EXPECT_FALSE(SCL->inSection("src", "hi")); EXPECT_FALSE(SCL->inSection("fun", "hello")); EXPECT_FALSE(SCL->inSection("src", "hello", "category")); } TEST_F(SpecialCaseListTest, GlobalInit) { std::unique_ptr<SpecialCaseList> SCL = makeSpecialCaseList("global:foo=init\n"); EXPECT_FALSE(SCL->inSection("global", "foo")); EXPECT_FALSE(SCL->inSection("global", "bar")); EXPECT_TRUE(SCL->inSection("global", "foo", "init")); EXPECT_FALSE(SCL->inSection("global", "bar", "init")); SCL = makeSpecialCaseList("type:t2=init\n"); EXPECT_FALSE(SCL->inSection("type", "t1")); EXPECT_FALSE(SCL->inSection("type", "t2")); EXPECT_FALSE(SCL->inSection("type", "t1", "init")); EXPECT_TRUE(SCL->inSection("type", "t2", "init")); SCL = makeSpecialCaseList("src:hello=init\n"); EXPECT_FALSE(SCL->inSection("src", "hello")); EXPECT_FALSE(SCL->inSection("src", "bye")); EXPECT_TRUE(SCL->inSection("src", "hello", "init")); EXPECT_FALSE(SCL->inSection("src", "bye", "init")); } TEST_F(SpecialCaseListTest, Substring) { std::unique_ptr<SpecialCaseList> SCL = makeSpecialCaseList("src:hello\n" "fun:foo\n" "global:bar\n"); EXPECT_FALSE(SCL->inSection("src", "othello")); EXPECT_FALSE(SCL->inSection("fun", "tomfoolery")); EXPECT_FALSE(SCL->inSection("global", "bartender")); SCL = makeSpecialCaseList("fun:*foo*\n"); EXPECT_TRUE(SCL->inSection("fun", "tomfoolery")); EXPECT_TRUE(SCL->inSection("fun", "foobar")); } TEST_F(SpecialCaseListTest, InvalidSpecialCaseList) { std::string Error; EXPECT_EQ(nullptr, makeSpecialCaseList("badline", Error)); EXPECT_EQ("malformed line 1: 'badline'", Error); EXPECT_EQ(nullptr, makeSpecialCaseList("src:bad[a-", Error)); EXPECT_EQ("malformed regex in line 1: 'bad[a-': invalid character range", Error); EXPECT_EQ(nullptr, makeSpecialCaseList("src:a.c\n" "fun:fun(a\n", Error)); EXPECT_EQ("malformed regex in line 2: 'fun(a': parentheses not balanced", Error); std::vector<std::string> Files(1, "unexisting"); EXPECT_EQ(nullptr, SpecialCaseList::create(Files, Error)); EXPECT_EQ(0U, Error.find("can't open file 'unexisting':")); } TEST_F(SpecialCaseListTest, EmptySpecialCaseList) { std::unique_ptr<SpecialCaseList> SCL = makeSpecialCaseList(""); EXPECT_FALSE(SCL->inSection("foo", "bar")); } TEST_F(SpecialCaseListTest, MultipleBlacklists) { std::vector<std::string> Files; Files.push_back(makeSpecialCaseListFile("src:bar\n" "src:*foo*\n" "src:ban=init\n")); Files.push_back(makeSpecialCaseListFile("src:baz\n" "src:*fog*\n")); auto SCL = SpecialCaseList::createOrDie(Files); EXPECT_TRUE(SCL->inSection("src", "bar")); EXPECT_TRUE(SCL->inSection("src", "baz")); EXPECT_FALSE(SCL->inSection("src", "ban")); EXPECT_TRUE(SCL->inSection("src", "ban", "init")); EXPECT_TRUE(SCL->inSection("src", "tomfoolery")); EXPECT_TRUE(SCL->inSection("src", "tomfoglery")); } }
0
repos/DirectXShaderCompiler/unittests
repos/DirectXShaderCompiler/unittests/Support/TargetRegistry.cpp
//===- unittests/Support/TargetRegistry.cpp - -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "gtest/gtest.h" using namespace llvm; namespace { TEST(TargetRegistry, TargetHasArchType) { // Presence of at least one target will be asserted when done with the loop, // else this would pass by accident if InitializeAllTargetInfos were omitted. int Count = 0; llvm::InitializeAllTargetInfos(); for (const Target &T : TargetRegistry::targets()) { StringRef Name = T.getName(); // There is really no way (at present) to ask a Target whether it targets // a specific architecture, because the logic for that is buried in a // predicate. // We can't ask the predicate "Are you a function that always returns // false?" // So given that the cpp backend truly has no target arch, it is skipped. if (Name != "cpp") { Triple::ArchType Arch = Triple::getArchTypeForLLVMName(Name); EXPECT_NE(Arch, Triple::UnknownArch); ++Count; } } ASSERT_NE(Count, 0); } } // end namespace