Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/StaticAnalyzer/AnalyzerOptionsTest.cpp
|
//===- unittest/Analysis/AnalyzerOptionsTest.cpp - SA Options test --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "gtest/gtest.h"
namespace clang {
namespace ento {
TEST(StaticAnalyzerOptions, SearchInParentPackageTests) {
AnalyzerOptions Opts;
Opts.Config["Outer.Inner.CheckerOne:Option"] = "true";
Opts.Config["Outer.Inner:Option"] = "false";
Opts.Config["Outer.Inner:Option2"] = "true";
Opts.Config["Outer:Option2"] = "false";
struct CheckerOneMock : CheckerBase {
StringRef getTagDescription() const override {
return "Outer.Inner.CheckerOne";
}
};
struct CheckerTwoMock : CheckerBase {
StringRef getTagDescription() const override {
return "Outer.Inner.CheckerTwo";
}
};
// Checker one has Option specified as true. It should read true regardless of
// search mode.
CheckerOneMock CheckerOne;
EXPECT_TRUE(Opts.getBooleanOption("Option", false, &CheckerOne));
// The package option is overriden with a checker option.
EXPECT_TRUE(Opts.getBooleanOption("Option", false, &CheckerOne, true));
// The Outer package option is overriden by the Inner package option. No
// package option is specified.
EXPECT_TRUE(Opts.getBooleanOption("Option2", false, &CheckerOne, true));
// No package option is specified and search in packages is turned off. The
// default value should be returned.
EXPECT_FALSE(Opts.getBooleanOption("Option2", false, &CheckerOne));
EXPECT_TRUE(Opts.getBooleanOption("Option2", true, &CheckerOne));
// Checker true has no option specified. It should get the default value when
// search in parents turned off and false when search in parents turned on.
CheckerTwoMock CheckerTwo;
EXPECT_FALSE(Opts.getBooleanOption("Option", false, &CheckerTwo));
EXPECT_TRUE(Opts.getBooleanOption("Option", true, &CheckerTwo));
EXPECT_FALSE(Opts.getBooleanOption("Option", true, &CheckerTwo, true));
}
TEST(StaticAnalyzerOptions, StringOptions) {
AnalyzerOptions Opts;
Opts.Config["Outer.Inner.CheckerOne:Option"] = "StringValue";
struct CheckerOneMock : CheckerBase {
StringRef getTagDescription() const override {
return "Outer.Inner.CheckerOne";
}
};
CheckerOneMock CheckerOne;
EXPECT_TRUE("StringValue" ==
Opts.getOptionAsString("Option", "DefaultValue", &CheckerOne));
EXPECT_TRUE("DefaultValue" ==
Opts.getOptionAsString("Option2", "DefaultValue", &CheckerOne));
}
} // end namespace ento
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers/ASTMatchersTest.cpp
|
//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher unit tests ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ASTMatchersTest.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Host.h"
#include "gtest/gtest.h"
namespace clang {
namespace ast_matchers {
#if GTEST_HAS_DEATH_TEST
TEST(HasNameDeathTest, DiesOnEmptyName) {
ASSERT_DEBUG_DEATH({
DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
}, "");
}
TEST(HasNameDeathTest, DiesOnEmptyPattern) {
ASSERT_DEBUG_DEATH({
DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
}, "");
}
TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
ASSERT_DEBUG_DEATH({
DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
}, "");
}
#endif
TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
MatchFinder Finder;
EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
nullptr));
// Do not accept non-toplevel matchers.
EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
}
TEST(Decl, MatchesDeclarations) {
EXPECT_TRUE(notMatches("", decl(usingDecl())));
EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
decl(usingDecl())));
}
TEST(NameableDeclaration, MatchesVariousDecls) {
DeclarationMatcher NamedX = namedDecl(hasName("X"));
EXPECT_TRUE(matches("typedef int X;", NamedX));
EXPECT_TRUE(matches("int X;", NamedX));
EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
EXPECT_TRUE(matches("namespace X { }", NamedX));
EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
EXPECT_TRUE(notMatches("#define X 1", NamedX));
}
TEST(NameableDeclaration, REMatchesVariousDecls) {
DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
EXPECT_TRUE(matches("typedef int Xa;", NamedX));
EXPECT_TRUE(matches("int Xb;", NamedX));
EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
EXPECT_TRUE(matches("namespace Xij { }", NamedX));
EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
EXPECT_TRUE(matches("int abc;", Abc));
EXPECT_TRUE(matches("int aFOObBARc;", Abc));
EXPECT_TRUE(notMatches("int cab;", Abc));
EXPECT_TRUE(matches("int cabc;", Abc));
DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
EXPECT_TRUE(matches("int k;", StartsWithK));
EXPECT_TRUE(matches("int kAbc;", StartsWithK));
EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
}
TEST(DeclarationMatcher, MatchClass) {
DeclarationMatcher ClassMatcher(recordDecl());
llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
if (Triple.getOS() != llvm::Triple::Win32 ||
Triple.getEnvironment() != llvm::Triple::MSVC)
EXPECT_FALSE(matches("", ClassMatcher));
else
// Matches class type_info.
EXPECT_TRUE(matches("", ClassMatcher));
DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
EXPECT_TRUE(matches("class X;", ClassX));
EXPECT_TRUE(matches("class X {};", ClassX));
EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
EXPECT_TRUE(notMatches("", ClassX));
}
TEST(DeclarationMatcher, ClassIsDerived) {
DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
EXPECT_TRUE(notMatches("", IsDerivedFromX));
DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
EXPECT_TRUE(matches("class X {};", IsAX));
EXPECT_TRUE(matches("class X;", IsAX));
EXPECT_TRUE(notMatches("class Y;", IsAX));
EXPECT_TRUE(notMatches("", IsAX));
DeclarationMatcher ZIsDerivedFromX =
recordDecl(hasName("Z"), isDerivedFrom("X"));
EXPECT_TRUE(
matches("class X {}; class Y : public X {}; class Z : public Y {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {};"
"template<class T> class Y : public X {};"
"class Z : public Y<int> {};", ZIsDerivedFromX));
EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T> class X {}; "
"template<class T> class Z : public X<T> {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T, class U=T> class X {}; "
"template<class T> class Z : public X<T> {};",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class A { class Z : public X {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class X> class A { public: class Z : public X {}; }; "
"class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
EXPECT_TRUE(
matches("template <class T> class X {}; "
"template<class Y> class A { class Z : public X<Y> {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<template<class T> class X> class A { "
" class Z : public X<int> {}; };", ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<template<class T> class X> class A { "
" public: class Z : public X<int> {}; }; "
"template<class T> class X {}; void y() { A<X>::Z z; }",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class A { class Z : public X::D {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class X> class A { public: "
" class Z : public X::D {}; }; "
"class Y { public: class X {}; typedef X D; }; "
"void y() { A<Y>::Z z; }", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X Y; class Z : public Y {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T> class Y { typedef typename T::U X; "
" class Z : public X {}; };", ZIsDerivedFromX));
EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class T> class X {}; "
"template<class T> class A { class Z : public X<T>::D {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T> class X { public: typedef X<T> D; }; "
"template<class T> class A { public: "
" class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class A { class Z : public X::D::E {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; class Y : public X {}; "
"typedef Y V; typedef V W; class Z : public W {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T, class U> class X {}; "
"template<class T> class A { class Z : public X<T, int> {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class D { typedef X A; typedef A B; "
" typedef B C; class Z : public C {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X A; typedef A B; "
"class Z : public B {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X A; typedef A B; typedef B C; "
"class Z : public C {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class U {}; typedef U X; typedef X V; "
"class Z : public V {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class Base {}; typedef Base X; "
"class Z : public Base {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class Base {}; typedef Base Base2; typedef Base2 X; "
"class Z : public Base {};", ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
"class Z : public Base {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class A {}; typedef A X; typedef A Y; "
"class Z : public Y {};", ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template <typename T> class Z;"
"template <> class Z<void> {};"
"template <typename T> class Z : public Z<void> {};",
IsDerivedFromX));
EXPECT_TRUE(
matches("template <typename T> class X;"
"template <> class X<void> {};"
"template <typename T> class X : public X<void> {};",
IsDerivedFromX));
EXPECT_TRUE(matches(
"class X {};"
"template <typename T> class Z;"
"template <> class Z<void> {};"
"template <typename T> class Z : public Z<void>, public X {};",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<int> struct X;"
"template<int i> struct X : public X<i-1> {};",
recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
EXPECT_TRUE(matches(
"struct A {};"
"template<int> struct X;"
"template<int i> struct X : public X<i-1> {};"
"template<> struct X<0> : public A {};"
"struct B : public X<42> {};",
recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
// FIXME: Once we have better matchers for template type matching,
// get rid of the Variable(...) matching and match the right template
// declarations directly.
const char *RecursiveTemplateOneParameter =
"class Base1 {}; class Base2 {};"
"template <typename T> class Z;"
"template <> class Z<void> : public Base1 {};"
"template <> class Z<int> : public Base2 {};"
"template <> class Z<float> : public Z<void> {};"
"template <> class Z<double> : public Z<int> {};"
"template <typename T> class Z : public Z<float>, public Z<double> {};"
"void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
EXPECT_TRUE(matches(
RecursiveTemplateOneParameter,
varDecl(hasName("z_float"),
hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
EXPECT_TRUE(notMatches(
RecursiveTemplateOneParameter,
varDecl(hasName("z_float"),
hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
EXPECT_TRUE(matches(
RecursiveTemplateOneParameter,
varDecl(hasName("z_char"),
hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
isDerivedFrom("Base2")))))));
const char *RecursiveTemplateTwoParameters =
"class Base1 {}; class Base2 {};"
"template <typename T1, typename T2> class Z;"
"template <typename T> class Z<void, T> : public Base1 {};"
"template <typename T> class Z<int, T> : public Base2 {};"
"template <typename T> class Z<float, T> : public Z<void, T> {};"
"template <typename T> class Z<double, T> : public Z<int, T> {};"
"template <typename T1, typename T2> class Z : "
" public Z<float, T2>, public Z<double, T2> {};"
"void f() { Z<float, void> z_float; Z<double, void> z_double; "
" Z<char, void> z_char; }";
EXPECT_TRUE(matches(
RecursiveTemplateTwoParameters,
varDecl(hasName("z_float"),
hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
EXPECT_TRUE(notMatches(
RecursiveTemplateTwoParameters,
varDecl(hasName("z_float"),
hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
EXPECT_TRUE(matches(
RecursiveTemplateTwoParameters,
varDecl(hasName("z_char"),
hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
isDerivedFrom("Base2")))))));
EXPECT_TRUE(matches(
"namespace ns { class X {}; class Y : public X {}; }",
recordDecl(isDerivedFrom("::ns::X"))));
EXPECT_TRUE(notMatches(
"class X {}; class Y : public X {};",
recordDecl(isDerivedFrom("::ns::X"))));
EXPECT_TRUE(matches(
"class X {}; class Y : public X {};",
recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
EXPECT_TRUE(matches(
"template<typename T> class X {};"
"template<typename T> using Z = X<T>;"
"template <typename T> class Y : Z<T> {};",
recordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
}
TEST(DeclarationMatcher, hasMethod) {
EXPECT_TRUE(matches("class A { void func(); };",
recordDecl(hasMethod(hasName("func")))));
EXPECT_TRUE(notMatches("class A { void func(); };",
recordDecl(hasMethod(isPublic()))));
}
TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
EXPECT_TRUE(matches(
"template <typename T> struct A {"
" template <typename T2> struct F {};"
"};"
"template <typename T> struct B : A<T>::template F<T> {};"
"B<int> b;",
recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
}
TEST(DeclarationMatcher, hasDeclContext) {
EXPECT_TRUE(matches(
"namespace N {"
" namespace M {"
" class D {};"
" }"
"}",
recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
EXPECT_TRUE(notMatches(
"namespace N {"
" namespace M {"
" class D {};"
" }"
"}",
recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
EXPECT_TRUE(matches("namespace {"
" namespace M {"
" class D {};"
" }"
"}",
recordDecl(hasDeclContext(namespaceDecl(
hasName("M"), hasDeclContext(namespaceDecl()))))));
EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
}
TEST(DeclarationMatcher, translationUnitDecl) {
const std::string Code = "int MyVar1;\n"
"namespace NameSpace {\n"
"int MyVar2;\n"
"} // namespace NameSpace\n";
EXPECT_TRUE(matches(
Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
EXPECT_FALSE(matches(
Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
EXPECT_TRUE(matches(
Code,
varDecl(hasName("MyVar2"),
hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
}
TEST(DeclarationMatcher, LinkageSpecification) {
EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
}
TEST(ClassTemplate, DoesNotMatchClass) {
DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
EXPECT_TRUE(notMatches("class X;", ClassX));
EXPECT_TRUE(notMatches("class X {};", ClassX));
}
TEST(ClassTemplate, MatchesClassTemplate) {
DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
}
TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
EXPECT_TRUE(notMatches("template<typename T> class X { };"
"template<> class X<int> { int a; };",
classTemplateDecl(hasName("X"),
hasDescendant(fieldDecl(hasName("a"))))));
}
TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
"template<typename T> class X<T, int> { int a; };",
classTemplateDecl(hasName("X"),
hasDescendant(fieldDecl(hasName("a"))))));
}
TEST(AllOf, AllOverloadsWork) {
const char Program[] =
"struct T { };"
"int f(int, T*, int, int);"
"void g(int x) { T t; f(x, &t, 3, 4); }";
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl())))))));
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl()))),
hasArgument(1, hasType(pointsTo(
recordDecl(hasName("T")))))))));
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl()))),
hasArgument(1, hasType(pointsTo(
recordDecl(hasName("T"))))),
hasArgument(2, integerLiteral(equals(3)))))));
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl()))),
hasArgument(1, hasType(pointsTo(
recordDecl(hasName("T"))))),
hasArgument(2, integerLiteral(equals(3))),
hasArgument(3, integerLiteral(equals(4)))))));
}
TEST(DeclarationMatcher, MatchAnyOf) {
DeclarationMatcher YOrZDerivedFromX =
recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
EXPECT_TRUE(
matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
EXPECT_TRUE(
notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
DeclarationMatcher XOrYOrZOrU =
recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
DeclarationMatcher XOrYOrZOrUOrV =
recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
hasName("V")));
EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
EXPECT_TRUE(
matches("void f() try { } catch (int) { } catch (...) { }",
catchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
}
TEST(DeclarationMatcher, MatchHas) {
DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
EXPECT_TRUE(matches("class X {};", HasClassX));
DeclarationMatcher YHasClassX =
recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
EXPECT_TRUE(notMatches("class X {};", YHasClassX));
EXPECT_TRUE(
notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
}
TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
DeclarationMatcher Recursive =
recordDecl(
has(recordDecl(
has(recordDecl(hasName("X"))),
has(recordDecl(hasName("Y"))),
hasName("Z"))),
has(recordDecl(
has(recordDecl(hasName("A"))),
has(recordDecl(hasName("B"))),
hasName("C"))),
hasName("F"));
EXPECT_TRUE(matches(
"class F {"
" class Z {"
" class X {};"
" class Y {};"
" };"
" class C {"
" class A {};"
" class B {};"
" };"
"};", Recursive));
EXPECT_TRUE(matches(
"class F {"
" class Z {"
" class A {};"
" class X {};"
" class Y {};"
" };"
" class C {"
" class X {};"
" class A {};"
" class B {};"
" };"
"};", Recursive));
EXPECT_TRUE(matches(
"class O1 {"
" class O2 {"
" class F {"
" class Z {"
" class A {};"
" class X {};"
" class Y {};"
" };"
" class C {"
" class X {};"
" class A {};"
" class B {};"
" };"
" };"
" };"
"};", Recursive));
}
TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
DeclarationMatcher Recursive =
recordDecl(
anyOf(
has(recordDecl(
anyOf(
has(recordDecl(
hasName("X"))),
has(recordDecl(
hasName("Y"))),
hasName("Z")))),
has(recordDecl(
anyOf(
hasName("C"),
has(recordDecl(
hasName("A"))),
has(recordDecl(
hasName("B")))))),
hasName("F")));
EXPECT_TRUE(matches("class F {};", Recursive));
EXPECT_TRUE(matches("class Z {};", Recursive));
EXPECT_TRUE(matches("class C {};", Recursive));
EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
EXPECT_TRUE(
matches("class O1 { class O2 {"
" class M { class N { class B {}; }; }; "
"}; };", Recursive));
}
TEST(DeclarationMatcher, MatchNot) {
DeclarationMatcher NotClassX =
recordDecl(
isDerivedFrom("Y"),
unless(hasName("X")));
EXPECT_TRUE(notMatches("", NotClassX));
EXPECT_TRUE(notMatches("class Y {};", NotClassX));
EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
EXPECT_TRUE(
notMatches("class Y {}; class Z {}; class X : public Y {};",
NotClassX));
DeclarationMatcher ClassXHasNotClassY =
recordDecl(
hasName("X"),
has(recordDecl(hasName("Z"))),
unless(
has(recordDecl(hasName("Y")))));
EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
ClassXHasNotClassY));
DeclarationMatcher NamedNotRecord =
namedDecl(hasName("Foo"), unless(recordDecl()));
EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
}
TEST(DeclarationMatcher, HasDescendant) {
DeclarationMatcher ZDescendantClassX =
recordDecl(
hasDescendant(recordDecl(hasName("X"))),
hasName("Z"));
EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
EXPECT_TRUE(
matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
EXPECT_TRUE(
matches("class Z { class A { class Y { class X {}; }; }; };",
ZDescendantClassX));
EXPECT_TRUE(
matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
ZDescendantClassX));
EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
DeclarationMatcher ZDescendantClassXHasClassY =
recordDecl(
hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
hasName("X"))),
hasName("Z"));
EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
ZDescendantClassXHasClassY));
EXPECT_TRUE(
matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
ZDescendantClassXHasClassY));
EXPECT_TRUE(notMatches(
"class Z {"
" class A {"
" class B {"
" class X {"
" class C {"
" class Y {};"
" };"
" };"
" }; "
" };"
"};", ZDescendantClassXHasClassY));
DeclarationMatcher ZDescendantClassXDescendantClassY =
recordDecl(
hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
hasName("X"))),
hasName("Z"));
EXPECT_TRUE(
matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
ZDescendantClassXDescendantClassY));
EXPECT_TRUE(matches(
"class Z {"
" class A {"
" class X {"
" class B {"
" class Y {};"
" };"
" class Y {};"
" };"
" };"
"};", ZDescendantClassXDescendantClassY));
}
TEST(DeclarationMatcher, HasDescendantMemoization) {
DeclarationMatcher CannotMemoize =
decl(hasDescendant(typeLoc().bind("x")), has(decl()));
EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
}
TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
auto Name = hasName("i");
auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
// Matching VD first should not make a cache hit for RD.
EXPECT_TRUE(notMatches("void f() { int i; }",
decl(hasDescendant(VD), hasDescendant(RD))));
EXPECT_TRUE(notMatches("void f() { int i; }",
decl(hasDescendant(RD), hasDescendant(VD))));
// Not matching RD first should not make a cache hit for VD either.
EXPECT_TRUE(matches("void f() { int i; }",
decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
}
TEST(DeclarationMatcher, HasAttr) {
EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
decl(hasAttr(clang::attr::WarnUnused))));
EXPECT_FALSE(matches("struct X {};",
decl(hasAttr(clang::attr::WarnUnused))));
}
TEST(DeclarationMatcher, MatchCudaDecl) {
EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
"void g() { f<<<1, 2>>>(); }",
CUDAKernelCallExpr()));
EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
hasAttr(clang::attr::CUDADevice)));
EXPECT_TRUE(notMatchesWithCuda("void f() {}",
CUDAKernelCallExpr()));
EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
hasAttr(clang::attr::CUDAGlobal)));
}
// Implements a run method that returns whether BoundNodes contains a
// Decl bound to Id that can be dynamically cast to T.
// Optionally checks that the check succeeded a specific number of times.
template <typename T>
class VerifyIdIsBoundTo : public BoundNodesCallback {
public:
// Create an object that checks that a node of type \c T was bound to \c Id.
// Does not check for a certain number of matches.
explicit VerifyIdIsBoundTo(llvm::StringRef Id)
: Id(Id), ExpectedCount(-1), Count(0) {}
// Create an object that checks that a node of type \c T was bound to \c Id.
// Checks that there were exactly \c ExpectedCount matches.
VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
: Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
// Create an object that checks that a node of type \c T was bound to \c Id.
// Checks that there was exactly one match with the name \c ExpectedName.
// Note that \c T must be a NamedDecl for this to work.
VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
int ExpectedCount = 1)
: Id(Id), ExpectedCount(ExpectedCount), Count(0),
ExpectedName(ExpectedName) {}
void onEndOfTranslationUnit() override {
if (ExpectedCount != -1)
EXPECT_EQ(ExpectedCount, Count);
if (!ExpectedName.empty())
EXPECT_EQ(ExpectedName, Name);
Count = 0;
Name.clear();
}
~VerifyIdIsBoundTo() override {
EXPECT_EQ(0, Count);
EXPECT_EQ("", Name);
}
bool run(const BoundNodes *Nodes) override {
const BoundNodes::IDToNodeMap &M = Nodes->getMap();
if (Nodes->getNodeAs<T>(Id)) {
++Count;
if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
Name = Named->getNameAsString();
} else if (const NestedNameSpecifier *NNS =
Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
llvm::raw_string_ostream OS(Name);
NNS->print(OS, PrintingPolicy(LangOptions()));
}
BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
EXPECT_NE(M.end(), I);
if (I != M.end())
EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
return true;
}
EXPECT_TRUE(M.count(Id) == 0 ||
M.find(Id)->second.template get<T>() == nullptr);
return false;
}
bool run(const BoundNodes *Nodes, ASTContext *Context) override {
return run(Nodes);
}
private:
const std::string Id;
const int ExpectedCount;
int Count;
const std::string ExpectedName;
std::string Name;
};
TEST(HasDescendant, MatchesDescendantTypes) {
EXPECT_TRUE(matches("void f() { int i = 3; }",
decl(hasDescendant(loc(builtinType())))));
EXPECT_TRUE(matches("void f() { int i = 3; }",
stmt(hasDescendant(builtinType()))));
EXPECT_TRUE(matches("void f() { int i = 3; }",
stmt(hasDescendant(loc(builtinType())))));
EXPECT_TRUE(matches("void f() { int i = 3; }",
stmt(hasDescendant(qualType(builtinType())))));
EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
stmt(hasDescendant(isInteger()))));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() { int a; float c; int d; int e; }",
functionDecl(forEachDescendant(
varDecl(hasDescendant(isInteger())).bind("x"))),
new VerifyIdIsBoundTo<Decl>("x", 3)));
}
TEST(HasDescendant, MatchesDescendantsOfTypes) {
EXPECT_TRUE(matches("void f() { int*** i; }",
qualType(hasDescendant(builtinType()))));
EXPECT_TRUE(matches("void f() { int*** i; }",
qualType(hasDescendant(
pointerType(pointee(builtinType()))))));
EXPECT_TRUE(matches("void f() { int*** i; }",
typeLoc(hasDescendant(loc(builtinType())))));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() { int*** i; }",
qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
new VerifyIdIsBoundTo<Type>("x", 2)));
}
TEST(Has, MatchesChildrenOfTypes) {
EXPECT_TRUE(matches("int i;",
varDecl(hasName("i"), has(isInteger()))));
EXPECT_TRUE(notMatches("int** i;",
varDecl(hasName("i"), has(isInteger()))));
EXPECT_TRUE(matchAndVerifyResultTrue(
"int (*f)(float, int);",
qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
new VerifyIdIsBoundTo<QualType>("x", 2)));
}
TEST(Has, MatchesChildTypes) {
EXPECT_TRUE(matches(
"int* i;",
varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
EXPECT_TRUE(notMatches(
"int* i;",
varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
}
TEST(ValueDecl, Matches) {
EXPECT_TRUE(matches("enum EnumType { EnumValue };",
valueDecl(hasType(asString("enum EnumType")))));
EXPECT_TRUE(matches("void FunctionDecl();",
valueDecl(hasType(asString("void (void)")))));
}
TEST(Enum, DoesNotMatchClasses) {
EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
}
TEST(Enum, MatchesEnums) {
EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
}
TEST(EnumConstant, Matches) {
DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
EXPECT_TRUE(matches("enum X{ A };", Matcher));
EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
EXPECT_TRUE(notMatches("enum X {};", Matcher));
}
TEST(StatementMatcher, Has) {
StatementMatcher HasVariableI =
expr(hasType(pointsTo(recordDecl(hasName("X")))),
has(declRefExpr(to(varDecl(hasName("i"))))));
EXPECT_TRUE(matches(
"class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
EXPECT_TRUE(notMatches(
"class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
}
TEST(StatementMatcher, HasDescendant) {
StatementMatcher HasDescendantVariableI =
expr(hasType(pointsTo(recordDecl(hasName("X")))),
hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
EXPECT_TRUE(matches(
"class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
HasDescendantVariableI));
EXPECT_TRUE(notMatches(
"class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
HasDescendantVariableI));
}
TEST(TypeMatcher, MatchesClassType) {
TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
EXPECT_TRUE(notMatches("class A {};", TypeA));
TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
TypeDerivedFromA));
EXPECT_TRUE(notMatches("class A {};", TypeA));
TypeMatcher TypeAHasClassB = hasDeclaration(
recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
EXPECT_TRUE(
matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
}
TEST(Matcher, BindMatchedNodes) {
DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
TypeMatcher TypeAHasClassB = hasDeclaration(
recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
TypeAHasClassB,
new VerifyIdIsBoundTo<Decl>("b")));
StatementMatcher MethodX =
callExpr(callee(methodDecl(hasName("x")))).bind("x");
EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
MethodX,
new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
}
TEST(Matcher, BindTheSameNameInAlternatives) {
StatementMatcher matcher = anyOf(
binaryOperator(hasOperatorName("+"),
hasLHS(expr().bind("x")),
hasRHS(integerLiteral(equals(0)))),
binaryOperator(hasOperatorName("+"),
hasLHS(integerLiteral(equals(0))),
hasRHS(expr().bind("x"))));
EXPECT_TRUE(matchAndVerifyResultTrue(
// The first branch of the matcher binds x to 0 but then fails.
// The second branch binds x to f() and succeeds.
"int f() { return 0 + f(); }",
matcher,
new VerifyIdIsBoundTo<CallExpr>("x")));
}
TEST(Matcher, BindsIDForMemoizedResults) {
// Using the same matcher in two match expressions will make memoization
// kick in.
DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { class B { class X {}; }; };",
DeclarationMatcher(anyOf(
recordDecl(hasName("A"), hasDescendant(ClassX)),
recordDecl(hasName("B"), hasDescendant(ClassX)))),
new VerifyIdIsBoundTo<Decl>("x", 2)));
}
TEST(HasDeclaration, HasDeclarationOfEnumType) {
EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
expr(hasType(pointsTo(
qualType(hasDeclaration(enumDecl(hasName("X")))))))));
}
TEST(HasDeclaration, HasGetDeclTraitTest) {
EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
}
TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
EXPECT_TRUE(matches("typedef int X; X a;",
varDecl(hasName("a"),
hasType(typedefType(hasDeclaration(decl()))))));
// FIXME: Add tests for other types with getDecl() (e.g. RecordType)
}
TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
varDecl(hasType(templateSpecializationType(
hasDeclaration(namedDecl(hasName("A"))))))));
}
TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
EXPECT_TRUE(
matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y(X *x) { x; }",
expr(hasType(ClassX))));
EXPECT_TRUE(
matches("class X {}; void y(X *x) { x; }",
expr(hasType(pointsTo(ClassX)))));
}
TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
EXPECT_TRUE(
matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
EXPECT_TRUE(
matches("class X {}; void y() { X *x; }",
varDecl(hasType(pointsTo(ClassX)))));
}
TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
DeclarationMatcher ClassX = recordDecl(hasName("X"));
EXPECT_TRUE(
matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y(X *x) { x; }",
expr(hasType(ClassX))));
}
TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
DeclarationMatcher ClassX = recordDecl(hasName("X"));
EXPECT_TRUE(
matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
}
TEST(HasTypeLoc, MatchesDeclaratorDecls) {
EXPECT_TRUE(matches("int x;",
varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
// Make sure we don't crash on implicit constructors.
EXPECT_TRUE(notMatches("class X {}; X x;",
declaratorDecl(hasTypeLoc(loc(asString("int"))))));
}
TEST(Matcher, Call) {
// FIXME: Do we want to overload Call() to directly take
// Matcher<Decl>, too?
StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
StatementMatcher MethodOnY =
memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
MethodOnY));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
MethodOnY));
StatementMatcher MethodOnYPointer =
memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
MethodOnYPointer));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
MethodOnYPointer));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
MethodOnYPointer));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
MethodOnYPointer));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
MethodOnYPointer));
}
TEST(Matcher, Lambda) {
EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
lambdaExpr()));
}
TEST(Matcher, ForRange) {
EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
"void f() { for (auto &a : as); }",
forRangeStmt()));
EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
forRangeStmt()));
}
TEST(Matcher, SubstNonTypeTemplateParm) {
EXPECT_FALSE(matches("template<int N>\n"
"struct A { static const int n = 0; };\n"
"struct B : public A<42> {};",
substNonTypeTemplateParmExpr()));
EXPECT_TRUE(matches("template<int N>\n"
"struct A { static const int n = N; };\n"
"struct B : public A<42> {};",
substNonTypeTemplateParmExpr()));
}
TEST(Matcher, UserDefinedLiteral) {
EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
" return i + 1;"
"}"
"char c = 'a'_inc;",
userDefinedLiteral()));
}
TEST(Matcher, FlowControl) {
EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
continueStmt()));
EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
}
TEST(HasType, MatchesAsString) {
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
memberCallExpr(on(hasType(asString("class Y *"))))));
EXPECT_TRUE(matches("class X { void x(int x) {} };",
methodDecl(hasParameter(0, hasType(asString("int"))))));
EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
fieldDecl(hasType(asString("ns::A")))));
EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
}
TEST(Matcher, OverloadedOperatorCall) {
StatementMatcher OpCall = operatorCallExpr();
// Unary operator
EXPECT_TRUE(matches("class Y { }; "
"bool operator!(Y x) { return false; }; "
"Y y; bool c = !y;", OpCall));
// No match -- special operators like "new", "delete"
// FIXME: operator new takes size_t, for which we need stddef.h, for which
// we need to figure out include paths in the test.
// EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
// "class Y { }; "
// "void *operator new(size_t size) { return 0; } "
// "Y *y = new Y;", OpCall));
EXPECT_TRUE(notMatches("class Y { }; "
"void operator delete(void *p) { } "
"void a() {Y *y = new Y; delete y;}", OpCall));
// Binary operator
EXPECT_TRUE(matches("class Y { }; "
"bool operator&&(Y x, Y y) { return true; }; "
"Y a; Y b; bool c = a && b;",
OpCall));
// No match -- normal operator, not an overloaded one.
EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
}
TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
StatementMatcher OpCallAndAnd =
operatorCallExpr(hasOverloadedOperatorName("&&"));
EXPECT_TRUE(matches("class Y { }; "
"bool operator&&(Y x, Y y) { return true; }; "
"Y a; Y b; bool c = a && b;", OpCallAndAnd));
StatementMatcher OpCallLessLess =
operatorCallExpr(hasOverloadedOperatorName("<<"));
EXPECT_TRUE(notMatches("class Y { }; "
"bool operator&&(Y x, Y y) { return true; }; "
"Y a; Y b; bool c = a && b;",
OpCallLessLess));
StatementMatcher OpStarCall =
operatorCallExpr(hasOverloadedOperatorName("*"));
EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
OpStarCall));
DeclarationMatcher ClassWithOpStar =
recordDecl(hasMethod(hasOverloadedOperatorName("*")));
EXPECT_TRUE(matches("class Y { int operator*(); };",
ClassWithOpStar));
EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
ClassWithOpStar)) ;
DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
}
TEST(Matcher, NestedOverloadedOperatorCalls) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class Y { }; "
"Y& operator&&(Y& x, Y& y) { return x; }; "
"Y a; Y b; Y c; Y d = a && b && c;",
operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
EXPECT_TRUE(matches(
"class Y { }; "
"Y& operator&&(Y& x, Y& y) { return x; }; "
"Y a; Y b; Y c; Y d = a && b && c;",
operatorCallExpr(hasParent(operatorCallExpr()))));
EXPECT_TRUE(matches(
"class Y { }; "
"Y& operator&&(Y& x, Y& y) { return x; }; "
"Y a; Y b; Y c; Y d = a && b && c;",
operatorCallExpr(hasDescendant(operatorCallExpr()))));
}
TEST(Matcher, ThisPointerType) {
StatementMatcher MethodOnY =
memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
MethodOnY));
EXPECT_TRUE(matches(
"class Y {"
" public: virtual void x();"
"};"
"class X : public Y {"
" public: virtual void x();"
"};"
"void z() { X *x; x->Y::x(); }", MethodOnY));
}
TEST(Matcher, VariableUsage) {
StatementMatcher Reference =
declRefExpr(to(
varDecl(hasInitializer(
memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
EXPECT_TRUE(matches(
"class Y {"
" public:"
" bool x() const;"
"};"
"void z(const Y &y) {"
" bool b = y.x();"
" if (b) {}"
"}", Reference));
EXPECT_TRUE(notMatches(
"class Y {"
" public:"
" bool x() const;"
"};"
"void z(const Y &y) {"
" bool b = y.x();"
"}", Reference));
}
TEST(Matcher, VarDecl_Storage) {
auto M = varDecl(hasName("X"), hasLocalStorage());
EXPECT_TRUE(matches("void f() { int X; }", M));
EXPECT_TRUE(notMatches("int X;", M));
EXPECT_TRUE(notMatches("void f() { static int X; }", M));
M = varDecl(hasName("X"), hasGlobalStorage());
EXPECT_TRUE(notMatches("void f() { int X; }", M));
EXPECT_TRUE(matches("int X;", M));
EXPECT_TRUE(matches("void f() { static int X; }", M));
}
TEST(Matcher, FindsVarDeclInFunctionParameter) {
EXPECT_TRUE(matches(
"void f(int i) {}",
varDecl(hasName("i"))));
}
TEST(Matcher, CalledVariable) {
StatementMatcher CallOnVariableY =
memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(matches(
"class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
EXPECT_TRUE(matches(
"class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
EXPECT_TRUE(matches(
"class Y { public: void x(); };"
"class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
EXPECT_TRUE(matches(
"class Y { public: void x(); };"
"class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
EXPECT_TRUE(notMatches(
"class Y { public: void x(); };"
"class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
CallOnVariableY));
}
TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
unaryExprOrTypeTraitExpr()));
EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
alignOfExpr(anything())));
// FIXME: Uncomment once alignof is enabled.
// EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
// unaryExprOrTypeTraitExpr()));
// EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
// sizeOfExpr()));
}
TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
hasArgumentOfType(asString("int")))));
EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
hasArgumentOfType(asString("float")))));
EXPECT_TRUE(matches(
"struct A {}; void x() { A a; int b = sizeof(a); }",
sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
}
TEST(MemberExpression, DoesNotMatchClasses) {
EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
}
TEST(MemberExpression, MatchesMemberFunctionCall) {
EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
}
TEST(MemberExpression, MatchesVariable) {
EXPECT_TRUE(
matches("class Y { void x() { this->y; } int y; };", memberExpr()));
EXPECT_TRUE(
matches("class Y { void x() { y; } int y; };", memberExpr()));
EXPECT_TRUE(
matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
}
TEST(MemberExpression, MatchesStaticVariable) {
EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
memberExpr()));
EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
memberExpr()));
EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
memberExpr()));
}
TEST(IsInteger, MatchesIntegers) {
EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
EXPECT_TRUE(matches(
"long long i = 0; void f(long long) { }; void g() {f(i);}",
callExpr(hasArgument(0, declRefExpr(
to(varDecl(hasType(isInteger()))))))));
}
TEST(IsInteger, ReportsNoFalsePositives) {
EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
callExpr(hasArgument(0, declRefExpr(
to(varDecl(hasType(isInteger()))))))));
}
TEST(IsArrow, MatchesMemberVariablesViaArrow) {
EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
memberExpr(isArrow())));
}
TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
memberExpr(isArrow())));
}
TEST(IsArrow, MatchesMemberCallsViaArrow) {
EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
memberExpr(isArrow())));
EXPECT_TRUE(matches("class Y { void x() { x(); } };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
memberExpr(isArrow())));
}
TEST(Callee, MatchesDeclarations) {
StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
CallMethodX = callExpr(callee(conversionDecl()));
EXPECT_TRUE(
matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
CallMethodX));
}
TEST(Callee, MatchesMemberExpressions) {
EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
callExpr(callee(memberExpr()))));
EXPECT_TRUE(
notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
}
TEST(Function, MatchesFunctionDeclarations) {
StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
llvm::Triple::Win32) {
// FIXME: Make this work for MSVC.
// Dependent contexts, but a non-dependent call.
EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
CallFunctionF));
EXPECT_TRUE(
matches("void f(); template <int N> struct S { void g() { f(); } };",
CallFunctionF));
}
// Depedent calls don't match.
EXPECT_TRUE(
notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
CallFunctionF));
EXPECT_TRUE(
notMatches("void f(int);"
"template <typename T> struct S { void g(T t) { f(t); } };",
CallFunctionF));
}
TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
EXPECT_TRUE(
matches("template <typename T> void f(T t) {}",
functionTemplateDecl(hasName("f"))));
}
TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
EXPECT_TRUE(
notMatches("void f(double d); void f(int t) {}",
functionTemplateDecl(hasName("f"))));
}
TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
EXPECT_TRUE(
notMatches("void g(); template <typename T> void f(T t) {}"
"template <> void f(int t) { g(); }",
functionTemplateDecl(hasName("f"),
hasDescendant(declRefExpr(to(
functionDecl(hasName("g"))))))));
}
TEST(Matcher, Argument) {
StatementMatcher CallArgumentY = callExpr(
hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
EXPECT_TRUE(
matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
StatementMatcher WrongIndex = callExpr(
hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
}
TEST(Matcher, AnyArgument) {
StatementMatcher CallArgumentY = callExpr(
hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
}
TEST(Matcher, ArgumentCount) {
StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
}
TEST(Matcher, ParameterCount) {
DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
}
TEST(Matcher, References) {
DeclarationMatcher ReferenceClassX = varDecl(
hasType(references(recordDecl(hasName("X")))));
EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
ReferenceClassX));
EXPECT_TRUE(
matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
// The match here is on the implicit copy constructor code for
// class X, not on code 'X x = y'.
EXPECT_TRUE(
matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
EXPECT_TRUE(
notMatches("class X {}; extern X x;", ReferenceClassX));
EXPECT_TRUE(
notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
}
TEST(QualType, hasCanonicalType) {
EXPECT_TRUE(notMatches("typedef int &int_ref;"
"int a;"
"int_ref b = a;",
varDecl(hasType(qualType(referenceType())))));
EXPECT_TRUE(
matches("typedef int &int_ref;"
"int a;"
"int_ref b = a;",
varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
}
TEST(QualType, hasLocalQualifiers) {
EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
varDecl(hasType(hasLocalQualifiers()))));
EXPECT_TRUE(matches("int *const j = nullptr;",
varDecl(hasType(hasLocalQualifiers()))));
EXPECT_TRUE(matches("int *volatile k;",
varDecl(hasType(hasLocalQualifiers()))));
EXPECT_TRUE(notMatches("int m;",
varDecl(hasType(hasLocalQualifiers()))));
}
TEST(HasParameter, CallsInnerMatcher) {
EXPECT_TRUE(matches("class X { void x(int) {} };",
methodDecl(hasParameter(0, varDecl()))));
EXPECT_TRUE(notMatches("class X { void x(int) {} };",
methodDecl(hasParameter(0, hasName("x")))));
}
TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
EXPECT_TRUE(notMatches("class X { void x(int) {} };",
methodDecl(hasParameter(42, varDecl()))));
}
TEST(HasType, MatchesParameterVariableTypesStrictly) {
EXPECT_TRUE(matches("class X { void x(X x) {} };",
methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
methodDecl(hasParameter(0,
hasType(pointsTo(recordDecl(hasName("X"))))))));
EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
methodDecl(hasParameter(0,
hasType(references(recordDecl(hasName("X"))))))));
}
TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
}
TEST(Returns, MatchesReturnTypes) {
EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
functionDecl(returns(asString("int")))));
EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
functionDecl(returns(asString("float")))));
EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
functionDecl(returns(hasDeclaration(
recordDecl(hasName("Y")))))));
}
TEST(IsExternC, MatchesExternCFunctionDeclarations) {
EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
functionDecl(isExternC())));
EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
}
TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
EXPECT_TRUE(
notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
EXPECT_TRUE(matches("void Func() = delete;",
functionDecl(hasName("Func"), isDeleted())));
}
TEST(isConstexpr, MatchesConstexprDeclarations) {
EXPECT_TRUE(matches("constexpr int foo = 42;",
varDecl(hasName("foo"), isConstexpr())));
EXPECT_TRUE(matches("constexpr int bar();",
functionDecl(hasName("bar"), isConstexpr())));
}
TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
}
TEST(HasAnyParameter, DoesNotMatchThisPointer) {
EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
methodDecl(hasAnyParameter(hasType(pointsTo(
recordDecl(hasName("X"))))))));
}
TEST(HasName, MatchesParameterVariableDeclarations) {
EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
methodDecl(hasAnyParameter(hasName("x")))));
EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
methodDecl(hasAnyParameter(hasName("x")))));
}
TEST(Matcher, MatchesClassTemplateSpecialization) {
EXPECT_TRUE(matches("template<typename T> struct A {};"
"template<> struct A<int> {};",
classTemplateSpecializationDecl()));
EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
classTemplateSpecializationDecl()));
EXPECT_TRUE(notMatches("template<typename T> struct A {};",
classTemplateSpecializationDecl()));
}
TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
EXPECT_TRUE(matches("int x;", declaratorDecl()));
EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
}
TEST(ParmVarDecl, MatchesParmVars) {
EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
}
TEST(Matcher, MatchesTypeTemplateArgument) {
EXPECT_TRUE(matches(
"template<typename T> struct B {};"
"B<int> b;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
asString("int"))))));
}
TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
EXPECT_TRUE(matches(
"struct B { int next; };"
"template<int(B::*next_ptr)> struct A {};"
"A<&B::next> a;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
refersToDeclaration(fieldDecl(hasName("next")))))));
EXPECT_TRUE(notMatches(
"template <typename T> struct A {};"
"A<int> a;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
refersToDeclaration(decl())))));
EXPECT_TRUE(matches(
"struct B { int next; };"
"template<int(B::*next_ptr)> struct A {};"
"A<&B::next> a;",
templateSpecializationType(hasAnyTemplateArgument(isExpr(
hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
EXPECT_TRUE(notMatches(
"template <typename T> struct A {};"
"A<int> a;",
templateSpecializationType(hasAnyTemplateArgument(
refersToDeclaration(decl())))));
}
TEST(Matcher, MatchesSpecificArgument) {
EXPECT_TRUE(matches(
"template<typename T, typename U> class A {};"
"A<bool, int> a;",
classTemplateSpecializationDecl(hasTemplateArgument(
1, refersToType(asString("int"))))));
EXPECT_TRUE(notMatches(
"template<typename T, typename U> class A {};"
"A<int, bool> a;",
classTemplateSpecializationDecl(hasTemplateArgument(
1, refersToType(asString("int"))))));
EXPECT_TRUE(matches(
"template<typename T, typename U> class A {};"
"A<bool, int> a;",
templateSpecializationType(hasTemplateArgument(
1, refersToType(asString("int"))))));
EXPECT_TRUE(notMatches(
"template<typename T, typename U> class A {};"
"A<int, bool> a;",
templateSpecializationType(hasTemplateArgument(
1, refersToType(asString("int"))))));
}
TEST(TemplateArgument, Matches) {
EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(templateArgument()))));
EXPECT_TRUE(matches(
"template<typename T> struct C {}; C<int> c;",
templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
}
TEST(TemplateArgumentCountIs, Matches) {
EXPECT_TRUE(
matches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(templateArgumentCountIs(1))));
EXPECT_TRUE(
notMatches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(templateArgumentCountIs(2))));
EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
templateSpecializationType(templateArgumentCountIs(1))));
EXPECT_TRUE(
notMatches("template<typename T> struct C {}; C<int> c;",
templateSpecializationType(templateArgumentCountIs(2))));
}
TEST(IsIntegral, Matches) {
EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(isIntegral()))));
EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
templateArgument(isIntegral())))));
}
TEST(RefersToIntegralType, Matches) {
EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(refersToIntegralType(
asString("int"))))));
EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
refersToIntegralType(asString("int"))))));
}
TEST(EqualsIntegralValue, Matches) {
EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(equalsIntegralValue("42")))));
EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(equalsIntegralValue("-42")))));
EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(equalsIntegralValue("-34")))));
EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
equalsIntegralValue("0042")))));
}
TEST(Matcher, MatchesAccessSpecDecls) {
EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
EXPECT_TRUE(
matches("class C { public: int i; };", accessSpecDecl(isPublic())));
EXPECT_TRUE(
notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
EXPECT_TRUE(
notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
}
TEST(Matcher, MatchesVirtualMethod) {
EXPECT_TRUE(matches("class X { virtual int f(); };",
methodDecl(isVirtual(), hasName("::X::f"))));
EXPECT_TRUE(notMatches("class X { int f(); };",
methodDecl(isVirtual())));
}
TEST(Matcher, MatchesPureMethod) {
EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
methodDecl(isPure(), hasName("::X::f"))));
EXPECT_TRUE(notMatches("class X { int f(); };",
methodDecl(isPure())));
}
TEST(Matcher, MatchesConstMethod) {
EXPECT_TRUE(matches("struct A { void foo() const; };",
methodDecl(isConst())));
EXPECT_TRUE(notMatches("struct A { void foo(); };",
methodDecl(isConst())));
}
TEST(Matcher, MatchesOverridingMethod) {
EXPECT_TRUE(matches("class X { virtual int f(); }; "
"class Y : public X { int f(); };",
methodDecl(isOverride(), hasName("::Y::f"))));
EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
"class Y : public X { int f(); };",
methodDecl(isOverride(), hasName("::X::f"))));
EXPECT_TRUE(notMatches("class X { int f(); }; "
"class Y : public X { int f(); };",
methodDecl(isOverride())));
EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
methodDecl(isOverride())));
EXPECT_TRUE(
matches("template <typename Base> struct Y : Base { void f() override;};",
methodDecl(isOverride(), hasName("::Y::f"))));
}
TEST(Matcher, ConstructorCall) {
StatementMatcher Constructor = constructExpr();
EXPECT_TRUE(
matches("class X { public: X(); }; void x() { X x; }", Constructor));
EXPECT_TRUE(
matches("class X { public: X(); }; void x() { X x = X(); }",
Constructor));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x = 0; }",
Constructor));
EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
}
TEST(Matcher, ConstructorArgument) {
StatementMatcher Constructor = constructExpr(
hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; X x(y); }",
Constructor));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
Constructor));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; X x = y; }",
Constructor));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
Constructor));
StatementMatcher WrongIndex = constructExpr(
hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
WrongIndex));
}
TEST(Matcher, ConstructorArgumentCount) {
StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x(0); }",
Constructor1Arg));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x = X(0); }",
Constructor1Arg));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x = 0; }",
Constructor1Arg));
EXPECT_TRUE(
notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
Constructor1Arg));
}
TEST(Matcher, ConstructorListInitialization) {
StatementMatcher ConstructorListInit = constructExpr(isListInitialization());
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x{0}; }",
ConstructorListInit));
EXPECT_FALSE(
matches("class X { public: X(int); }; void x() { X x(0); }",
ConstructorListInit));
}
TEST(Matcher,ThisExpr) {
EXPECT_TRUE(
matches("struct X { int a; int f () { return a; } };", thisExpr()));
EXPECT_TRUE(
notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
}
TEST(Matcher, BindTemporaryExpression) {
StatementMatcher TempExpression = bindTemporaryExpr();
std::string ClassString = "class string { public: string(); ~string(); }; ";
EXPECT_TRUE(
matches(ClassString +
"string GetStringByValue();"
"void FunctionTakesString(string s);"
"void run() { FunctionTakesString(GetStringByValue()); }",
TempExpression));
EXPECT_TRUE(
notMatches(ClassString +
"string* GetStringPointer(); "
"void FunctionTakesStringPtr(string* s);"
"void run() {"
" string* s = GetStringPointer();"
" FunctionTakesStringPtr(GetStringPointer());"
" FunctionTakesStringPtr(s);"
"}",
TempExpression));
EXPECT_TRUE(
notMatches("class no_dtor {};"
"no_dtor GetObjByValue();"
"void ConsumeObj(no_dtor param);"
"void run() { ConsumeObj(GetObjByValue()); }",
TempExpression));
}
TEST(MaterializeTemporaryExpr, MatchesTemporary) {
std::string ClassString =
"class string { public: string(); int length(); }; ";
EXPECT_TRUE(
matches(ClassString +
"string GetStringByValue();"
"void FunctionTakesString(string s);"
"void run() { FunctionTakesString(GetStringByValue()); }",
materializeTemporaryExpr()));
EXPECT_TRUE(
notMatches(ClassString +
"string* GetStringPointer(); "
"void FunctionTakesStringPtr(string* s);"
"void run() {"
" string* s = GetStringPointer();"
" FunctionTakesStringPtr(GetStringPointer());"
" FunctionTakesStringPtr(s);"
"}",
materializeTemporaryExpr()));
EXPECT_TRUE(
notMatches(ClassString +
"string GetStringByValue();"
"void run() { int k = GetStringByValue().length(); }",
materializeTemporaryExpr()));
EXPECT_TRUE(
notMatches(ClassString +
"string GetStringByValue();"
"void run() { GetStringByValue(); }",
materializeTemporaryExpr()));
}
TEST(ConstructorDeclaration, SimpleCase) {
EXPECT_TRUE(matches("class Foo { Foo(int i); };",
constructorDecl(ofClass(hasName("Foo")))));
EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
constructorDecl(ofClass(hasName("Bar")))));
}
TEST(ConstructorDeclaration, IsImplicit) {
// This one doesn't match because the constructor is not added by the
// compiler (it is not needed).
EXPECT_TRUE(notMatches("class Foo { };",
constructorDecl(isImplicit())));
// The compiler added the implicit default constructor.
EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
constructorDecl(isImplicit())));
EXPECT_TRUE(matches("class Foo { Foo(){} };",
constructorDecl(unless(isImplicit()))));
// The compiler added an implicit assignment operator.
EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
methodDecl(isImplicit(), hasName("operator="))));
}
TEST(DestructorDeclaration, MatchesVirtualDestructor) {
EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
destructorDecl(ofClass(hasName("Foo")))));
}
TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
EXPECT_TRUE(notMatches("class Foo {};",
destructorDecl(ofClass(hasName("Foo")))));
}
TEST(HasAnyConstructorInitializer, SimpleCase) {
EXPECT_TRUE(notMatches(
"class Foo { Foo() { } };",
constructorDecl(hasAnyConstructorInitializer(anything()))));
EXPECT_TRUE(matches(
"class Foo {"
" Foo() : foo_() { }"
" int foo_;"
"};",
constructorDecl(hasAnyConstructorInitializer(anything()))));
}
TEST(HasAnyConstructorInitializer, ForField) {
static const char Code[] =
"class Baz { };"
"class Foo {"
" Foo() : foo_() { }"
" Baz foo_;"
" Baz bar_;"
"};";
EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
forField(hasType(recordDecl(hasName("Baz"))))))));
EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
forField(hasName("foo_"))))));
EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
forField(hasType(recordDecl(hasName("Bar"))))))));
}
TEST(HasAnyConstructorInitializer, WithInitializer) {
static const char Code[] =
"class Foo {"
" Foo() : foo_(0) { }"
" int foo_;"
"};";
EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
withInitializer(integerLiteral(equals(0)))))));
EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
withInitializer(integerLiteral(equals(1)))))));
}
TEST(HasAnyConstructorInitializer, IsWritten) {
static const char Code[] =
"struct Bar { Bar(){} };"
"class Foo {"
" Foo() : foo_() { }"
" Bar foo_;"
" Bar bar_;"
"};";
EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
allOf(forField(hasName("foo_")), isWritten())))));
EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
allOf(forField(hasName("bar_")), isWritten())))));
EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
allOf(forField(hasName("bar_")), unless(isWritten()))))));
}
TEST(Matcher, NewExpression) {
StatementMatcher New = newExpr();
EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
EXPECT_TRUE(
matches("class X { public: X(); }; void x() { new X(); }", New));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { new X(0); }", New));
EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
}
TEST(Matcher, NewExpressionArgument) {
StatementMatcher New = constructExpr(
hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; new X(y); }",
New));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; new X(y); }",
New));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
New));
StatementMatcher WrongIndex = constructExpr(
hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
WrongIndex));
}
TEST(Matcher, NewExpressionArgumentCount) {
StatementMatcher New = constructExpr(argumentCountIs(1));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { new X(0); }", New));
EXPECT_TRUE(
notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
New));
}
TEST(Matcher, DeleteExpression) {
EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
deleteExpr()));
}
TEST(Matcher, DefaultArgument) {
StatementMatcher Arg = defaultArgExpr();
EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
EXPECT_TRUE(
matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
}
TEST(Matcher, StringLiterals) {
StatementMatcher Literal = stringLiteral();
EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
// wide string
EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
// with escaped characters
EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
// no matching -- though the data type is the same, there is no string literal
EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
}
TEST(Matcher, CharacterLiterals) {
StatementMatcher CharLiteral = characterLiteral();
EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
// wide character
EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
// wide character, Hex encoded, NOT MATCHED!
EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
}
TEST(Matcher, IntegerLiterals) {
StatementMatcher HasIntLiteral = integerLiteral();
EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
// Non-matching cases (character literals, float and double)
EXPECT_TRUE(notMatches("int i = L'a';",
HasIntLiteral)); // this is actually a character
// literal cast to int
EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
}
TEST(Matcher, FloatLiterals) {
StatementMatcher HasFloatLiteral = floatLiteral();
EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
EXPECT_TRUE(
matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
EXPECT_TRUE(
notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
}
TEST(Matcher, NullPtrLiteral) {
EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
}
TEST(Matcher, GNUNullExpr) {
EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
}
TEST(Matcher, AsmStatement) {
EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
}
TEST(Matcher, Conditions) {
StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
}
TEST(IfStmt, ChildTraversalMatchers) {
EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
ifStmt(hasThen(boolLiteral(equals(true))))));
EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
ifStmt(hasThen(boolLiteral(equals(true))))));
EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
ifStmt(hasElse(boolLiteral(equals(true))))));
EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
ifStmt(hasElse(boolLiteral(equals(true))))));
}
TEST(MatchBinaryOperator, HasOperatorName) {
StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
}
TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
StatementMatcher OperatorTrueFalse =
binaryOperator(hasLHS(boolLiteral(equals(true))),
hasRHS(boolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
}
TEST(MatchBinaryOperator, HasEitherOperand) {
StatementMatcher HasOperand =
binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
}
TEST(Matcher, BinaryOperatorTypes) {
// Integration test that verifies the AST provides all binary operators in
// a way we expect.
// FIXME: Operator ','
EXPECT_TRUE(
matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
EXPECT_TRUE(
matches("bool b; bool c = (b = true);",
binaryOperator(hasOperatorName("="))));
EXPECT_TRUE(
matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
EXPECT_TRUE(
matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
EXPECT_TRUE(
matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
EXPECT_TRUE(
matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
EXPECT_TRUE(
matches("int i = 1; int j = (i <<= 2);",
binaryOperator(hasOperatorName("<<="))));
EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
EXPECT_TRUE(
matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
EXPECT_TRUE(
matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
EXPECT_TRUE(
matches("int i = 1; int j = (i >>= 2);",
binaryOperator(hasOperatorName(">>="))));
EXPECT_TRUE(
matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i ^= 42);",
binaryOperator(hasOperatorName("^="))));
EXPECT_TRUE(
matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i %= 42);",
binaryOperator(hasOperatorName("%="))));
EXPECT_TRUE(
matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
EXPECT_TRUE(
matches("bool b = true && false;",
binaryOperator(hasOperatorName("&&"))));
EXPECT_TRUE(
matches("bool b = true; bool c = (b &= false);",
binaryOperator(hasOperatorName("&="))));
EXPECT_TRUE(
matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
EXPECT_TRUE(
matches("bool b = true || false;",
binaryOperator(hasOperatorName("||"))));
EXPECT_TRUE(
matches("bool b = true; bool c = (b |= false);",
binaryOperator(hasOperatorName("|="))));
EXPECT_TRUE(
matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i *= 23);",
binaryOperator(hasOperatorName("*="))));
EXPECT_TRUE(
matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i /= 23);",
binaryOperator(hasOperatorName("/="))));
EXPECT_TRUE(
matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i += 23);",
binaryOperator(hasOperatorName("+="))));
EXPECT_TRUE(
matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i -= 23);",
binaryOperator(hasOperatorName("-="))));
EXPECT_TRUE(
matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
binaryOperator(hasOperatorName("->*"))));
EXPECT_TRUE(
matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
binaryOperator(hasOperatorName(".*"))));
// Member expressions as operators are not supported in matches.
EXPECT_TRUE(
notMatches("struct A { void x(A *a) { a->x(this); } };",
binaryOperator(hasOperatorName("->"))));
// Initializer assignments are not represented as operator equals.
EXPECT_TRUE(
notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
// Array indexing is not represented as operator.
EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
// Overloaded operators do not match at all.
EXPECT_TRUE(notMatches(
"struct A { bool operator&&(const A &a) const { return false; } };"
"void x() { A a, b; a && b; }",
binaryOperator()));
}
TEST(MatchUnaryOperator, HasOperatorName) {
StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
}
TEST(MatchUnaryOperator, HasUnaryOperand) {
StatementMatcher OperatorOnFalse =
unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
}
TEST(Matcher, UnaryOperatorTypes) {
// Integration test that verifies the AST provides all unary operators in
// a way we expect.
EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
EXPECT_TRUE(
matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
EXPECT_TRUE(
matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
EXPECT_TRUE(
matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
EXPECT_TRUE(
matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
EXPECT_TRUE(
matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
EXPECT_TRUE(
matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
EXPECT_TRUE(
matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
EXPECT_TRUE(
matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
// We don't match conversion operators.
EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
// Function calls are not represented as operator.
EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
// Overloaded operators do not match at all.
// FIXME: We probably want to add that.
EXPECT_TRUE(notMatches(
"struct A { bool operator!() const { return false; } };"
"void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
}
TEST(Matcher, ConditionalOperator) {
StatementMatcher Conditional = conditionalOperator(
hasCondition(boolLiteral(equals(true))),
hasTrueExpression(boolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
StatementMatcher ConditionalFalse = conditionalOperator(
hasFalseExpression(boolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
EXPECT_TRUE(
notMatches("void x() { true ? false : true; }", ConditionalFalse));
}
TEST(ArraySubscriptMatchers, ArraySubscripts) {
EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
arraySubscriptExpr()));
EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
arraySubscriptExpr()));
}
TEST(ArraySubscriptMatchers, ArrayIndex) {
EXPECT_TRUE(matches(
"int i[2]; void f() { i[1] = 1; }",
arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
EXPECT_TRUE(matches(
"int i[2]; void f() { 1[i] = 1; }",
arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
EXPECT_TRUE(notMatches(
"int i[2]; void f() { i[1] = 1; }",
arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
}
TEST(ArraySubscriptMatchers, MatchesArrayBase) {
EXPECT_TRUE(matches(
"int i[2]; void f() { i[1] = 2; }",
arraySubscriptExpr(hasBase(implicitCastExpr(
hasSourceExpression(declRefExpr()))))));
}
TEST(Matcher, HasNameSupportsNamespaces) {
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a::b::C"))));
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("::a::b::C"))));
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("b::C"))));
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("c::b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a::c::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a::b::A"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("::b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("z::a::b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a+b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
recordDecl(hasName("C"))));
}
TEST(Matcher, HasNameSupportsOuterClasses) {
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("A::B::C"))));
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("::A::B::C"))));
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("B::C"))));
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("c::B::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("A::c::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("A::B::A"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("::B::C"))));
EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
recordDecl(hasName("z::A::B::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("A+B::C"))));
}
TEST(Matcher, IsDefinition) {
DeclarationMatcher DefinitionOfClassA =
recordDecl(hasName("A"), isDefinition());
EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
DeclarationMatcher DefinitionOfVariableA =
varDecl(hasName("a"), isDefinition());
EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
DeclarationMatcher DefinitionOfMethodA =
methodDecl(hasName("a"), isDefinition());
EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
}
TEST(Matcher, OfClass) {
StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
ofClass(hasName("X")))));
EXPECT_TRUE(
matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
EXPECT_TRUE(
matches("class X { public: X(); }; void x(int) { X x = X(); }",
Constructor));
EXPECT_TRUE(
notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
Constructor));
}
TEST(Matcher, VisitsTemplateInstantiations) {
EXPECT_TRUE(matches(
"class A { public: void x(); };"
"template <typename T> class B { public: void y() { T t; t.x(); } };"
"void f() { B<A> b; b.y(); }",
callExpr(callee(methodDecl(hasName("x"))))));
EXPECT_TRUE(matches(
"class A { public: void x(); };"
"class C {"
" public:"
" template <typename T> class B { public: void y() { T t; t.x(); } };"
"};"
"void f() {"
" C::B<A> b; b.y();"
"}",
recordDecl(hasName("C"),
hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
}
TEST(Matcher, HandlesNullQualTypes) {
// FIXME: Add a Type matcher so we can replace uses of this
// variable with Type(True())
const TypeMatcher AnyType = anything();
// We don't really care whether this matcher succeeds; we're testing that
// it completes without crashing.
EXPECT_TRUE(matches(
"struct A { };"
"template <typename T>"
"void f(T t) {"
" T local_t(t /* this becomes a null QualType in the AST */);"
"}"
"void g() {"
" f(0);"
"}",
expr(hasType(TypeMatcher(
anyOf(
TypeMatcher(hasDeclaration(anything())),
pointsTo(AnyType),
references(AnyType)
// Other QualType matchers should go here.
))))));
}
// For testing AST_MATCHER_P().
AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
// Make sure all special variables are used: node, match_finder,
// bound_nodes_builder, and the parameter named 'AMatcher'.
return AMatcher.matches(Node, Finder, Builder);
}
TEST(AstMatcherPMacro, Works) {
DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
}
AST_POLYMORPHIC_MATCHER_P(polymorphicHas,
AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt),
internal::Matcher<Decl>, AMatcher) {
return Finder->matchesChildOf(
Node, AMatcher, Builder,
ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
ASTMatchFinder::BK_First);
}
TEST(AstPolymorphicMatcherPMacro, Works) {
DeclarationMatcher HasClassB =
polymorphicHas(recordDecl(hasName("B")).bind("b"));
EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
StatementMatcher StatementHasClassB =
polymorphicHas(recordDecl(hasName("B")));
EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
}
TEST(For, FindsForLoops) {
EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
"void f() { for (auto &a : as); }",
forStmt()));
}
TEST(For, ForLoopInternals) {
EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
forStmt(hasCondition(anything()))));
EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
forStmt(hasLoopInit(anything()))));
}
TEST(For, ForRangeLoopInternals) {
EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
forRangeStmt(hasLoopVariable(anything()))));
EXPECT_TRUE(matches(
"void f(){ int a[] {1, 2}; for (int i : a); }",
forRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
}
TEST(For, NegativeForLoopInternals) {
EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
forStmt(hasCondition(expr()))));
EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
forStmt(hasLoopInit(anything()))));
}
TEST(For, ReportsNoFalsePositives) {
EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
}
TEST(CompoundStatement, HandlesSimpleCases) {
EXPECT_TRUE(notMatches("void f();", compoundStmt()));
EXPECT_TRUE(matches("void f() {}", compoundStmt()));
EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
}
TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
// It's not a compound statement just because there's "{}" in the source
// text. This is an AST search, not grep.
EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
compoundStmt()));
EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
compoundStmt()));
}
TEST(HasBody, FindsBodyOfForWhileDoLoops) {
EXPECT_TRUE(matches("void f() { for(;;) {} }",
forStmt(hasBody(compoundStmt()))));
EXPECT_TRUE(notMatches("void f() { for(;;); }",
forStmt(hasBody(compoundStmt()))));
EXPECT_TRUE(matches("void f() { while(true) {} }",
whileStmt(hasBody(compoundStmt()))));
EXPECT_TRUE(matches("void f() { do {} while(true); }",
doStmt(hasBody(compoundStmt()))));
EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
forRangeStmt(hasBody(compoundStmt()))));
}
TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
// The simplest case: every compound statement is in a function
// definition, and the function body itself must be a compound
// statement.
EXPECT_TRUE(matches("void f() { for (;;); }",
compoundStmt(hasAnySubstatement(forStmt()))));
}
TEST(HasAnySubstatement, IsNotRecursive) {
// It's really "has any immediate substatement".
EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
compoundStmt(hasAnySubstatement(forStmt()))));
}
TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
compoundStmt(hasAnySubstatement(forStmt()))));
}
TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
compoundStmt(hasAnySubstatement(forStmt()))));
}
TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
EXPECT_TRUE(matches("void f() { }",
compoundStmt(statementCountIs(0))));
EXPECT_TRUE(notMatches("void f() {}",
compoundStmt(statementCountIs(1))));
}
TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
EXPECT_TRUE(matches("void f() { 1; }",
compoundStmt(statementCountIs(1))));
EXPECT_TRUE(notMatches("void f() { 1; }",
compoundStmt(statementCountIs(0))));
EXPECT_TRUE(notMatches("void f() { 1; }",
compoundStmt(statementCountIs(2))));
}
TEST(StatementCountIs, WorksWithMultipleStatements) {
EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
compoundStmt(statementCountIs(3))));
}
TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
compoundStmt(statementCountIs(1))));
EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
compoundStmt(statementCountIs(2))));
EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
compoundStmt(statementCountIs(3))));
EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
compoundStmt(statementCountIs(4))));
}
TEST(Member, WorksInSimplestCase) {
EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
memberExpr(member(hasName("first")))));
}
TEST(Member, DoesNotMatchTheBaseExpression) {
// Don't pick out the wrong part of the member expression, this should
// be checking the member (name) only.
EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
memberExpr(member(hasName("first")))));
}
TEST(Member, MatchesInMemberFunctionCall) {
EXPECT_TRUE(matches("void f() {"
" struct { void first() {}; } s;"
" s.first();"
"};",
memberExpr(member(hasName("first")))));
}
TEST(Member, MatchesMember) {
EXPECT_TRUE(matches(
"struct A { int i; }; void f() { A a; a.i = 2; }",
memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
EXPECT_TRUE(notMatches(
"struct A { float f; }; void f() { A a; a.f = 2.0f; }",
memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
}
TEST(Member, UnderstandsAccess) {
EXPECT_TRUE(matches(
"struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
EXPECT_TRUE(notMatches(
"struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
EXPECT_TRUE(notMatches(
"struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
EXPECT_TRUE(notMatches(
"class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
EXPECT_TRUE(notMatches(
"class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
EXPECT_TRUE(matches(
"class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
EXPECT_TRUE(notMatches(
"class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
EXPECT_TRUE(matches("class A { protected: int i; };",
fieldDecl(isProtected(), hasName("i"))));
EXPECT_TRUE(notMatches(
"class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
// Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
}
TEST(Member, MatchesMemberAllocationFunction) {
// Fails in C++11 mode
EXPECT_TRUE(matchesConditionally(
"namespace std { typedef typeof(sizeof(int)) size_t; }"
"class X { void *operator new(std::size_t); };",
methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
EXPECT_TRUE(matches("class X { void operator delete(void*); };",
methodDecl(ofClass(hasName("X")))));
// Fails in C++11 mode
EXPECT_TRUE(matchesConditionally(
"namespace std { typedef typeof(sizeof(int)) size_t; }"
"class X { void operator delete[](void*, std::size_t); };",
methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
}
TEST(HasObjectExpression, DoesNotMatchMember) {
EXPECT_TRUE(notMatches(
"class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
}
TEST(HasObjectExpression, MatchesBaseOfVariable) {
EXPECT_TRUE(matches(
"struct X { int m; }; void f(X x) { x.m; }",
memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
EXPECT_TRUE(matches(
"struct X { int m; }; void f(X* x) { x->m; }",
memberExpr(hasObjectExpression(
hasType(pointsTo(recordDecl(hasName("X"))))))));
}
TEST(HasObjectExpression,
MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
EXPECT_TRUE(matches(
"class X {}; struct S { X m; void f() { this->m; } };",
memberExpr(hasObjectExpression(
hasType(pointsTo(recordDecl(hasName("S"))))))));
EXPECT_TRUE(matches(
"class X {}; struct S { X m; void f() { m; } };",
memberExpr(hasObjectExpression(
hasType(pointsTo(recordDecl(hasName("S"))))))));
}
TEST(Field, DoesNotMatchNonFieldMembers) {
EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
}
TEST(Field, MatchesField) {
EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
}
TEST(IsConstQualified, MatchesConstInt) {
EXPECT_TRUE(matches("const int i = 42;",
varDecl(hasType(isConstQualified()))));
}
TEST(IsConstQualified, MatchesConstPointer) {
EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
varDecl(hasType(isConstQualified()))));
}
TEST(IsConstQualified, MatchesThroughTypedef) {
EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
varDecl(hasType(isConstQualified()))));
EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
varDecl(hasType(isConstQualified()))));
}
TEST(IsConstQualified, DoesNotMatchInappropriately) {
EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
varDecl(hasType(isConstQualified()))));
EXPECT_TRUE(notMatches("int const* p;",
varDecl(hasType(isConstQualified()))));
}
TEST(CastExpression, MatchesExplicitCasts) {
EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
EXPECT_TRUE(matches("char c = char(0);", castExpr()));
}
TEST(CastExpression, MatchesImplicitCasts) {
// This test creates an implicit cast from int to char.
EXPECT_TRUE(matches("char c = 0;", castExpr()));
// This test creates an implicit cast from lvalue to rvalue.
EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
}
TEST(CastExpression, DoesNotMatchNonCasts) {
EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
}
TEST(ReinterpretCast, MatchesSimpleCase) {
EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
reinterpretCastExpr()));
}
TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
reinterpretCastExpr()));
EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
reinterpretCastExpr()));
EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
"B b;"
"D* p = dynamic_cast<D*>(&b);",
reinterpretCastExpr()));
}
TEST(FunctionalCast, MatchesSimpleCase) {
std::string foo_class = "class Foo { public: Foo(const char*); };";
EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
functionalCastExpr()));
}
TEST(FunctionalCast, DoesNotMatchOtherCasts) {
std::string FooClass = "class Foo { public: Foo(const char*); };";
EXPECT_TRUE(
notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
functionalCastExpr()));
EXPECT_TRUE(
notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
functionalCastExpr()));
}
TEST(DynamicCast, MatchesSimpleCase) {
EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
"B b;"
"D* p = dynamic_cast<D*>(&b);",
dynamicCastExpr()));
}
TEST(StaticCast, MatchesSimpleCase) {
EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
staticCastExpr()));
}
TEST(StaticCast, DoesNotMatchOtherCasts) {
EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
staticCastExpr()));
EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
staticCastExpr()));
EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
"B b;"
"D* p = dynamic_cast<D*>(&b);",
staticCastExpr()));
}
TEST(CStyleCast, MatchesSimpleCase) {
EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
}
TEST(CStyleCast, DoesNotMatchOtherCasts) {
EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
"char q, *r = const_cast<char*>(&q);"
"void* s = reinterpret_cast<char*>(&s);"
"struct B { virtual ~B() {} }; struct D : B {};"
"B b;"
"D* t = dynamic_cast<D*>(&b);",
cStyleCastExpr()));
}
TEST(HasDestinationType, MatchesSimpleCase) {
EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
staticCastExpr(hasDestinationType(
pointsTo(TypeMatcher(anything()))))));
}
TEST(HasImplicitDestinationType, MatchesSimpleCase) {
// This test creates an implicit const cast.
EXPECT_TRUE(matches("int x; const int i = x;",
implicitCastExpr(
hasImplicitDestinationType(isInteger()))));
// This test creates an implicit array-to-pointer cast.
EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
implicitCastExpr(hasImplicitDestinationType(
pointsTo(TypeMatcher(anything()))))));
}
TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
// This test creates an implicit cast from int to char.
EXPECT_TRUE(notMatches("char c = 0;",
implicitCastExpr(hasImplicitDestinationType(
unless(anything())))));
// This test creates an implicit array-to-pointer cast.
EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
implicitCastExpr(hasImplicitDestinationType(
unless(anything())))));
}
TEST(ImplicitCast, MatchesSimpleCase) {
// This test creates an implicit const cast.
EXPECT_TRUE(matches("int x = 0; const int y = x;",
varDecl(hasInitializer(implicitCastExpr()))));
// This test creates an implicit cast from int to char.
EXPECT_TRUE(matches("char c = 0;",
varDecl(hasInitializer(implicitCastExpr()))));
// This test creates an implicit array-to-pointer cast.
EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
varDecl(hasInitializer(implicitCastExpr()))));
}
TEST(ImplicitCast, DoesNotMatchIncorrectly) {
// This test verifies that implicitCastExpr() matches exactly when implicit casts
// are present, and that it ignores explicit and paren casts.
// These two test cases have no casts.
EXPECT_TRUE(notMatches("int x = 0;",
varDecl(hasInitializer(implicitCastExpr()))));
EXPECT_TRUE(notMatches("int x = 0, &y = x;",
varDecl(hasInitializer(implicitCastExpr()))));
EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
varDecl(hasInitializer(implicitCastExpr()))));
EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
varDecl(hasInitializer(implicitCastExpr()))));
EXPECT_TRUE(notMatches("int x = (0);",
varDecl(hasInitializer(implicitCastExpr()))));
}
TEST(IgnoringImpCasts, MatchesImpCasts) {
// This test checks that ignoringImpCasts matches when implicit casts are
// present and its inner matcher alone does not match.
// Note that this test creates an implicit const cast.
EXPECT_TRUE(matches("int x = 0; const int y = x;",
varDecl(hasInitializer(ignoringImpCasts(
declRefExpr(to(varDecl(hasName("x")))))))));
// This test creates an implict cast from int to char.
EXPECT_TRUE(matches("char x = 0;",
varDecl(hasInitializer(ignoringImpCasts(
integerLiteral(equals(0)))))));
}
TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
// These tests verify that ignoringImpCasts does not match if the inner
// matcher does not match.
// Note that the first test creates an implicit const cast.
EXPECT_TRUE(notMatches("int x; const int y = x;",
varDecl(hasInitializer(ignoringImpCasts(
unless(anything()))))));
EXPECT_TRUE(notMatches("int x; int y = x;",
varDecl(hasInitializer(ignoringImpCasts(
unless(anything()))))));
// These tests verify that ignoringImplictCasts does not look through explicit
// casts or parentheses.
EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
varDecl(hasInitializer(ignoringImpCasts(
integerLiteral())))));
EXPECT_TRUE(notMatches("int i = (0);",
varDecl(hasInitializer(ignoringImpCasts(
integerLiteral())))));
EXPECT_TRUE(notMatches("float i = (float)0;",
varDecl(hasInitializer(ignoringImpCasts(
integerLiteral())))));
EXPECT_TRUE(notMatches("float i = float(0);",
varDecl(hasInitializer(ignoringImpCasts(
integerLiteral())))));
}
TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
// This test verifies that expressions that do not have implicit casts
// still match the inner matcher.
EXPECT_TRUE(matches("int x = 0; int &y = x;",
varDecl(hasInitializer(ignoringImpCasts(
declRefExpr(to(varDecl(hasName("x")))))))));
}
TEST(IgnoringParenCasts, MatchesParenCasts) {
// This test checks that ignoringParenCasts matches when parentheses and/or
// casts are present and its inner matcher alone does not match.
EXPECT_TRUE(matches("int x = (0);",
varDecl(hasInitializer(ignoringParenCasts(
integerLiteral(equals(0)))))));
EXPECT_TRUE(matches("int x = (((((0)))));",
varDecl(hasInitializer(ignoringParenCasts(
integerLiteral(equals(0)))))));
// This test creates an implict cast from int to char in addition to the
// parentheses.
EXPECT_TRUE(matches("char x = (0);",
varDecl(hasInitializer(ignoringParenCasts(
integerLiteral(equals(0)))))));
EXPECT_TRUE(matches("char x = (char)0;",
varDecl(hasInitializer(ignoringParenCasts(
integerLiteral(equals(0)))))));
EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
varDecl(hasInitializer(ignoringParenCasts(
integerLiteral(equals(0)))))));
}
TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
// This test verifies that expressions that do not have any casts still match.
EXPECT_TRUE(matches("int x = 0;",
varDecl(hasInitializer(ignoringParenCasts(
integerLiteral(equals(0)))))));
}
TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
// These tests verify that ignoringImpCasts does not match if the inner
// matcher does not match.
EXPECT_TRUE(notMatches("int x = ((0));",
varDecl(hasInitializer(ignoringParenCasts(
unless(anything()))))));
// This test creates an implicit cast from int to char in addition to the
// parentheses.
EXPECT_TRUE(notMatches("char x = ((0));",
varDecl(hasInitializer(ignoringParenCasts(
unless(anything()))))));
EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
varDecl(hasInitializer(ignoringParenCasts(
unless(anything()))))));
}
TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
// This test checks that ignoringParenAndImpCasts matches when
// parentheses and/or implicit casts are present and its inner matcher alone
// does not match.
// Note that this test creates an implicit const cast.
EXPECT_TRUE(matches("int x = 0; const int y = x;",
varDecl(hasInitializer(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasName("x")))))))));
// This test creates an implicit cast from int to char.
EXPECT_TRUE(matches("const char x = (0);",
varDecl(hasInitializer(ignoringParenImpCasts(
integerLiteral(equals(0)))))));
}
TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
// This test verifies that expressions that do not have parentheses or
// implicit casts still match.
EXPECT_TRUE(matches("int x = 0; int &y = x;",
varDecl(hasInitializer(ignoringParenImpCasts(
declRefExpr(to(varDecl(hasName("x")))))))));
EXPECT_TRUE(matches("int x = 0;",
varDecl(hasInitializer(ignoringParenImpCasts(
integerLiteral(equals(0)))))));
}
TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
// These tests verify that ignoringParenImpCasts does not match if
// the inner matcher does not match.
// This test creates an implicit cast.
EXPECT_TRUE(notMatches("char c = ((3));",
varDecl(hasInitializer(ignoringParenImpCasts(
unless(anything()))))));
// These tests verify that ignoringParenAndImplictCasts does not look
// through explicit casts.
EXPECT_TRUE(notMatches("float y = (float(0));",
varDecl(hasInitializer(ignoringParenImpCasts(
integerLiteral())))));
EXPECT_TRUE(notMatches("float y = (float)0;",
varDecl(hasInitializer(ignoringParenImpCasts(
integerLiteral())))));
EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
varDecl(hasInitializer(ignoringParenImpCasts(
integerLiteral())))));
}
TEST(HasSourceExpression, MatchesImplicitCasts) {
EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
"void r() {string a_string; URL url = a_string; }",
implicitCastExpr(
hasSourceExpression(constructExpr()))));
}
TEST(HasSourceExpression, MatchesExplicitCasts) {
EXPECT_TRUE(matches("float x = static_cast<float>(42);",
explicitCastExpr(
hasSourceExpression(hasDescendant(
expr(integerLiteral()))))));
}
TEST(Statement, DoesNotMatchDeclarations) {
EXPECT_TRUE(notMatches("class X {};", stmt()));
}
TEST(Statement, MatchesCompoundStatments) {
EXPECT_TRUE(matches("void x() {}", stmt()));
}
TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
EXPECT_TRUE(notMatches("void x() {}", declStmt()));
}
TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
}
TEST(ExprWithCleanups, MatchesExprWithCleanups) {
EXPECT_TRUE(matches("struct Foo { ~Foo(); };"
"const Foo f = Foo();",
varDecl(hasInitializer(exprWithCleanups()))));
EXPECT_FALSE(matches("struct Foo { };"
"const Foo f = Foo();",
varDecl(hasInitializer(exprWithCleanups()))));
}
TEST(InitListExpression, MatchesInitListExpression) {
EXPECT_TRUE(matches("int a[] = { 1, 2 };",
initListExpr(hasType(asString("int [2]")))));
EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
initListExpr(hasType(recordDecl(hasName("B"))))));
EXPECT_TRUE(matches("struct S { S(void (*a)()); };"
"void f();"
"S s[1] = { &f };",
declRefExpr(to(functionDecl(hasName("f"))))));
EXPECT_TRUE(
matches("int i[1] = {42, [0] = 43};", integerLiteral(equals(42))));
}
TEST(UsingDeclaration, MatchesUsingDeclarations) {
EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
usingDecl()));
}
TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
}
TEST(UsingDeclaration, MatchesSpecificTarget) {
EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
usingDecl(hasAnyUsingShadowDecl(
hasTargetDecl(functionDecl())))));
EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
usingDecl(hasAnyUsingShadowDecl(
hasTargetDecl(functionDecl())))));
}
TEST(UsingDeclaration, ThroughUsingDeclaration) {
EXPECT_TRUE(matches(
"namespace a { void f(); } using a::f; void g() { f(); }",
declRefExpr(throughUsingDecl(anything()))));
EXPECT_TRUE(notMatches(
"namespace a { void f(); } using a::f; void g() { a::f(); }",
declRefExpr(throughUsingDecl(anything()))));
}
TEST(UsingDirectiveDeclaration, MatchesUsingNamespace) {
EXPECT_TRUE(matches("namespace X { int x; } using namespace X;",
usingDirectiveDecl()));
EXPECT_FALSE(
matches("namespace X { int x; } using X::x;", usingDirectiveDecl()));
}
TEST(SingleDecl, IsSingleDecl) {
StatementMatcher SingleDeclStmt =
declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
SingleDeclStmt));
}
TEST(DeclStmt, ContainsDeclaration) {
DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
EXPECT_TRUE(matches("void f() {int a = 4;}",
declStmt(containsDeclaration(0, MatchesInit))));
EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
declStmt(containsDeclaration(0, MatchesInit),
containsDeclaration(1, MatchesInit))));
unsigned WrongIndex = 42;
EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
declStmt(containsDeclaration(WrongIndex,
MatchesInit))));
}
TEST(DeclCount, DeclCountIsCorrect) {
EXPECT_TRUE(matches("void f() {int i,j;}",
declStmt(declCountIs(2))));
EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
declStmt(declCountIs(3))));
EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
declStmt(declCountIs(3))));
}
TEST(While, MatchesWhileLoops) {
EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
}
TEST(Do, MatchesDoLoops) {
EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
}
TEST(Do, DoesNotMatchWhileLoops) {
EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
}
TEST(SwitchCase, MatchesCase) {
EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
}
TEST(SwitchCase, MatchesSwitch) {
EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
}
TEST(SwitchCase, MatchesEachCase) {
EXPECT_TRUE(notMatches("void x() { switch(42); }",
switchStmt(forEachSwitchCase(caseStmt()))));
EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
switchStmt(forEachSwitchCase(caseStmt()))));
EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
switchStmt(forEachSwitchCase(caseStmt()))));
EXPECT_TRUE(notMatches(
"void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
switchStmt(forEachSwitchCase(
caseStmt(hasCaseConstant(integerLiteral()))))));
EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
switchStmt(forEachSwitchCase(
caseStmt(hasCaseConstant(integerLiteral()))))));
EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
switchStmt(forEachSwitchCase(
caseStmt(hasCaseConstant(integerLiteral()))))));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void x() { switch (42) { case 1: case 2: case 3: default:; } }",
switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
new VerifyIdIsBoundTo<CaseStmt>("x", 3)));
}
TEST(ForEachConstructorInitializer, MatchesInitializers) {
EXPECT_TRUE(matches(
"struct X { X() : i(42), j(42) {} int i, j; };",
constructorDecl(forEachConstructorInitializer(ctorInitializer()))));
}
TEST(ExceptionHandling, SimpleCases) {
EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
throwExpr()));
EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
throwExpr()));
EXPECT_TRUE(matches("void foo() try { throw; } catch(...) { }",
catchStmt(isCatchAll())));
EXPECT_TRUE(notMatches("void foo() try { throw; } catch(int) { }",
catchStmt(isCatchAll())));
}
TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
EXPECT_TRUE(notMatches(
"void x() { if(true) {} }",
ifStmt(hasConditionVariableStatement(declStmt()))));
EXPECT_TRUE(notMatches(
"void x() { int x; if((x = 42)) {} }",
ifStmt(hasConditionVariableStatement(declStmt()))));
}
TEST(HasConditionVariableStatement, MatchesConditionVariables) {
EXPECT_TRUE(matches(
"void x() { if(int* a = 0) {} }",
ifStmt(hasConditionVariableStatement(declStmt()))));
}
TEST(ForEach, BindsOneNode) {
EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
}
TEST(ForEach, BindsMultipleNodes) {
EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
}
TEST(ForEach, BindsRecursiveCombinations) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class C { class D { int x; int y; }; class E { int y; int z; }; };",
recordDecl(hasName("C"),
forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
}
TEST(ForEachDescendant, BindsOneNode) {
EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
recordDecl(hasName("C"),
forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
}
TEST(ForEachDescendant, NestedForEachDescendant) {
DeclarationMatcher m = recordDecl(
isDefinition(), decl().bind("x"), hasName("C"));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { class B { class C {}; }; };",
recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
new VerifyIdIsBoundTo<Decl>("x", "C")));
// Check that a partial match of 'm' that binds 'x' in the
// first part of anyOf(m, anything()) will not overwrite the
// binding created by the earlier binding in the hasDescendant.
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { class B { class C {}; }; };",
recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
new VerifyIdIsBoundTo<Decl>("x", "C")));
}
TEST(ForEachDescendant, BindsMultipleNodes) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class C { class D { int x; int y; }; "
" class E { class F { int y; int z; }; }; };",
recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
}
TEST(ForEachDescendant, BindsRecursiveCombinations) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class C { class D { "
" class E { class F { class G { int y; int z; }; }; }; }; };",
recordDecl(hasName("C"), forEachDescendant(recordDecl(
forEachDescendant(fieldDecl().bind("f"))))),
new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
}
TEST(ForEachDescendant, BindsCombinations) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
"(true) {} }",
compoundStmt(forEachDescendant(ifStmt().bind("if")),
forEachDescendant(whileStmt().bind("while"))),
new VerifyIdIsBoundTo<IfStmt>("if", 6)));
}
TEST(Has, DoesNotDeleteBindings) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
new VerifyIdIsBoundTo<Decl>("x", 1)));
}
TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
// Those matchers cover all the cases where an inner matcher is called
// and there is not a 1:1 relationship between the match of the outer
// matcher and the match of the inner matcher.
// The pattern to look for is:
// ... return InnerMatcher.matches(...); ...
// In which case no special handling is needed.
//
// On the other hand, if there are multiple alternative matches
// (for example forEach*) or matches might be discarded (for example has*)
// the implementation must make sure that the discarded matches do not
// affect the bindings.
// When new such matchers are added, add a test here that:
// - matches a simple node, and binds it as the first thing in the matcher:
// recordDecl(decl().bind("x"), hasName("X")))
// - uses the matcher under test afterwards in a way that not the first
// alternative is matched; for anyOf, that means the first branch
// would need to return false; for hasAncestor, it means that not
// the direct parent matches the inner matcher.
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X { int y; };",
recordDecl(
recordDecl().bind("x"), hasName("::X"),
anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
anyOf(unless(anything()), anything())),
new VerifyIdIsBoundTo<CXXRecordDecl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"template<typename T1, typename T2> class X {}; X<float, int> x;",
classTemplateSpecializationDecl(
decl().bind("x"),
hasAnyTemplateArgument(refersToType(asString("int")))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X { void f(); void g(); };",
recordDecl(decl().bind("x"), hasMethod(hasName("g"))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X { X() : a(1), b(2) {} double a; int b; };",
recordDecl(decl().bind("x"),
has(constructorDecl(
hasAnyConstructorInitializer(forField(hasName("b")))))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void x(int, int) { x(0, 42); }",
callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
new VerifyIdIsBoundTo<Expr>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void x(int, int y) {}",
functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void x() { return; if (true) {} }",
functionDecl(decl().bind("x"),
has(compoundStmt(hasAnySubstatement(ifStmt())))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"namespace X { void b(int); void b(); }"
"using X::b;",
usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
functionDecl(parameterCountIs(1))))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A{}; class B{}; class C : B, A {};",
recordDecl(decl().bind("x"), isDerivedFrom("::A")),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A{}; typedef A B; typedef A C; typedef A D;"
"class E : A {};",
recordDecl(decl().bind("x"), isDerivedFrom("C")),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { class B { void f() {} }; };",
functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"template <typename T> struct A { struct B {"
" void f() { if(true) {} }"
"}; };"
"void t() { A<int>::B b; b.f(); }",
ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
new VerifyIdIsBoundTo<Stmt>("x", 2)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A {};",
recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { A() : s(), i(42) {} const char *s; int i; };",
constructorDecl(hasName("::A::A"), decl().bind("x"),
forEachConstructorInitializer(forField(hasName("i")))),
new VerifyIdIsBoundTo<Decl>("x", 1)));
}
TEST(ForEachDescendant, BindsCorrectNodes) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class C { void f(); int i; };",
recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class C { void f() {} int i; };",
recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
}
TEST(FindAll, BindsNodeOnMatch) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A {};",
recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
}
TEST(FindAll, BindsDescendantNodeOnMatch) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { int a; int b; };",
recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
}
TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { int a; int b; };",
recordDecl(hasName("::A"),
findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
fieldDecl().bind("v"))))),
new VerifyIdIsBoundTo<Decl>("v", 3)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { class B {}; class C {}; };",
recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
}
TEST(EachOf, TriggersForEachMatch) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { int a; int b; };",
recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
has(fieldDecl(hasName("b")).bind("v")))),
new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
}
TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { int a; int c; };",
recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
has(fieldDecl(hasName("b")).bind("v")))),
new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { int c; int b; };",
recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
has(fieldDecl(hasName("b")).bind("v")))),
new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
EXPECT_TRUE(notMatches(
"class A { int c; int d; };",
recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
has(fieldDecl(hasName("b")).bind("v"))))));
}
TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
// Make sure that we can both match the class by name (::X) and by the type
// the template was instantiated with (via a field).
EXPECT_TRUE(matches(
"template <typename T> class X {}; class A {}; X<A> x;",
recordDecl(hasName("::X"), isTemplateInstantiation())));
EXPECT_TRUE(matches(
"template <typename T> class X { T t; }; class A {}; X<A> x;",
recordDecl(isTemplateInstantiation(), hasDescendant(
fieldDecl(hasType(recordDecl(hasName("A"))))))));
}
TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
EXPECT_TRUE(matches(
"template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
isTemplateInstantiation())));
}
TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
EXPECT_TRUE(matches(
"template <typename T> class X { T t; }; class A {};"
"template class X<A>;",
recordDecl(isTemplateInstantiation(), hasDescendant(
fieldDecl(hasType(recordDecl(hasName("A"))))))));
}
TEST(IsTemplateInstantiation,
MatchesInstantiationOfPartiallySpecializedClassTemplate) {
EXPECT_TRUE(matches(
"template <typename T> class X {};"
"template <typename T> class X<T*> {}; class A {}; X<A*> x;",
recordDecl(hasName("::X"), isTemplateInstantiation())));
}
TEST(IsTemplateInstantiation,
MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
EXPECT_TRUE(matches(
"class A {};"
"class X {"
" template <typename U> class Y { U u; };"
" Y<A> y;"
"};",
recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
}
TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
// FIXME: Figure out whether this makes sense. It doesn't affect the
// normal use case as long as the uppermost instantiation always is marked
// as template instantiation, but it might be confusing as a predicate.
EXPECT_TRUE(matches(
"class A {};"
"template <typename T> class X {"
" template <typename U> class Y { U u; };"
" Y<T> y;"
"}; X<A> x;",
recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
}
TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
EXPECT_TRUE(notMatches(
"template <typename T> class X {}; class A {};"
"template <> class X<A> {}; X<A> x;",
recordDecl(hasName("::X"), isTemplateInstantiation())));
}
TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
EXPECT_TRUE(notMatches(
"class A {}; class Y { A a; };",
recordDecl(isTemplateInstantiation())));
}
TEST(IsInstantiated, MatchesInstantiation) {
EXPECT_TRUE(
matches("template<typename T> class A { T i; }; class Y { A<int> a; };",
recordDecl(isInstantiated())));
}
TEST(IsInstantiated, NotMatchesDefinition) {
EXPECT_TRUE(notMatches("template<typename T> class A { T i; };",
recordDecl(isInstantiated())));
}
TEST(IsInTemplateInstantiation, MatchesInstantiationStmt) {
EXPECT_TRUE(matches("template<typename T> struct A { A() { T i; } };"
"class Y { A<int> a; }; Y y;",
declStmt(isInTemplateInstantiation())));
}
TEST(IsInTemplateInstantiation, NotMatchesDefinitionStmt) {
EXPECT_TRUE(notMatches("template<typename T> struct A { void x() { T i; } };",
declStmt(isInTemplateInstantiation())));
}
TEST(IsInstantiated, MatchesFunctionInstantiation) {
EXPECT_TRUE(
matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
functionDecl(isInstantiated())));
}
TEST(IsInstantiated, NotMatchesFunctionDefinition) {
EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
varDecl(isInstantiated())));
}
TEST(IsInTemplateInstantiation, MatchesFunctionInstantiationStmt) {
EXPECT_TRUE(
matches("template<typename T> void A(T t) { T i; } void x() { A(0); }",
declStmt(isInTemplateInstantiation())));
}
TEST(IsInTemplateInstantiation, NotMatchesFunctionDefinitionStmt) {
EXPECT_TRUE(notMatches("template<typename T> void A(T t) { T i; }",
declStmt(isInTemplateInstantiation())));
}
TEST(IsInTemplateInstantiation, Sharing) {
auto Matcher = binaryOperator(unless(isInTemplateInstantiation()));
// FIXME: Node sharing is an implementation detail, exposing it is ugly
// and makes the matcher behave in non-obvious ways.
EXPECT_TRUE(notMatches(
"int j; template<typename T> void A(T t) { j += 42; } void x() { A(0); }",
Matcher));
EXPECT_TRUE(matches(
"int j; template<typename T> void A(T t) { j += t; } void x() { A(0); }",
Matcher));
}
TEST(IsExplicitTemplateSpecialization,
DoesNotMatchPrimaryTemplate) {
EXPECT_TRUE(notMatches(
"template <typename T> class X {};",
recordDecl(isExplicitTemplateSpecialization())));
EXPECT_TRUE(notMatches(
"template <typename T> void f(T t);",
functionDecl(isExplicitTemplateSpecialization())));
}
TEST(IsExplicitTemplateSpecialization,
DoesNotMatchExplicitTemplateInstantiations) {
EXPECT_TRUE(notMatches(
"template <typename T> class X {};"
"template class X<int>; extern template class X<long>;",
recordDecl(isExplicitTemplateSpecialization())));
EXPECT_TRUE(notMatches(
"template <typename T> void f(T t) {}"
"template void f(int t); extern template void f(long t);",
functionDecl(isExplicitTemplateSpecialization())));
}
TEST(IsExplicitTemplateSpecialization,
DoesNotMatchImplicitTemplateInstantiations) {
EXPECT_TRUE(notMatches(
"template <typename T> class X {}; X<int> x;",
recordDecl(isExplicitTemplateSpecialization())));
EXPECT_TRUE(notMatches(
"template <typename T> void f(T t); void g() { f(10); }",
functionDecl(isExplicitTemplateSpecialization())));
}
TEST(IsExplicitTemplateSpecialization,
MatchesExplicitTemplateSpecializations) {
EXPECT_TRUE(matches(
"template <typename T> class X {};"
"template<> class X<int> {};",
recordDecl(isExplicitTemplateSpecialization())));
EXPECT_TRUE(matches(
"template <typename T> void f(T t) {}"
"template<> void f(int t) {}",
functionDecl(isExplicitTemplateSpecialization())));
}
TEST(HasAncenstor, MatchesDeclarationAncestors) {
EXPECT_TRUE(matches(
"class A { class B { class C {}; }; };",
recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
}
TEST(HasAncenstor, FailsIfNoAncestorMatches) {
EXPECT_TRUE(notMatches(
"class A { class B { class C {}; }; };",
recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
}
TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
EXPECT_TRUE(matches(
"class A { class B { void f() { C c; } class C {}; }; };",
varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
hasAncestor(recordDecl(hasName("A"))))))));
}
TEST(HasAncenstor, MatchesStatementAncestors) {
EXPECT_TRUE(matches(
"void f() { if (true) { while (false) { 42; } } }",
integerLiteral(equals(42), hasAncestor(ifStmt()))));
}
TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
EXPECT_TRUE(matches(
"void f() { if (true) { int x = 42; } }",
integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
}
TEST(HasAncestor, BindsRecursiveCombinations) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class C { class D { class E { class F { int y; }; }; }; };",
fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
}
TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class C { class D { class E { class F { int y; }; }; }; };",
fieldDecl(hasAncestor(
decl(
hasDescendant(recordDecl(isDefinition(),
hasAncestor(recordDecl())))
).bind("d")
)),
new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
}
TEST(HasAncestor, MatchesClosestAncestor) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"template <typename T> struct C {"
" void f(int) {"
" struct I { void g(T) { int x; } } i; i.g(42);"
" }"
"};"
"template struct C<int>;",
varDecl(hasName("x"),
hasAncestor(functionDecl(hasParameter(
0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
}
TEST(HasAncestor, MatchesInTemplateInstantiations) {
EXPECT_TRUE(matches(
"template <typename T> struct A { struct B { struct C { T t; }; }; }; "
"A<int>::B::C a;",
fieldDecl(hasType(asString("int")),
hasAncestor(recordDecl(hasName("A"))))));
}
TEST(HasAncestor, MatchesInImplicitCode) {
EXPECT_TRUE(matches(
"struct X {}; struct A { A() {} X x; };",
constructorDecl(
hasAnyConstructorInitializer(withInitializer(expr(
hasAncestor(recordDecl(hasName("A")))))))));
}
TEST(HasParent, MatchesOnlyParent) {
EXPECT_TRUE(matches(
"void f() { if (true) { int x = 42; } }",
compoundStmt(hasParent(ifStmt()))));
EXPECT_TRUE(notMatches(
"void f() { for (;;) { int x = 42; } }",
compoundStmt(hasParent(ifStmt()))));
EXPECT_TRUE(notMatches(
"void f() { if (true) for (;;) { int x = 42; } }",
compoundStmt(hasParent(ifStmt()))));
}
TEST(HasAncestor, MatchesAllAncestors) {
EXPECT_TRUE(matches(
"template <typename T> struct C { static void f() { 42; } };"
"void t() { C<int>::f(); }",
integerLiteral(
equals(42),
allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
}
TEST(HasParent, MatchesAllParents) {
EXPECT_TRUE(matches(
"template <typename T> struct C { static void f() { 42; } };"
"void t() { C<int>::f(); }",
integerLiteral(
equals(42),
hasParent(compoundStmt(hasParent(functionDecl(
hasParent(recordDecl(isTemplateInstantiation())))))))));
EXPECT_TRUE(matches(
"template <typename T> struct C { static void f() { 42; } };"
"void t() { C<int>::f(); }",
integerLiteral(
equals(42),
hasParent(compoundStmt(hasParent(functionDecl(
hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
EXPECT_TRUE(matches(
"template <typename T> struct C { static void f() { 42; } };"
"void t() { C<int>::f(); }",
integerLiteral(equals(42),
hasParent(compoundStmt(allOf(
hasParent(functionDecl(
hasParent(recordDecl(isTemplateInstantiation())))),
hasParent(functionDecl(hasParent(recordDecl(
unless(isTemplateInstantiation())))))))))));
EXPECT_TRUE(
notMatches("template <typename T> struct C { static void f() {} };"
"void t() { C<int>::f(); }",
compoundStmt(hasParent(recordDecl()))));
}
TEST(HasParent, NoDuplicateParents) {
class HasDuplicateParents : public BoundNodesCallback {
public:
bool run(const BoundNodes *Nodes) override { return false; }
bool run(const BoundNodes *Nodes, ASTContext *Context) override {
const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
std::set<const void *> Parents;
for (const auto &Parent : Context->getParents(*Node)) {
if (!Parents.insert(Parent.getMemoizationData()).second) {
return true;
}
}
return false;
}
};
EXPECT_FALSE(matchAndVerifyResultTrue(
"template <typename T> int Foo() { return 1 + 2; }\n"
"int x = Foo<int>() + Foo<unsigned>();",
stmt().bind("node"), new HasDuplicateParents()));
}
TEST(TypeMatching, MatchesTypes) {
EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
}
TEST(TypeMatching, MatchesVoid) {
EXPECT_TRUE(
matches("struct S { void func(); };", methodDecl(returns(voidType()))));
}
TEST(TypeMatching, MatchesArrayTypes) {
EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
EXPECT_TRUE(matches("int a[42];", arrayType()));
EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
EXPECT_TRUE(notMatches("struct A {}; A a[7];",
arrayType(hasElementType(builtinType()))));
EXPECT_TRUE(matches(
"int const a[] = { 2, 3 };",
qualType(arrayType(hasElementType(builtinType())))));
EXPECT_TRUE(matches(
"int const a[] = { 2, 3 };",
qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
EXPECT_TRUE(matches(
"typedef const int T; T x[] = { 1, 2 };",
qualType(isConstQualified(), arrayType())));
EXPECT_TRUE(notMatches(
"int a[] = { 2, 3 };",
qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
EXPECT_TRUE(notMatches(
"int a[] = { 2, 3 };",
qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
EXPECT_TRUE(notMatches(
"int const a[] = { 2, 3 };",
qualType(arrayType(hasElementType(builtinType())),
unless(isConstQualified()))));
EXPECT_TRUE(matches("int a[2];",
constantArrayType(hasElementType(builtinType()))));
EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
}
TEST(TypeMatching, MatchesComplexTypes) {
EXPECT_TRUE(matches("_Complex float f;", complexType()));
EXPECT_TRUE(matches(
"_Complex float f;",
complexType(hasElementType(builtinType()))));
EXPECT_TRUE(notMatches(
"_Complex float f;",
complexType(hasElementType(isInteger()))));
}
TEST(TypeMatching, MatchesConstantArrayTypes) {
EXPECT_TRUE(matches("int a[2];", constantArrayType()));
EXPECT_TRUE(notMatches(
"void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
constantArrayType(hasElementType(builtinType()))));
EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
}
TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
EXPECT_TRUE(matches(
"template <typename T, int Size> class array { T data[Size]; };",
dependentSizedArrayType()));
EXPECT_TRUE(notMatches(
"int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
dependentSizedArrayType()));
}
TEST(TypeMatching, MatchesIncompleteArrayType) {
EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
incompleteArrayType()));
}
TEST(TypeMatching, MatchesVariableArrayType) {
EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
EXPECT_TRUE(matches(
"void f(int b) { int a[b]; }",
variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
varDecl(hasName("b")))))))));
}
TEST(TypeMatching, MatchesAtomicTypes) {
if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
llvm::Triple::Win32) {
// FIXME: Make this work for MSVC.
EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
EXPECT_TRUE(matches("_Atomic(int) i;",
atomicType(hasValueType(isInteger()))));
EXPECT_TRUE(notMatches("_Atomic(float) f;",
atomicType(hasValueType(isInteger()))));
}
}
TEST(TypeMatching, MatchesAutoTypes) {
EXPECT_TRUE(matches("auto i = 2;", autoType()));
EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
autoType()));
// FIXME: Matching against the type-as-written can't work here, because the
// type as written was not deduced.
//EXPECT_TRUE(matches("auto a = 1;",
// autoType(hasDeducedType(isInteger()))));
//EXPECT_TRUE(notMatches("auto b = 2.0;",
// autoType(hasDeducedType(isInteger()))));
}
TEST(TypeMatching, MatchesFunctionTypes) {
EXPECT_TRUE(matches("int (*f)(int);", functionType()));
EXPECT_TRUE(matches("void f(int i) {}", functionType()));
}
TEST(TypeMatching, MatchesParenType) {
EXPECT_TRUE(
matches("int (*array)[4];", varDecl(hasType(pointsTo(parenType())))));
EXPECT_TRUE(notMatches("int *array[4];", varDecl(hasType(parenType()))));
EXPECT_TRUE(matches(
"int (*ptr_to_func)(int);",
varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
EXPECT_TRUE(notMatches(
"int (*ptr_to_array)[4];",
varDecl(hasType(pointsTo(parenType(innerType(functionType())))))));
}
TEST(TypeMatching, PointerTypes) {
// FIXME: Reactive when these tests can be more specific (not matching
// implicit code on certain platforms), likely when we have hasDescendant for
// Types/TypeLocs.
//EXPECT_TRUE(matchAndVerifyResultTrue(
// "int* a;",
// pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
// new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
//EXPECT_TRUE(matchAndVerifyResultTrue(
// "int* a;",
// pointerTypeLoc().bind("loc"),
// new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
EXPECT_TRUE(matches(
"int** a;",
loc(pointerType(pointee(qualType())))));
EXPECT_TRUE(matches(
"int** a;",
loc(pointerType(pointee(pointerType())))));
EXPECT_TRUE(matches(
"int* b; int* * const a = &b;",
loc(qualType(isConstQualified(), pointerType()))));
std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(blockPointerType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
hasType(memberPointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(pointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(referenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(lValueReferenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(rValueReferenceType()))));
Fragment = "int *ptr;";
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(blockPointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(memberPointerType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
hasType(pointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
hasType(referenceType()))));
Fragment = "int a; int &ref = a;";
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(blockPointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(memberPointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(pointerType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
hasType(referenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
hasType(lValueReferenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(rValueReferenceType()))));
Fragment = "int &&ref = 2;";
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(blockPointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(memberPointerType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(pointerType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
hasType(referenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
hasType(lValueReferenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
hasType(rValueReferenceType()))));
}
TEST(TypeMatching, AutoRefTypes) {
std::string Fragment = "auto a = 1;"
"auto b = a;"
"auto &c = a;"
"auto &&d = c;"
"auto &&e = 2;";
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
hasType(referenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
hasType(referenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
hasType(referenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
hasType(lValueReferenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
hasType(rValueReferenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
hasType(referenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
hasType(lValueReferenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
hasType(rValueReferenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
hasType(referenceType()))));
EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
hasType(lValueReferenceType()))));
EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
hasType(rValueReferenceType()))));
}
TEST(TypeMatching, PointeeTypes) {
EXPECT_TRUE(matches("int b; int &a = b;",
referenceType(pointee(builtinType()))));
EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
EXPECT_TRUE(matches("int *a;",
loc(pointerType(pointee(builtinType())))));
EXPECT_TRUE(matches(
"int const *A;",
pointerType(pointee(isConstQualified(), builtinType()))));
EXPECT_TRUE(notMatches(
"int *A;",
pointerType(pointee(isConstQualified(), builtinType()))));
}
TEST(TypeMatching, MatchesPointersToConstTypes) {
EXPECT_TRUE(matches("int b; int * const a = &b;",
loc(pointerType())));
EXPECT_TRUE(matches("int b; int * const a = &b;",
loc(pointerType())));
EXPECT_TRUE(matches(
"int b; const int * a = &b;",
loc(pointerType(pointee(builtinType())))));
EXPECT_TRUE(matches(
"int b; const int * a = &b;",
pointerType(pointee(builtinType()))));
}
TEST(TypeMatching, MatchesTypedefTypes) {
EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
hasType(typedefType()))));
}
TEST(TypeMatching, MatchesTemplateSpecializationType) {
EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
templateSpecializationType()));
}
TEST(TypeMatching, MatchesRecordType) {
EXPECT_TRUE(matches("class C{}; C c;", recordType()));
EXPECT_TRUE(matches("struct S{}; S s;",
recordType(hasDeclaration(recordDecl(hasName("S"))))));
EXPECT_TRUE(notMatches("int i;",
recordType(hasDeclaration(recordDecl(hasName("S"))))));
}
TEST(TypeMatching, MatchesElaboratedType) {
EXPECT_TRUE(matches(
"namespace N {"
" namespace M {"
" class D {};"
" }"
"}"
"N::M::D d;", elaboratedType()));
EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
}
TEST(ElaboratedTypeNarrowing, hasQualifier) {
EXPECT_TRUE(matches(
"namespace N {"
" namespace M {"
" class D {};"
" }"
"}"
"N::M::D d;",
elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
EXPECT_TRUE(notMatches(
"namespace M {"
" class D {};"
"}"
"M::D d;",
elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
EXPECT_TRUE(notMatches(
"struct D {"
"} d;",
elaboratedType(hasQualifier(nestedNameSpecifier()))));
}
TEST(ElaboratedTypeNarrowing, namesType) {
EXPECT_TRUE(matches(
"namespace N {"
" namespace M {"
" class D {};"
" }"
"}"
"N::M::D d;",
elaboratedType(elaboratedType(namesType(recordType(
hasDeclaration(namedDecl(hasName("D")))))))));
EXPECT_TRUE(notMatches(
"namespace M {"
" class D {};"
"}"
"M::D d;",
elaboratedType(elaboratedType(namesType(typedefType())))));
}
TEST(NNS, MatchesNestedNameSpecifiers) {
EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
nestedNameSpecifier()));
EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
nestedNameSpecifier()));
EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
nestedNameSpecifier()));
EXPECT_TRUE(matches(
"struct A { static void f() {} }; void g() { A::f(); }",
nestedNameSpecifier()));
EXPECT_TRUE(notMatches(
"struct A { static void f() {} }; void g(A* a) { a->f(); }",
nestedNameSpecifier()));
}
TEST(NullStatement, SimpleCases) {
EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
}
TEST(NNS, MatchesTypes) {
NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
specifiesType(hasDeclaration(recordDecl(hasName("A")))));
EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
Matcher));
EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
}
TEST(NNS, MatchesNamespaceDecls) {
NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
specifiesNamespace(hasName("ns")));
EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
}
TEST(NNS, BindsNestedNameSpecifiers) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"namespace ns { struct E { struct B {}; }; } ns::E::B b;",
nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
}
TEST(NNS, BindsNestedNameSpecifierLocs) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"namespace ns { struct B {}; } ns::B b;",
loc(nestedNameSpecifier()).bind("loc"),
new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
}
TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
EXPECT_TRUE(matches(
"struct A { struct B { struct C {}; }; }; A::B::C c;",
nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
EXPECT_TRUE(matches(
"struct A { struct B { struct C {}; }; }; A::B::C c;",
nestedNameSpecifierLoc(hasPrefix(
specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
}
TEST(NNS, DescendantsOfNestedNameSpecifiers) {
std::string Fragment =
"namespace a { struct A { struct B { struct C {}; }; }; };"
"void f() { a::A::B::C c; }";
EXPECT_TRUE(matches(
Fragment,
nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
hasDescendant(nestedNameSpecifier(
specifiesNamespace(hasName("a")))))));
EXPECT_TRUE(notMatches(
Fragment,
nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
has(nestedNameSpecifier(
specifiesNamespace(hasName("a")))))));
EXPECT_TRUE(matches(
Fragment,
nestedNameSpecifier(specifiesType(asString("struct a::A")),
has(nestedNameSpecifier(
specifiesNamespace(hasName("a")))))));
// Not really useful because a NestedNameSpecifier can af at most one child,
// but to complete the interface.
EXPECT_TRUE(matchAndVerifyResultTrue(
Fragment,
nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
forEach(nestedNameSpecifier().bind("x"))),
new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
}
TEST(NNS, NestedNameSpecifiersAsDescendants) {
std::string Fragment =
"namespace a { struct A { struct B { struct C {}; }; }; };"
"void f() { a::A::B::C c; }";
EXPECT_TRUE(matches(
Fragment,
decl(hasDescendant(nestedNameSpecifier(specifiesType(
asString("struct a::A")))))));
EXPECT_TRUE(matchAndVerifyResultTrue(
Fragment,
functionDecl(hasName("f"),
forEachDescendant(nestedNameSpecifier().bind("x"))),
// Nested names: a, a::A and a::A::B.
new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
}
TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
std::string Fragment =
"namespace a { struct A { struct B { struct C {}; }; }; };"
"void f() { a::A::B::C c; }";
EXPECT_TRUE(matches(
Fragment,
nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
hasDescendant(loc(nestedNameSpecifier(
specifiesNamespace(hasName("a"))))))));
EXPECT_TRUE(notMatches(
Fragment,
nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
has(loc(nestedNameSpecifier(
specifiesNamespace(hasName("a"))))))));
EXPECT_TRUE(matches(
Fragment,
nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
has(loc(nestedNameSpecifier(
specifiesNamespace(hasName("a"))))))));
EXPECT_TRUE(matchAndVerifyResultTrue(
Fragment,
nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
forEach(nestedNameSpecifierLoc().bind("x"))),
new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
}
TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
std::string Fragment =
"namespace a { struct A { struct B { struct C {}; }; }; };"
"void f() { a::A::B::C c; }";
EXPECT_TRUE(matches(
Fragment,
decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
asString("struct a::A"))))))));
EXPECT_TRUE(matchAndVerifyResultTrue(
Fragment,
functionDecl(hasName("f"),
forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
// Nested names: a, a::A and a::A::B.
new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
}
template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
public:
VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
StringRef InnerId)
: Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
}
bool run(const BoundNodes *Nodes) override { return false; }
bool run(const BoundNodes *Nodes, ASTContext *Context) override {
const T *Node = Nodes->getNodeAs<T>(Id);
return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
nullptr;
}
private:
std::string Id;
internal::Matcher<T> InnerMatcher;
std::string InnerId;
};
TEST(MatchFinder, CanMatchDeclarationsRecursively) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
new VerifyMatchOnNode<clang::Decl>(
"X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
"Y")));
EXPECT_TRUE(matchAndVerifyResultFalse(
"class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
new VerifyMatchOnNode<clang::Decl>(
"X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
"Z")));
}
TEST(MatchFinder, CanMatchStatementsRecursively) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
new VerifyMatchOnNode<clang::Stmt>(
"if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
EXPECT_TRUE(matchAndVerifyResultFalse(
"void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
new VerifyMatchOnNode<clang::Stmt>(
"if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
}
TEST(MatchFinder, CanMatchSingleNodesRecursively) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
new VerifyMatchOnNode<clang::Decl>(
"X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
EXPECT_TRUE(matchAndVerifyResultFalse(
"class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
new VerifyMatchOnNode<clang::Decl>(
"X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
}
template <typename T>
class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
public:
bool run(const BoundNodes *Nodes) override { return false; }
bool run(const BoundNodes *Nodes, ASTContext *Context) override {
const T *Node = Nodes->getNodeAs<T>("");
return verify(*Nodes, *Context, Node);
}
bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
// Use the original typed pointer to verify we can pass pointers to subtypes
// to equalsNode.
const T *TypedNode = cast<T>(Node);
return selectFirst<T>(
"", match(stmt(hasParent(
stmt(has(stmt(equalsNode(TypedNode)))).bind(""))),
*Node, Context)) != nullptr;
}
bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
// Use the original typed pointer to verify we can pass pointers to subtypes
// to equalsNode.
const T *TypedNode = cast<T>(Node);
return selectFirst<T>(
"", match(decl(hasParent(
decl(has(decl(equalsNode(TypedNode)))).bind(""))),
*Node, Context)) != nullptr;
}
};
TEST(IsEqualTo, MatchesNodesByIdentity) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
new VerifyAncestorHasChildIsEqual<CXXRecordDecl>()));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() { if (true) if(true) {} }", ifStmt().bind(""),
new VerifyAncestorHasChildIsEqual<IfStmt>()));
}
TEST(MatchFinder, CheckProfiling) {
MatchFinder::MatchFinderOptions Options;
llvm::StringMap<llvm::TimeRecord> Records;
Options.CheckProfiling.emplace(Records);
MatchFinder Finder(std::move(Options));
struct NamedCallback : public MatchFinder::MatchCallback {
void run(const MatchFinder::MatchResult &Result) override {}
StringRef getID() const override { return "MyID"; }
} Callback;
Finder.addMatcher(decl(), &Callback);
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
EXPECT_EQ(1u, Records.size());
EXPECT_EQ("MyID", Records.begin()->getKey());
}
class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
public:
VerifyStartOfTranslationUnit() : Called(false) {}
void run(const MatchFinder::MatchResult &Result) override {
EXPECT_TRUE(Called);
}
void onStartOfTranslationUnit() override { Called = true; }
bool Called;
};
TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
MatchFinder Finder;
VerifyStartOfTranslationUnit VerifyCallback;
Finder.addMatcher(decl(), &VerifyCallback);
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
EXPECT_TRUE(VerifyCallback.Called);
VerifyCallback.Called = false;
std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
ASSERT_TRUE(AST.get());
Finder.matchAST(AST->getASTContext());
EXPECT_TRUE(VerifyCallback.Called);
}
class VerifyEndOfTranslationUnit : public MatchFinder::MatchCallback {
public:
VerifyEndOfTranslationUnit() : Called(false) {}
void run(const MatchFinder::MatchResult &Result) override {
EXPECT_FALSE(Called);
}
void onEndOfTranslationUnit() override { Called = true; }
bool Called;
};
TEST(MatchFinder, InterceptsEndOfTranslationUnit) {
MatchFinder Finder;
VerifyEndOfTranslationUnit VerifyCallback;
Finder.addMatcher(decl(), &VerifyCallback);
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
EXPECT_TRUE(VerifyCallback.Called);
VerifyCallback.Called = false;
std::unique_ptr<ASTUnit> AST(tooling::buildASTFromCode("int x;"));
ASSERT_TRUE(AST.get());
Finder.matchAST(AST->getASTContext());
EXPECT_TRUE(VerifyCallback.Called);
}
TEST(EqualsBoundNodeMatcher, QualType) {
EXPECT_TRUE(matches(
"int i = 1;", varDecl(hasType(qualType().bind("type")),
hasInitializer(ignoringParenImpCasts(
hasType(qualType(equalsBoundNode("type"))))))));
EXPECT_TRUE(notMatches("int i = 1.f;",
varDecl(hasType(qualType().bind("type")),
hasInitializer(ignoringParenImpCasts(hasType(
qualType(equalsBoundNode("type"))))))));
}
TEST(EqualsBoundNodeMatcher, NonMatchingTypes) {
EXPECT_TRUE(notMatches(
"int i = 1;", varDecl(namedDecl(hasName("i")).bind("name"),
hasInitializer(ignoringParenImpCasts(
hasType(qualType(equalsBoundNode("type"))))))));
}
TEST(EqualsBoundNodeMatcher, Stmt) {
EXPECT_TRUE(
matches("void f() { if(true) {} }",
stmt(allOf(ifStmt().bind("if"),
hasParent(stmt(has(stmt(equalsBoundNode("if")))))))));
EXPECT_TRUE(notMatches(
"void f() { if(true) { if (true) {} } }",
stmt(allOf(ifStmt().bind("if"), has(stmt(equalsBoundNode("if")))))));
}
TEST(EqualsBoundNodeMatcher, Decl) {
EXPECT_TRUE(matches(
"class X { class Y {}; };",
decl(allOf(recordDecl(hasName("::X::Y")).bind("record"),
hasParent(decl(has(decl(equalsBoundNode("record")))))))));
EXPECT_TRUE(notMatches("class X { class Y {}; };",
decl(allOf(recordDecl(hasName("::X")).bind("record"),
has(decl(equalsBoundNode("record")))))));
}
TEST(EqualsBoundNodeMatcher, Type) {
EXPECT_TRUE(matches(
"class X { int a; int b; };",
recordDecl(
has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
EXPECT_TRUE(notMatches(
"class X { int a; double b; };",
recordDecl(
has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))));
}
TEST(EqualsBoundNodeMatcher, UsingForEachDescendant) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"int f() {"
" if (1) {"
" int i = 9;"
" }"
" int j = 10;"
" {"
" float k = 9.0;"
" }"
" return 0;"
"}",
// Look for variable declarations within functions whose type is the same
// as the function return type.
functionDecl(returns(qualType().bind("type")),
forEachDescendant(varDecl(hasType(
qualType(equalsBoundNode("type")))).bind("decl"))),
// Only i and j should match, not k.
new VerifyIdIsBoundTo<VarDecl>("decl", 2)));
}
TEST(EqualsBoundNodeMatcher, FiltersMatchedCombinations) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() {"
" int x;"
" double d;"
" x = d + x - d + x;"
"}",
functionDecl(
hasName("f"), forEachDescendant(varDecl().bind("d")),
forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))),
new VerifyIdIsBoundTo<VarDecl>("d", 5)));
}
TEST(EqualsBoundNodeMatcher, UnlessDescendantsOfAncestorsMatch) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"struct StringRef { int size() const; const char* data() const; };"
"void f(StringRef v) {"
" v.data();"
"}",
memberCallExpr(
callee(methodDecl(hasName("data"))),
on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
.bind("var")))),
unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
.bind("data"),
new VerifyIdIsBoundTo<Expr>("data", 1)));
EXPECT_FALSE(matches(
"struct StringRef { int size() const; const char* data() const; };"
"void f(StringRef v) {"
" v.data();"
" v.size();"
"}",
memberCallExpr(
callee(methodDecl(hasName("data"))),
on(declRefExpr(to(varDecl(hasType(recordDecl(hasName("StringRef"))))
.bind("var")))),
unless(hasAncestor(stmt(hasDescendant(memberCallExpr(
callee(methodDecl(anyOf(hasName("size"), hasName("length")))),
on(declRefExpr(to(varDecl(equalsBoundNode("var")))))))))))
.bind("data")));
}
TEST(TypeDefDeclMatcher, Match) {
EXPECT_TRUE(matches("typedef int typedefDeclTest;",
typedefDecl(hasName("typedefDeclTest"))));
}
// FIXME: Figure out how to specify paths so the following tests pass on Windows.
#ifndef LLVM_ON_WIN32
TEST(Matcher, IsExpansionInMainFileMatcher) {
EXPECT_TRUE(matches("class X {};",
recordDecl(hasName("X"), isExpansionInMainFile())));
EXPECT_TRUE(notMatches("", recordDecl(isExpansionInMainFile())));
FileContentMappings M;
M.push_back(std::make_pair("/other", "class X {};"));
EXPECT_TRUE(matchesConditionally("#include <other>\n",
recordDecl(isExpansionInMainFile()), false,
"-isystem/", M));
}
TEST(Matcher, IsExpansionInSystemHeader) {
FileContentMappings M;
M.push_back(std::make_pair("/other", "class X {};"));
EXPECT_TRUE(matchesConditionally(
"#include \"other\"\n", recordDecl(isExpansionInSystemHeader()), true,
"-isystem/", M));
EXPECT_TRUE(matchesConditionally("#include \"other\"\n",
recordDecl(isExpansionInSystemHeader()),
false, "-I/", M));
EXPECT_TRUE(notMatches("class X {};",
recordDecl(isExpansionInSystemHeader())));
EXPECT_TRUE(notMatches("", recordDecl(isExpansionInSystemHeader())));
}
TEST(Matcher, IsExpansionInFileMatching) {
FileContentMappings M;
M.push_back(std::make_pair("/foo", "class A {};"));
M.push_back(std::make_pair("/bar", "class B {};"));
EXPECT_TRUE(matchesConditionally(
"#include <foo>\n"
"#include <bar>\n"
"class X {};",
recordDecl(isExpansionInFileMatching("b.*"), hasName("B")), true,
"-isystem/", M));
EXPECT_TRUE(matchesConditionally(
"#include <foo>\n"
"#include <bar>\n"
"class X {};",
recordDecl(isExpansionInFileMatching("f.*"), hasName("X")), false,
"-isystem/", M));
}
#endif // LLVM_ON_WIN32
TEST(ObjCMessageExprMatcher, SimpleExprs) {
// don't find ObjCMessageExpr where none are present
EXPECT_TRUE(notMatchesObjC("", objcMessageExpr(anything())));
std::string Objc1String =
"@interface Str "
" - (Str *)uppercaseString:(Str *)str;"
"@end "
"@interface foo "
"- (void)meth:(Str *)text;"
"@end "
" "
"@implementation foo "
"- (void) meth:(Str *)text { "
" [self contents];"
" Str *up = [text uppercaseString];"
"} "
"@end ";
EXPECT_TRUE(matchesObjC(
Objc1String,
objcMessageExpr(anything())));
EXPECT_TRUE(matchesObjC(
Objc1String,
objcMessageExpr(hasSelector("contents"))));
EXPECT_TRUE(matchesObjC(
Objc1String,
objcMessageExpr(matchesSelector("cont*"))));
EXPECT_FALSE(matchesObjC(
Objc1String,
objcMessageExpr(matchesSelector("?cont*"))));
EXPECT_TRUE(notMatchesObjC(
Objc1String,
objcMessageExpr(hasSelector("contents"), hasNullSelector())));
EXPECT_TRUE(matchesObjC(
Objc1String,
objcMessageExpr(hasSelector("contents"), hasUnarySelector())));
EXPECT_TRUE(matchesObjC(
Objc1String,
objcMessageExpr(matchesSelector("uppercase*"),
argumentCountIs(0)
)));
}
} // end namespace ast_matchers
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers/ASTMatchersTest.h
|
//===- unittest/Tooling/ASTMatchersTest.h - Matcher tests helpers ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_UNITTESTS_ASTMATCHERS_ASTMATCHERSTEST_H
#define LLVM_CLANG_UNITTESTS_ASTMATCHERS_ASTMATCHERSTEST_H
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
namespace clang {
namespace ast_matchers {
using clang::tooling::buildASTFromCodeWithArgs;
using clang::tooling::newFrontendActionFactory;
using clang::tooling::runToolOnCodeWithArgs;
using clang::tooling::FrontendActionFactory;
using clang::tooling::FileContentMappings;
class BoundNodesCallback {
public:
virtual ~BoundNodesCallback() {}
virtual bool run(const BoundNodes *BoundNodes) = 0;
virtual bool run(const BoundNodes *BoundNodes, ASTContext *Context) = 0;
virtual void onEndOfTranslationUnit() {}
};
// If 'FindResultVerifier' is not NULL, sets *Verified to the result of
// running 'FindResultVerifier' with the bound nodes as argument.
// If 'FindResultVerifier' is NULL, sets *Verified to true when Run is called.
class VerifyMatch : public MatchFinder::MatchCallback {
public:
VerifyMatch(BoundNodesCallback *FindResultVerifier, bool *Verified)
: Verified(Verified), FindResultReviewer(FindResultVerifier) {}
void run(const MatchFinder::MatchResult &Result) override {
if (FindResultReviewer != nullptr) {
*Verified |= FindResultReviewer->run(&Result.Nodes, Result.Context);
} else {
*Verified = true;
}
}
void onEndOfTranslationUnit() override {
if (FindResultReviewer)
FindResultReviewer->onEndOfTranslationUnit();
}
private:
bool *const Verified;
BoundNodesCallback *const FindResultReviewer;
};
template <typename T>
testing::AssertionResult matchesConditionally(
const std::string &Code, const T &AMatcher, bool ExpectMatch,
llvm::StringRef CompileArg,
const FileContentMappings &VirtualMappedFiles = FileContentMappings(),
const std::string &Filename = "input.cc") {
bool Found = false, DynamicFound = false;
MatchFinder Finder;
VerifyMatch VerifyFound(nullptr, &Found);
Finder.addMatcher(AMatcher, &VerifyFound);
VerifyMatch VerifyDynamicFound(nullptr, &DynamicFound);
if (!Finder.addDynamicMatcher(AMatcher, &VerifyDynamicFound))
return testing::AssertionFailure() << "Could not add dynamic matcher";
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
// Some tests use typeof, which is a gnu extension.
std::vector<std::string> Args;
Args.push_back(CompileArg);
// Some tests need rtti/exceptions on
Args.push_back("-frtti");
Args.push_back("-fexceptions");
if (!runToolOnCodeWithArgs(Factory->create(), Code, Args, Filename,
std::make_shared<PCHContainerOperations>(),
VirtualMappedFiles)) {
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
}
if (Found != DynamicFound) {
return testing::AssertionFailure() << "Dynamic match result ("
<< DynamicFound
<< ") does not match static result ("
<< Found << ")";
}
if (!Found && ExpectMatch) {
return testing::AssertionFailure()
<< "Could not find match in \"" << Code << "\"";
} else if (Found && !ExpectMatch) {
return testing::AssertionFailure()
<< "Found unexpected match in \"" << Code << "\"";
}
return testing::AssertionSuccess();
}
template <typename T>
testing::AssertionResult matches(const std::string &Code, const T &AMatcher) {
return matchesConditionally(Code, AMatcher, true, "-std=c++11");
}
template <typename T>
testing::AssertionResult notMatches(const std::string &Code,
const T &AMatcher) {
return matchesConditionally(Code, AMatcher, false, "-std=c++11");
}
template <typename T>
testing::AssertionResult matchesObjC(const std::string &Code,
const T &AMatcher) {
return matchesConditionally(
Code, AMatcher, true,
"", FileContentMappings(), "input.m");
}
template <typename T>
testing::AssertionResult notMatchesObjC(const std::string &Code,
const T &AMatcher) {
return matchesConditionally(
Code, AMatcher, false,
"", FileContentMappings(), "input.m");
}
// Function based on matchesConditionally with "-x cuda" argument added and
// small CUDA header prepended to the code string.
template <typename T>
testing::AssertionResult matchesConditionallyWithCuda(
const std::string &Code, const T &AMatcher, bool ExpectMatch,
llvm::StringRef CompileArg) {
const std::string CudaHeader =
"typedef unsigned int size_t;\n"
"#define __constant__ __attribute__((constant))\n"
"#define __device__ __attribute__((device))\n"
"#define __global__ __attribute__((global))\n"
"#define __host__ __attribute__((host))\n"
"#define __shared__ __attribute__((shared))\n"
"struct dim3 {"
" unsigned x, y, z;"
" __host__ __device__ dim3(unsigned x, unsigned y = 1, unsigned z = 1)"
" : x(x), y(y), z(z) {}"
"};"
"typedef struct cudaStream *cudaStream_t;"
"int cudaConfigureCall(dim3 gridSize, dim3 blockSize,"
" size_t sharedSize = 0,"
" cudaStream_t stream = 0);";
bool Found = false, DynamicFound = false;
MatchFinder Finder;
VerifyMatch VerifyFound(nullptr, &Found);
Finder.addMatcher(AMatcher, &VerifyFound);
VerifyMatch VerifyDynamicFound(nullptr, &DynamicFound);
if (!Finder.addDynamicMatcher(AMatcher, &VerifyDynamicFound))
return testing::AssertionFailure() << "Could not add dynamic matcher";
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
// Some tests use typeof, which is a gnu extension.
std::vector<std::string> Args;
Args.push_back("-xcuda");
Args.push_back("-fno-ms-extensions");
Args.push_back("--cuda-host-only");
Args.push_back(CompileArg);
if (!runToolOnCodeWithArgs(Factory->create(),
CudaHeader + Code, Args)) {
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
}
if (Found != DynamicFound) {
return testing::AssertionFailure() << "Dynamic match result ("
<< DynamicFound
<< ") does not match static result ("
<< Found << ")";
}
if (!Found && ExpectMatch) {
return testing::AssertionFailure()
<< "Could not find match in \"" << Code << "\"";
} else if (Found && !ExpectMatch) {
return testing::AssertionFailure()
<< "Found unexpected match in \"" << Code << "\"";
}
return testing::AssertionSuccess();
}
template <typename T>
testing::AssertionResult matchesWithCuda(const std::string &Code,
const T &AMatcher) {
return matchesConditionallyWithCuda(Code, AMatcher, true, "-std=c++11");
}
template <typename T>
testing::AssertionResult notMatchesWithCuda(const std::string &Code,
const T &AMatcher) {
return matchesConditionallyWithCuda(Code, AMatcher, false, "-std=c++11");
}
template <typename T>
testing::AssertionResult
matchAndVerifyResultConditionally(const std::string &Code, const T &AMatcher,
BoundNodesCallback *FindResultVerifier,
bool ExpectResult) {
std::unique_ptr<BoundNodesCallback> ScopedVerifier(FindResultVerifier);
bool VerifiedResult = false;
MatchFinder Finder;
VerifyMatch VerifyVerifiedResult(FindResultVerifier, &VerifiedResult);
Finder.addMatcher(AMatcher, &VerifyVerifiedResult);
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Finder));
// Some tests use typeof, which is a gnu extension.
std::vector<std::string> Args(1, "-std=gnu++98");
if (!runToolOnCodeWithArgs(Factory->create(), Code, Args)) {
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
}
if (!VerifiedResult && ExpectResult) {
return testing::AssertionFailure()
<< "Could not verify result in \"" << Code << "\"";
} else if (VerifiedResult && !ExpectResult) {
return testing::AssertionFailure()
<< "Verified unexpected result in \"" << Code << "\"";
}
VerifiedResult = false;
std::unique_ptr<ASTUnit> AST(buildASTFromCodeWithArgs(Code, Args));
if (!AST.get())
return testing::AssertionFailure() << "Parsing error in \"" << Code
<< "\" while building AST";
Finder.matchAST(AST->getASTContext());
if (!VerifiedResult && ExpectResult) {
return testing::AssertionFailure()
<< "Could not verify result in \"" << Code << "\" with AST";
} else if (VerifiedResult && !ExpectResult) {
return testing::AssertionFailure()
<< "Verified unexpected result in \"" << Code << "\" with AST";
}
return testing::AssertionSuccess();
}
// FIXME: Find better names for these functions (or document what they
// do more precisely).
template <typename T>
testing::AssertionResult
matchAndVerifyResultTrue(const std::string &Code, const T &AMatcher,
BoundNodesCallback *FindResultVerifier) {
return matchAndVerifyResultConditionally(
Code, AMatcher, FindResultVerifier, true);
}
template <typename T>
testing::AssertionResult
matchAndVerifyResultFalse(const std::string &Code, const T &AMatcher,
BoundNodesCallback *FindResultVerifier) {
return matchAndVerifyResultConditionally(
Code, AMatcher, FindResultVerifier, false);
}
} // end namespace ast_matchers
} // end namespace clang
#endif // LLVM_CLANG_UNITTESTS_AST_MATCHERS_AST_MATCHERS_TEST_H
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers/CMakeLists.txt
|
set(LLVM_LINK_COMPONENTS
Support
)
add_clang_unittest(ASTMatchersTests
ASTMatchersTest.cpp)
target_link_libraries(ASTMatchersTests
clangAST
clangASTMatchers
clangBasic
clangFrontend
clangTooling
)
add_subdirectory(Dynamic)
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers
|
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
|
//===- unittest/ASTMatchers/Dynamic/ParserTest.cpp - Parser unit tests -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===-------------------------------------------------------------------===//
#include "../ASTMatchersTest.h"
#include "clang/ASTMatchers/Dynamic/Parser.h"
#include "clang/ASTMatchers/Dynamic/Registry.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringMap.h"
#include "gtest/gtest.h"
#include <string>
#include <vector>
namespace clang {
namespace ast_matchers {
namespace dynamic {
namespace {
class MockSema : public Parser::Sema {
public:
~MockSema() override {}
uint64_t expectMatcher(StringRef MatcherName) {
// Optimizations on the matcher framework make simple matchers like
// 'stmt()' to be all the same matcher.
// Use a more complex expression to prevent that.
ast_matchers::internal::Matcher<Stmt> M = stmt(stmt(), stmt());
ExpectedMatchers.insert(std::make_pair(MatcherName, M));
return M.getID().second;
}
void parse(StringRef Code) {
Diagnostics Error;
VariantValue Value;
Parser::parseExpression(Code, this, &Value, &Error);
Values.push_back(Value);
Errors.push_back(Error.toStringFull());
}
llvm::Optional<MatcherCtor>
lookupMatcherCtor(StringRef MatcherName) override {
const ExpectedMatchersTy::value_type *Matcher =
&*ExpectedMatchers.find(MatcherName);
return reinterpret_cast<MatcherCtor>(Matcher);
}
VariantMatcher actOnMatcherExpression(MatcherCtor Ctor,
const SourceRange &NameRange,
StringRef BindID,
ArrayRef<ParserValue> Args,
Diagnostics *Error) override {
const ExpectedMatchersTy::value_type *Matcher =
reinterpret_cast<const ExpectedMatchersTy::value_type *>(Ctor);
MatcherInfo ToStore = { Matcher->first, NameRange, Args, BindID };
Matchers.push_back(ToStore);
return VariantMatcher::SingleMatcher(Matcher->second);
}
struct MatcherInfo {
StringRef MatcherName;
SourceRange NameRange;
std::vector<ParserValue> Args;
std::string BoundID;
};
std::vector<std::string> Errors;
std::vector<VariantValue> Values;
std::vector<MatcherInfo> Matchers;
typedef std::map<std::string, ast_matchers::internal::Matcher<Stmt> >
ExpectedMatchersTy;
ExpectedMatchersTy ExpectedMatchers;
};
TEST(ParserTest, ParseUnsigned) {
MockSema Sema;
Sema.parse("0");
Sema.parse("123");
Sema.parse("0x1f");
Sema.parse("12345678901");
Sema.parse("1a1");
EXPECT_EQ(5U, Sema.Values.size());
EXPECT_EQ(0U, Sema.Values[0].getUnsigned());
EXPECT_EQ(123U, Sema.Values[1].getUnsigned());
EXPECT_EQ(31U, Sema.Values[2].getUnsigned());
EXPECT_EQ("1:1: Error parsing unsigned token: <12345678901>", Sema.Errors[3]);
EXPECT_EQ("1:1: Error parsing unsigned token: <1a1>", Sema.Errors[4]);
}
TEST(ParserTest, ParseString) {
MockSema Sema;
Sema.parse("\"Foo\"");
Sema.parse("\"\"");
Sema.parse("\"Baz");
EXPECT_EQ(3ULL, Sema.Values.size());
EXPECT_EQ("Foo", Sema.Values[0].getString());
EXPECT_EQ("", Sema.Values[1].getString());
EXPECT_EQ("1:1: Error parsing string token: <\"Baz>", Sema.Errors[2]);
}
bool matchesRange(const SourceRange &Range, unsigned StartLine,
unsigned EndLine, unsigned StartColumn, unsigned EndColumn) {
EXPECT_EQ(StartLine, Range.Start.Line);
EXPECT_EQ(EndLine, Range.End.Line);
EXPECT_EQ(StartColumn, Range.Start.Column);
EXPECT_EQ(EndColumn, Range.End.Column);
return Range.Start.Line == StartLine && Range.End.Line == EndLine &&
Range.Start.Column == StartColumn && Range.End.Column == EndColumn;
}
llvm::Optional<DynTypedMatcher> getSingleMatcher(const VariantValue &Value) {
llvm::Optional<DynTypedMatcher> Result =
Value.getMatcher().getSingleMatcher();
EXPECT_TRUE(Result.hasValue());
return Result;
}
TEST(ParserTest, ParseMatcher) {
MockSema Sema;
const uint64_t ExpectedFoo = Sema.expectMatcher("Foo");
const uint64_t ExpectedBar = Sema.expectMatcher("Bar");
const uint64_t ExpectedBaz = Sema.expectMatcher("Baz");
Sema.parse(" Foo ( Bar ( 17), Baz( \n \"B A,Z\") ) .bind( \"Yo!\") ");
for (size_t i = 0, e = Sema.Errors.size(); i != e; ++i) {
EXPECT_EQ("", Sema.Errors[i]);
}
EXPECT_NE(ExpectedFoo, ExpectedBar);
EXPECT_NE(ExpectedFoo, ExpectedBaz);
EXPECT_NE(ExpectedBar, ExpectedBaz);
EXPECT_EQ(1ULL, Sema.Values.size());
EXPECT_EQ(ExpectedFoo, getSingleMatcher(Sema.Values[0])->getID().second);
EXPECT_EQ(3ULL, Sema.Matchers.size());
const MockSema::MatcherInfo Bar = Sema.Matchers[0];
EXPECT_EQ("Bar", Bar.MatcherName);
EXPECT_TRUE(matchesRange(Bar.NameRange, 1, 1, 8, 17));
EXPECT_EQ(1ULL, Bar.Args.size());
EXPECT_EQ(17U, Bar.Args[0].Value.getUnsigned());
const MockSema::MatcherInfo Baz = Sema.Matchers[1];
EXPECT_EQ("Baz", Baz.MatcherName);
EXPECT_TRUE(matchesRange(Baz.NameRange, 1, 2, 19, 10));
EXPECT_EQ(1ULL, Baz.Args.size());
EXPECT_EQ("B A,Z", Baz.Args[0].Value.getString());
const MockSema::MatcherInfo Foo = Sema.Matchers[2];
EXPECT_EQ("Foo", Foo.MatcherName);
EXPECT_TRUE(matchesRange(Foo.NameRange, 1, 2, 2, 12));
EXPECT_EQ(2ULL, Foo.Args.size());
EXPECT_EQ(ExpectedBar, getSingleMatcher(Foo.Args[0].Value)->getID().second);
EXPECT_EQ(ExpectedBaz, getSingleMatcher(Foo.Args[1].Value)->getID().second);
EXPECT_EQ("Yo!", Foo.BoundID);
}
using ast_matchers::internal::Matcher;
Parser::NamedValueMap getTestNamedValues() {
Parser::NamedValueMap Values;
Values["nameX"] = llvm::StringRef("x");
Values["hasParamA"] =
VariantMatcher::SingleMatcher(hasParameter(0, hasName("a")));
return Values;
}
TEST(ParserTest, FullParserTest) {
Diagnostics Error;
llvm::Optional<DynTypedMatcher> VarDecl(Parser::parseMatcherExpression(
"varDecl(hasInitializer(binaryOperator(hasLHS(integerLiteral()),"
" hasOperatorName(\"+\"))))",
&Error));
EXPECT_EQ("", Error.toStringFull());
Matcher<Decl> M = VarDecl->unconditionalConvertTo<Decl>();
EXPECT_TRUE(matches("int x = 1 + false;", M));
EXPECT_FALSE(matches("int x = true + 1;", M));
EXPECT_FALSE(matches("int x = 1 - false;", M));
EXPECT_FALSE(matches("int x = true - 1;", M));
llvm::Optional<DynTypedMatcher> HasParameter(Parser::parseMatcherExpression(
"functionDecl(hasParameter(1, hasName(\"x\")))", &Error));
EXPECT_EQ("", Error.toStringFull());
M = HasParameter->unconditionalConvertTo<Decl>();
EXPECT_TRUE(matches("void f(int a, int x);", M));
EXPECT_FALSE(matches("void f(int x, int a);", M));
// Test named values.
auto NamedValues = getTestNamedValues();
llvm::Optional<DynTypedMatcher> HasParameterWithNamedValues(
Parser::parseMatcherExpression(
"functionDecl(hasParamA, hasParameter(1, hasName(nameX)))",
nullptr, &NamedValues, &Error));
EXPECT_EQ("", Error.toStringFull());
M = HasParameterWithNamedValues->unconditionalConvertTo<Decl>();
EXPECT_TRUE(matches("void f(int a, int x);", M));
EXPECT_FALSE(matches("void f(int x, int a);", M));
EXPECT_TRUE(!Parser::parseMatcherExpression(
"hasInitializer(\n binaryOperator(hasLHS(\"A\")))",
&Error).hasValue());
EXPECT_EQ("1:1: Error parsing argument 1 for matcher hasInitializer.\n"
"2:5: Error parsing argument 1 for matcher binaryOperator.\n"
"2:20: Error building matcher hasLHS.\n"
"2:27: Incorrect type for arg 1. "
"(Expected = Matcher<Expr>) != (Actual = String)",
Error.toStringFull());
}
std::string ParseWithError(StringRef Code) {
Diagnostics Error;
VariantValue Value;
Parser::parseExpression(Code, &Value, &Error);
return Error.toStringFull();
}
std::string ParseMatcherWithError(StringRef Code) {
Diagnostics Error;
Parser::parseMatcherExpression(Code, &Error);
return Error.toStringFull();
}
TEST(ParserTest, Errors) {
EXPECT_EQ(
"1:5: Error parsing matcher. Found token <123> while looking for '('.",
ParseWithError("Foo 123"));
EXPECT_EQ(
"1:1: Matcher not found: Foo\n"
"1:9: Error parsing matcher. Found token <123> while looking for ','.",
ParseWithError("Foo(\"A\" 123)"));
EXPECT_EQ(
"1:1: Error parsing argument 1 for matcher stmt.\n"
"1:6: Value not found: someValue",
ParseWithError("stmt(someValue)"));
EXPECT_EQ(
"1:1: Matcher not found: Foo\n"
"1:4: Error parsing matcher. Found end-of-code while looking for ')'.",
ParseWithError("Foo("));
EXPECT_EQ("1:1: End of code found while looking for token.",
ParseWithError(""));
EXPECT_EQ("Input value is not a matcher expression.",
ParseMatcherWithError("\"A\""));
EXPECT_EQ("1:1: Matcher not found: Foo\n"
"1:1: Error parsing argument 1 for matcher Foo.\n"
"1:5: Invalid token <(> found when looking for a value.",
ParseWithError("Foo(("));
EXPECT_EQ("1:7: Expected end of code.", ParseWithError("expr()a"));
EXPECT_EQ("1:11: Malformed bind() expression.",
ParseWithError("isArrow().biind"));
EXPECT_EQ("1:15: Malformed bind() expression.",
ParseWithError("isArrow().bind"));
EXPECT_EQ("1:16: Malformed bind() expression.",
ParseWithError("isArrow().bind(foo"));
EXPECT_EQ("1:21: Malformed bind() expression.",
ParseWithError("isArrow().bind(\"foo\""));
EXPECT_EQ("1:1: Error building matcher isArrow.\n"
"1:1: Matcher does not support binding.",
ParseWithError("isArrow().bind(\"foo\")"));
EXPECT_EQ("Input value has unresolved overloaded type: "
"Matcher<DoStmt|ForStmt|WhileStmt|CXXForRangeStmt>",
ParseMatcherWithError("hasBody(stmt())"));
}
TEST(ParserTest, OverloadErrors) {
EXPECT_EQ("1:1: Error building matcher callee.\n"
"1:8: Candidate 1: Incorrect type for arg 1. "
"(Expected = Matcher<Stmt>) != (Actual = String)\n"
"1:8: Candidate 2: Incorrect type for arg 1. "
"(Expected = Matcher<Decl>) != (Actual = String)",
ParseWithError("callee(\"A\")"));
}
TEST(ParserTest, CompletionRegistry) {
std::vector<MatcherCompletion> Comps =
Parser::completeExpression("while", 5);
ASSERT_EQ(1u, Comps.size());
EXPECT_EQ("Stmt(", Comps[0].TypedText);
EXPECT_EQ("Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)",
Comps[0].MatcherDecl);
Comps = Parser::completeExpression("whileStmt().", 12);
ASSERT_EQ(1u, Comps.size());
EXPECT_EQ("bind(\"", Comps[0].TypedText);
EXPECT_EQ("bind", Comps[0].MatcherDecl);
}
TEST(ParserTest, CompletionNamedValues) {
// Can complete non-matcher types.
auto NamedValues = getTestNamedValues();
StringRef Code = "functionDecl(hasName(";
std::vector<MatcherCompletion> Comps =
Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
ASSERT_EQ(1u, Comps.size());
EXPECT_EQ("nameX", Comps[0].TypedText);
EXPECT_EQ("String nameX", Comps[0].MatcherDecl);
// Can complete if there are names in the expression.
Code = "methodDecl(hasName(nameX), ";
Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
EXPECT_LT(0u, Comps.size());
// Can complete names and registry together.
Code = "methodDecl(hasP";
Comps = Parser::completeExpression(Code, Code.size(), nullptr, &NamedValues);
ASSERT_EQ(3u, Comps.size());
EXPECT_EQ("aramA", Comps[0].TypedText);
EXPECT_EQ("Matcher<FunctionDecl> hasParamA", Comps[0].MatcherDecl);
EXPECT_EQ("arameter(", Comps[1].TypedText);
EXPECT_EQ(
"Matcher<FunctionDecl> hasParameter(unsigned, Matcher<ParmVarDecl>)",
Comps[1].MatcherDecl);
EXPECT_EQ("arent(", Comps[2].TypedText);
EXPECT_EQ("Matcher<Decl> hasParent(Matcher<Decl|Stmt>)",
Comps[2].MatcherDecl);
}
} // end anonymous namespace
} // end namespace dynamic
} // end namespace ast_matchers
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers
|
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers/Dynamic/CMakeLists.txt
|
set(LLVM_LINK_COMPONENTS
Support
)
add_clang_unittest(DynamicASTMatchersTests
VariantValueTest.cpp
ParserTest.cpp
RegistryTest.cpp)
target_link_libraries(DynamicASTMatchersTests
clangAST
clangASTMatchers
clangBasic
clangDynamicASTMatchers
clangFrontend
clangTooling
)
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers
|
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers/Dynamic/VariantValueTest.cpp
|
//===- unittest/ASTMatchers/Dynamic/VariantValueTest.cpp - VariantValue unit tests -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===-----------------------------------------------------------------------------===//
#include "../ASTMatchersTest.h"
#include "clang/ASTMatchers/Dynamic/VariantValue.h"
#include "gtest/gtest.h"
namespace clang {
namespace ast_matchers {
namespace dynamic {
namespace {
using ast_matchers::internal::DynTypedMatcher;
using ast_matchers::internal::Matcher;
TEST(VariantValueTest, Unsigned) {
const unsigned kUnsigned = 17;
VariantValue Value = kUnsigned;
EXPECT_TRUE(Value.isUnsigned());
EXPECT_EQ(kUnsigned, Value.getUnsigned());
EXPECT_TRUE(Value.hasValue());
EXPECT_FALSE(Value.isString());
EXPECT_FALSE(Value.isMatcher());
}
TEST(VariantValueTest, String) {
const StringRef kString = "string";
VariantValue Value = kString;
EXPECT_TRUE(Value.isString());
EXPECT_EQ(kString, Value.getString());
EXPECT_EQ("String", Value.getTypeAsString());
EXPECT_TRUE(Value.hasValue());
EXPECT_FALSE(Value.isUnsigned());
EXPECT_FALSE(Value.isMatcher());
}
TEST(VariantValueTest, DynTypedMatcher) {
VariantValue Value = VariantMatcher::SingleMatcher(stmt());
EXPECT_TRUE(Value.hasValue());
EXPECT_FALSE(Value.isUnsigned());
EXPECT_FALSE(Value.isString());
EXPECT_TRUE(Value.isMatcher());
EXPECT_FALSE(Value.getMatcher().hasTypedMatcher<Decl>());
EXPECT_TRUE(Value.getMatcher().hasTypedMatcher<UnaryOperator>());
EXPECT_EQ("Matcher<Stmt>", Value.getTypeAsString());
// Can only convert to compatible matchers.
Value = VariantMatcher::SingleMatcher(recordDecl());
EXPECT_TRUE(Value.isMatcher());
EXPECT_TRUE(Value.getMatcher().hasTypedMatcher<Decl>());
EXPECT_FALSE(Value.getMatcher().hasTypedMatcher<UnaryOperator>());
EXPECT_EQ("Matcher<Decl>", Value.getTypeAsString());
Value = VariantMatcher::SingleMatcher(ignoringImpCasts(expr()));
EXPECT_TRUE(Value.isMatcher());
EXPECT_FALSE(Value.getMatcher().hasTypedMatcher<Decl>());
EXPECT_FALSE(Value.getMatcher().hasTypedMatcher<Stmt>());
EXPECT_TRUE(Value.getMatcher().hasTypedMatcher<Expr>());
EXPECT_TRUE(Value.getMatcher().hasTypedMatcher<IntegerLiteral>());
EXPECT_FALSE(Value.getMatcher().hasTypedMatcher<GotoStmt>());
EXPECT_EQ("Matcher<Expr>", Value.getTypeAsString());
}
TEST(VariantValueTest, Assignment) {
VariantValue Value = StringRef("A");
EXPECT_TRUE(Value.isString());
EXPECT_EQ("A", Value.getString());
EXPECT_TRUE(Value.hasValue());
EXPECT_FALSE(Value.isUnsigned());
EXPECT_FALSE(Value.isMatcher());
EXPECT_EQ("String", Value.getTypeAsString());
Value = VariantMatcher::SingleMatcher(recordDecl());
EXPECT_TRUE(Value.hasValue());
EXPECT_FALSE(Value.isUnsigned());
EXPECT_FALSE(Value.isString());
EXPECT_TRUE(Value.isMatcher());
EXPECT_TRUE(Value.getMatcher().hasTypedMatcher<Decl>());
EXPECT_FALSE(Value.getMatcher().hasTypedMatcher<UnaryOperator>());
EXPECT_EQ("Matcher<Decl>", Value.getTypeAsString());
Value = 17;
EXPECT_TRUE(Value.isUnsigned());
EXPECT_EQ(17U, Value.getUnsigned());
EXPECT_TRUE(Value.hasValue());
EXPECT_FALSE(Value.isMatcher());
EXPECT_FALSE(Value.isString());
Value = VariantValue();
EXPECT_FALSE(Value.hasValue());
EXPECT_FALSE(Value.isUnsigned());
EXPECT_FALSE(Value.isString());
EXPECT_FALSE(Value.isMatcher());
EXPECT_EQ("Nothing", Value.getTypeAsString());
}
TEST(VariantValueTest, ImplicitBool) {
VariantValue Value;
bool IfTrue = false;
if (Value) {
IfTrue = true;
}
EXPECT_FALSE(IfTrue);
EXPECT_TRUE(!Value);
Value = StringRef();
IfTrue = false;
if (Value) {
IfTrue = true;
}
EXPECT_TRUE(IfTrue);
EXPECT_FALSE(!Value);
}
TEST(VariantValueTest, Matcher) {
EXPECT_TRUE(matches("class X {};", VariantValue(VariantMatcher::SingleMatcher(
recordDecl(hasName("X"))))
.getMatcher()
.getTypedMatcher<Decl>()));
EXPECT_TRUE(
matches("int x;", VariantValue(VariantMatcher::SingleMatcher(varDecl()))
.getMatcher()
.getTypedMatcher<Decl>()));
EXPECT_TRUE(
matches("int foo() { return 1 + 1; }",
VariantValue(VariantMatcher::SingleMatcher(functionDecl()))
.getMatcher()
.getTypedMatcher<Decl>()));
// Can't get the wrong matcher.
EXPECT_FALSE(VariantValue(VariantMatcher::SingleMatcher(varDecl()))
.getMatcher()
.hasTypedMatcher<Stmt>());
#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
// Trying to get the wrong matcher fails an assertion in Matcher<T>. We don't
// do this test when building with MSVC because its debug C runtime prints the
// assertion failure message as a wide string, which gtest doesn't understand.
EXPECT_DEATH(VariantValue(VariantMatcher::SingleMatcher(varDecl()))
.getMatcher()
.getTypedMatcher<Stmt>(),
"hasTypedMatcher");
#endif
EXPECT_FALSE(matches(
"int x;", VariantValue(VariantMatcher::SingleMatcher(functionDecl()))
.getMatcher()
.getTypedMatcher<Decl>()));
EXPECT_FALSE(
matches("int foo() { return 1 + 1; }",
VariantValue(VariantMatcher::SingleMatcher(declRefExpr()))
.getMatcher()
.getTypedMatcher<Stmt>()));
}
} // end anonymous namespace
} // end namespace dynamic
} // end namespace ast_matchers
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers
|
repos/DirectXShaderCompiler/tools/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
|
//===- unittest/ASTMatchers/Dynamic/RegistryTest.cpp - Registry unit tests -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===-----------------------------------------------------------------------===//
#include "../ASTMatchersTest.h"
#include "clang/ASTMatchers/Dynamic/Registry.h"
#include "gtest/gtest.h"
#include <vector>
namespace clang {
namespace ast_matchers {
namespace dynamic {
namespace {
using ast_matchers::internal::Matcher;
class RegistryTest : public ::testing::Test {
public:
std::vector<ParserValue> Args() { return std::vector<ParserValue>(); }
std::vector<ParserValue> Args(const VariantValue &Arg1) {
std::vector<ParserValue> Out(1);
Out[0].Value = Arg1;
return Out;
}
std::vector<ParserValue> Args(const VariantValue &Arg1,
const VariantValue &Arg2) {
std::vector<ParserValue> Out(2);
Out[0].Value = Arg1;
Out[1].Value = Arg2;
return Out;
}
llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) {
return Registry::lookupMatcherCtor(MatcherName);
}
VariantMatcher constructMatcher(StringRef MatcherName,
Diagnostics *Error = nullptr) {
Diagnostics DummyError;
if (!Error) Error = &DummyError;
llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
VariantMatcher Out;
if (Ctor)
Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(), Error);
EXPECT_EQ("", DummyError.toStringFull());
return Out;
}
VariantMatcher constructMatcher(StringRef MatcherName,
const VariantValue &Arg1,
Diagnostics *Error = nullptr) {
Diagnostics DummyError;
if (!Error) Error = &DummyError;
llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
VariantMatcher Out;
if (Ctor)
Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1), Error);
EXPECT_EQ("", DummyError.toStringFull()) << MatcherName;
return Out;
}
VariantMatcher constructMatcher(StringRef MatcherName,
const VariantValue &Arg1,
const VariantValue &Arg2,
Diagnostics *Error = nullptr) {
Diagnostics DummyError;
if (!Error) Error = &DummyError;
llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
VariantMatcher Out;
if (Ctor)
Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1, Arg2),
Error);
EXPECT_EQ("", DummyError.toStringFull());
return Out;
}
typedef std::vector<MatcherCompletion> CompVector;
CompVector getCompletions() {
std::vector<std::pair<MatcherCtor, unsigned> > Context;
return Registry::getMatcherCompletions(
Registry::getAcceptedCompletionTypes(Context));
}
CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1) {
std::vector<std::pair<MatcherCtor, unsigned> > Context;
llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
if (!Ctor)
return CompVector();
Context.push_back(std::make_pair(*Ctor, ArgNo1));
return Registry::getMatcherCompletions(
Registry::getAcceptedCompletionTypes(Context));
}
CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1,
StringRef MatcherName2, unsigned ArgNo2) {
std::vector<std::pair<MatcherCtor, unsigned> > Context;
llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
if (!Ctor)
return CompVector();
Context.push_back(std::make_pair(*Ctor, ArgNo1));
Ctor = lookupMatcherCtor(MatcherName2);
if (!Ctor)
return CompVector();
Context.push_back(std::make_pair(*Ctor, ArgNo2));
return Registry::getMatcherCompletions(
Registry::getAcceptedCompletionTypes(Context));
}
bool hasCompletion(const CompVector &Comps, StringRef TypedText,
StringRef MatcherDecl = StringRef()) {
for (CompVector::const_iterator I = Comps.begin(), E = Comps.end(); I != E;
++I) {
if (I->TypedText == TypedText &&
(MatcherDecl.empty() || I->MatcherDecl == MatcherDecl)) {
return true;
}
}
return false;
}
};
TEST_F(RegistryTest, CanConstructNoArgs) {
Matcher<Stmt> IsArrowValue = constructMatcher(
"memberExpr", constructMatcher("isArrow")).getTypedMatcher<Stmt>();
Matcher<Stmt> BoolValue =
constructMatcher("boolLiteral").getTypedMatcher<Stmt>();
const std::string ClassSnippet = "struct Foo { int x; };\n"
"Foo *foo = new Foo;\n"
"int i = foo->x;\n";
const std::string BoolSnippet = "bool Foo = true;\n";
EXPECT_TRUE(matches(ClassSnippet, IsArrowValue));
EXPECT_TRUE(matches(BoolSnippet, BoolValue));
EXPECT_FALSE(matches(ClassSnippet, BoolValue));
EXPECT_FALSE(matches(BoolSnippet, IsArrowValue));
}
TEST_F(RegistryTest, ConstructWithSimpleArgs) {
Matcher<Decl> Value = constructMatcher(
"namedDecl", constructMatcher("hasName", StringRef("X")))
.getTypedMatcher<Decl>();
EXPECT_TRUE(matches("class X {};", Value));
EXPECT_FALSE(matches("int x;", Value));
Value = functionDecl(constructMatcher("parameterCountIs", 2)
.getTypedMatcher<FunctionDecl>());
EXPECT_TRUE(matches("void foo(int,int);", Value));
EXPECT_FALSE(matches("void foo(int);", Value));
}
TEST_F(RegistryTest, ConstructWithMatcherArgs) {
Matcher<Decl> HasInitializerSimple = constructMatcher(
"varDecl", constructMatcher("hasInitializer", constructMatcher("stmt")))
.getTypedMatcher<Decl>();
Matcher<Decl> HasInitializerComplex = constructMatcher(
"varDecl",
constructMatcher("hasInitializer", constructMatcher("callExpr")))
.getTypedMatcher<Decl>();
std::string code = "int i;";
EXPECT_FALSE(matches(code, HasInitializerSimple));
EXPECT_FALSE(matches(code, HasInitializerComplex));
code = "int i = 1;";
EXPECT_TRUE(matches(code, HasInitializerSimple));
EXPECT_FALSE(matches(code, HasInitializerComplex));
code = "int y(); int i = y();";
EXPECT_TRUE(matches(code, HasInitializerSimple));
EXPECT_TRUE(matches(code, HasInitializerComplex));
Matcher<Decl> HasParameter =
functionDecl(constructMatcher(
"hasParameter", 1, constructMatcher("hasName", StringRef("x")))
.getTypedMatcher<FunctionDecl>());
EXPECT_TRUE(matches("void f(int a, int x);", HasParameter));
EXPECT_FALSE(matches("void f(int x, int a);", HasParameter));
}
TEST_F(RegistryTest, OverloadedMatchers) {
Matcher<Stmt> CallExpr0 = constructMatcher(
"callExpr",
constructMatcher("callee", constructMatcher("memberExpr",
constructMatcher("isArrow"))))
.getTypedMatcher<Stmt>();
Matcher<Stmt> CallExpr1 = constructMatcher(
"callExpr",
constructMatcher(
"callee",
constructMatcher("methodDecl",
constructMatcher("hasName", StringRef("x")))))
.getTypedMatcher<Stmt>();
std::string Code = "class Y { public: void x(); }; void z() { Y y; y.x(); }";
EXPECT_FALSE(matches(Code, CallExpr0));
EXPECT_TRUE(matches(Code, CallExpr1));
Code = "class Z { public: void z() { this->z(); } };";
EXPECT_TRUE(matches(Code, CallExpr0));
EXPECT_FALSE(matches(Code, CallExpr1));
Matcher<Decl> DeclDecl = declaratorDecl(hasTypeLoc(
constructMatcher(
"loc", constructMatcher("asString", StringRef("const double *")))
.getTypedMatcher<TypeLoc>()));
Matcher<NestedNameSpecifierLoc> NNSL =
constructMatcher(
"loc", VariantMatcher::SingleMatcher(nestedNameSpecifier(
specifiesType(hasDeclaration(recordDecl(hasName("A")))))))
.getTypedMatcher<NestedNameSpecifierLoc>();
Code = "const double * x = 0;";
EXPECT_TRUE(matches(Code, DeclDecl));
EXPECT_FALSE(matches(Code, NNSL));
Code = "struct A { struct B {}; }; A::B a_b;";
EXPECT_FALSE(matches(Code, DeclDecl));
EXPECT_TRUE(matches(Code, NNSL));
}
TEST_F(RegistryTest, PolymorphicMatchers) {
const VariantMatcher IsDefinition = constructMatcher("isDefinition");
Matcher<Decl> Var =
constructMatcher("varDecl", IsDefinition).getTypedMatcher<Decl>();
Matcher<Decl> Class =
constructMatcher("recordDecl", IsDefinition).getTypedMatcher<Decl>();
Matcher<Decl> Func =
constructMatcher("functionDecl", IsDefinition).getTypedMatcher<Decl>();
EXPECT_TRUE(matches("int a;", Var));
EXPECT_FALSE(matches("extern int a;", Var));
EXPECT_TRUE(matches("class A {};", Class));
EXPECT_FALSE(matches("class A;", Class));
EXPECT_TRUE(matches("void f(){};", Func));
EXPECT_FALSE(matches("void f();", Func));
Matcher<Decl> Anything = constructMatcher("anything").getTypedMatcher<Decl>();
Matcher<Decl> RecordDecl = constructMatcher(
"recordDecl", constructMatcher("hasName", StringRef("Foo")),
VariantMatcher::SingleMatcher(Anything)).getTypedMatcher<Decl>();
EXPECT_TRUE(matches("int Foo;", Anything));
EXPECT_TRUE(matches("class Foo {};", Anything));
EXPECT_TRUE(matches("void Foo(){};", Anything));
EXPECT_FALSE(matches("int Foo;", RecordDecl));
EXPECT_TRUE(matches("class Foo {};", RecordDecl));
EXPECT_FALSE(matches("void Foo(){};", RecordDecl));
Matcher<Stmt> ConstructExpr = constructMatcher(
"constructExpr",
constructMatcher(
"hasDeclaration",
constructMatcher(
"methodDecl",
constructMatcher(
"ofClass", constructMatcher("hasName", StringRef("Foo"))))))
.getTypedMatcher<Stmt>();
EXPECT_FALSE(matches("class Foo { public: Foo(); };", ConstructExpr));
EXPECT_TRUE(
matches("class Foo { public: Foo(); }; Foo foo = Foo();", ConstructExpr));
}
TEST_F(RegistryTest, TemplateArgument) {
Matcher<Decl> HasTemplateArgument = constructMatcher(
"classTemplateSpecializationDecl",
constructMatcher(
"hasAnyTemplateArgument",
constructMatcher("refersToType",
constructMatcher("asString", StringRef("int")))))
.getTypedMatcher<Decl>();
EXPECT_TRUE(matches("template<typename T> class A {}; A<int> a;",
HasTemplateArgument));
EXPECT_FALSE(matches("template<typename T> class A {}; A<char> a;",
HasTemplateArgument));
}
TEST_F(RegistryTest, TypeTraversal) {
Matcher<Type> M = constructMatcher(
"pointerType",
constructMatcher("pointee", constructMatcher("isConstQualified"),
constructMatcher("isInteger"))).getTypedMatcher<Type>();
EXPECT_FALSE(matches("int *a;", M));
EXPECT_TRUE(matches("int const *b;", M));
M = constructMatcher(
"arrayType",
constructMatcher("hasElementType", constructMatcher("builtinType")))
.getTypedMatcher<Type>();
EXPECT_FALSE(matches("struct A{}; A a[7];;", M));
EXPECT_TRUE(matches("int b[7];", M));
}
TEST_F(RegistryTest, CXXCtorInitializer) {
Matcher<Decl> CtorDecl = constructMatcher(
"constructorDecl",
constructMatcher(
"hasAnyConstructorInitializer",
constructMatcher("forField",
constructMatcher("hasName", StringRef("foo")))))
.getTypedMatcher<Decl>();
EXPECT_TRUE(matches("struct Foo { Foo() : foo(1) {} int foo; };", CtorDecl));
EXPECT_FALSE(matches("struct Foo { Foo() {} int foo; };", CtorDecl));
EXPECT_FALSE(matches("struct Foo { Foo() : bar(1) {} int bar; };", CtorDecl));
}
TEST_F(RegistryTest, Adaptative) {
Matcher<Decl> D = constructMatcher(
"recordDecl",
constructMatcher(
"has",
constructMatcher("recordDecl",
constructMatcher("hasName", StringRef("X")))))
.getTypedMatcher<Decl>();
EXPECT_TRUE(matches("class X {};", D));
EXPECT_TRUE(matches("class Y { class X {}; };", D));
EXPECT_FALSE(matches("class Y { class Z {}; };", D));
Matcher<Stmt> S = constructMatcher(
"forStmt",
constructMatcher(
"hasDescendant",
constructMatcher("varDecl",
constructMatcher("hasName", StringRef("X")))))
.getTypedMatcher<Stmt>();
EXPECT_TRUE(matches("void foo() { for(int X;;); }", S));
EXPECT_TRUE(matches("void foo() { for(;;) { int X; } }", S));
EXPECT_FALSE(matches("void foo() { for(;;); }", S));
EXPECT_FALSE(matches("void foo() { if (int X = 0){} }", S));
S = constructMatcher(
"compoundStmt", constructMatcher("hasParent", constructMatcher("ifStmt")))
.getTypedMatcher<Stmt>();
EXPECT_TRUE(matches("void foo() { if (true) { int x = 42; } }", S));
EXPECT_FALSE(matches("void foo() { if (true) return; }", S));
}
TEST_F(RegistryTest, VariadicOp) {
Matcher<Decl> D = constructMatcher(
"anyOf",
constructMatcher("recordDecl",
constructMatcher("hasName", StringRef("Foo"))),
constructMatcher("functionDecl",
constructMatcher("hasName", StringRef("foo"))))
.getTypedMatcher<Decl>();
EXPECT_TRUE(matches("void foo(){}", D));
EXPECT_TRUE(matches("struct Foo{};", D));
EXPECT_FALSE(matches("int i = 0;", D));
D = constructMatcher(
"allOf", constructMatcher("recordDecl"),
constructMatcher(
"namedDecl",
constructMatcher("anyOf",
constructMatcher("hasName", StringRef("Foo")),
constructMatcher("hasName", StringRef("Bar")))))
.getTypedMatcher<Decl>();
EXPECT_FALSE(matches("void foo(){}", D));
EXPECT_TRUE(matches("struct Foo{};", D));
EXPECT_FALSE(matches("int i = 0;", D));
EXPECT_TRUE(matches("class Bar{};", D));
EXPECT_FALSE(matches("class OtherBar{};", D));
D = recordDecl(
has(fieldDecl(hasName("Foo"))),
constructMatcher(
"unless",
constructMatcher("namedDecl",
constructMatcher("hasName", StringRef("Bar"))))
.getTypedMatcher<Decl>());
EXPECT_FALSE(matches("class Bar{ int Foo; };", D));
EXPECT_TRUE(matches("class OtherBar{ int Foo; };", D));
D = constructMatcher(
"namedDecl", constructMatcher("hasName", StringRef("Foo")),
constructMatcher("unless", constructMatcher("recordDecl")))
.getTypedMatcher<Decl>();
EXPECT_TRUE(matches("void Foo(){}", D));
EXPECT_TRUE(notMatches("struct Foo {};", D));
}
TEST_F(RegistryTest, Errors) {
// Incorrect argument count.
std::unique_ptr<Diagnostics> Error(new Diagnostics());
EXPECT_TRUE(constructMatcher("hasInitializer", Error.get()).isNull());
EXPECT_EQ("Incorrect argument count. (Expected = 1) != (Actual = 0)",
Error->toString());
Error.reset(new Diagnostics());
EXPECT_TRUE(constructMatcher("isArrow", StringRef(), Error.get()).isNull());
EXPECT_EQ("Incorrect argument count. (Expected = 0) != (Actual = 1)",
Error->toString());
Error.reset(new Diagnostics());
EXPECT_TRUE(constructMatcher("anyOf", Error.get()).isNull());
EXPECT_EQ("Incorrect argument count. (Expected = (2, )) != (Actual = 0)",
Error->toString());
Error.reset(new Diagnostics());
EXPECT_TRUE(constructMatcher("unless", StringRef(), StringRef(),
Error.get()).isNull());
EXPECT_EQ("Incorrect argument count. (Expected = (1, 1)) != (Actual = 2)",
Error->toString());
// Bad argument type
Error.reset(new Diagnostics());
EXPECT_TRUE(constructMatcher("ofClass", StringRef(), Error.get()).isNull());
EXPECT_EQ("Incorrect type for arg 1. (Expected = Matcher<CXXRecordDecl>) != "
"(Actual = String)",
Error->toString());
Error.reset(new Diagnostics());
EXPECT_TRUE(constructMatcher("recordDecl", constructMatcher("recordDecl"),
constructMatcher("parameterCountIs", 3),
Error.get()).isNull());
EXPECT_EQ("Incorrect type for arg 2. (Expected = Matcher<CXXRecordDecl>) != "
"(Actual = Matcher<FunctionDecl>)",
Error->toString());
// Bad argument type with variadic.
Error.reset(new Diagnostics());
EXPECT_TRUE(constructMatcher("anyOf", StringRef(), StringRef(),
Error.get()).isNull());
EXPECT_EQ(
"Incorrect type for arg 1. (Expected = Matcher<>) != (Actual = String)",
Error->toString());
Error.reset(new Diagnostics());
EXPECT_TRUE(constructMatcher(
"recordDecl",
constructMatcher("allOf",
constructMatcher("isDerivedFrom", StringRef("FOO")),
constructMatcher("isArrow")),
Error.get()).isNull());
EXPECT_EQ("Incorrect type for arg 1. "
"(Expected = Matcher<CXXRecordDecl>) != "
"(Actual = Matcher<CXXRecordDecl>&Matcher<MemberExpr>)",
Error->toString());
}
TEST_F(RegistryTest, Completion) {
CompVector Comps = getCompletions();
// Overloaded
EXPECT_TRUE(hasCompletion(
Comps, "hasParent(", "Matcher<Decl|Stmt> hasParent(Matcher<Decl|Stmt>)"));
// Variadic.
EXPECT_TRUE(hasCompletion(Comps, "whileStmt(",
"Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)"));
// Polymorphic.
EXPECT_TRUE(hasCompletion(
Comps, "hasDescendant(",
"Matcher<NestedNameSpecifier|NestedNameSpecifierLoc|QualType|...> "
"hasDescendant(Matcher<CXXCtorInitializer|NestedNameSpecifier|"
"NestedNameSpecifierLoc|...>)"));
CompVector WhileComps = getCompletions("whileStmt", 0);
EXPECT_TRUE(hasCompletion(WhileComps, "hasBody(",
"Matcher<WhileStmt> hasBody(Matcher<Stmt>)"));
EXPECT_TRUE(hasCompletion(WhileComps, "hasParent(",
"Matcher<Stmt> hasParent(Matcher<Decl|Stmt>)"));
EXPECT_TRUE(
hasCompletion(WhileComps, "allOf(", "Matcher<T> allOf(Matcher<T>...)"));
EXPECT_FALSE(hasCompletion(WhileComps, "whileStmt("));
EXPECT_FALSE(hasCompletion(WhileComps, "ifStmt("));
CompVector AllOfWhileComps =
getCompletions("allOf", 0, "whileStmt", 0);
ASSERT_EQ(AllOfWhileComps.size(), WhileComps.size());
EXPECT_TRUE(std::equal(WhileComps.begin(), WhileComps.end(),
AllOfWhileComps.begin()));
CompVector DeclWhileComps =
getCompletions("decl", 0, "whileStmt", 0);
EXPECT_EQ(0u, DeclWhileComps.size());
CompVector NamedDeclComps = getCompletions("namedDecl", 0);
EXPECT_TRUE(
hasCompletion(NamedDeclComps, "isPublic()", "Matcher<Decl> isPublic()"));
EXPECT_TRUE(hasCompletion(NamedDeclComps, "hasName(\"",
"Matcher<NamedDecl> hasName(string)"));
// Heterogeneous overloads.
Comps = getCompletions("classTemplateSpecializationDecl", 0);
EXPECT_TRUE(hasCompletion(
Comps, "isSameOrDerivedFrom(",
"Matcher<CXXRecordDecl> isSameOrDerivedFrom(string|Matcher<NamedDecl>)"));
}
TEST_F(RegistryTest, HasArgs) {
Matcher<Decl> Value = constructMatcher(
"decl", constructMatcher("hasAttr", StringRef("attr::WarnUnused")))
.getTypedMatcher<Decl>();
EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};", Value));
EXPECT_FALSE(matches("struct X {};", Value));
}
} // end anonymous namespace
} // end namespace dynamic
} // end namespace ast_matchers
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/libclang/LibclangTest.cpp
|
//===- unittests/libclang/LibclangTest.cpp --- libclang tests -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang-c/Index.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "gtest/gtest.h"
#include <fstream>
#include <set>
#define DEBUG_TYPE "libclang-test"
TEST(libclang, clang_parseTranslationUnit2_InvalidArgs) {
EXPECT_EQ(CXError_InvalidArguments,
clang_parseTranslationUnit2(nullptr, nullptr, nullptr, 0, nullptr,
0, 0, nullptr));
}
TEST(libclang, clang_createTranslationUnit_InvalidArgs) {
EXPECT_EQ(nullptr, clang_createTranslationUnit(nullptr, nullptr));
}
TEST(libclang, clang_createTranslationUnit2_InvalidArgs) {
EXPECT_EQ(CXError_InvalidArguments,
clang_createTranslationUnit2(nullptr, nullptr, nullptr));
CXTranslationUnit TU = reinterpret_cast<CXTranslationUnit>(1);
EXPECT_EQ(CXError_InvalidArguments,
clang_createTranslationUnit2(nullptr, nullptr, &TU));
EXPECT_EQ(nullptr, TU);
}
namespace {
struct TestVFO {
const char *Contents;
CXVirtualFileOverlay VFO;
TestVFO(const char *Contents) : Contents(Contents) {
VFO = clang_VirtualFileOverlay_create(0);
}
void map(const char *VPath, const char *RPath) {
CXErrorCode Err = clang_VirtualFileOverlay_addFileMapping(VFO, VPath, RPath);
EXPECT_EQ(Err, CXError_Success);
}
void mapError(const char *VPath, const char *RPath, CXErrorCode ExpErr) {
CXErrorCode Err = clang_VirtualFileOverlay_addFileMapping(VFO, VPath, RPath);
EXPECT_EQ(Err, ExpErr);
}
~TestVFO() {
if (Contents) {
char *BufPtr;
unsigned BufSize;
clang_VirtualFileOverlay_writeToBuffer(VFO, 0, &BufPtr, &BufSize);
std::string BufStr(BufPtr, BufSize);
EXPECT_STREQ(Contents, BufStr.c_str());
clang_free(BufPtr);
}
clang_VirtualFileOverlay_dispose(VFO);
}
};
}
TEST(libclang, VirtualFileOverlay_Basic) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'roots': [\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/virtual\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo.h\",\n"
" 'external-contents': \"/real/foo.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
"}\n";
TestVFO T(contents);
T.map("/path/virtual/foo.h", "/real/foo.h");
}
TEST(libclang, VirtualFileOverlay_Unicode) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'roots': [\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/\\u266B\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"\\u2602.h\",\n"
" 'external-contents': \"/real/\\u2602.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
"}\n";
TestVFO T(contents);
T.map("/path/♫/☂.h", "/real/☂.h");
}
TEST(libclang, VirtualFileOverlay_InvalidArgs) {
TestVFO T(nullptr);
T.mapError("/path/./virtual/../foo.h", "/real/foo.h",
CXError_InvalidArguments);
}
TEST(libclang, VirtualFileOverlay_RemapDirectories) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'roots': [\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/another/dir\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo2.h\",\n"
" 'external-contents': \"/real/foo2.h\"\n"
" }\n"
" ]\n"
" },\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/virtual/dir\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo1.h\",\n"
" 'external-contents': \"/real/foo1.h\"\n"
" },\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo3.h\",\n"
" 'external-contents': \"/real/foo3.h\"\n"
" },\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"in/subdir\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo4.h\",\n"
" 'external-contents': \"/real/foo4.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
"}\n";
TestVFO T(contents);
T.map("/path/virtual/dir/foo1.h", "/real/foo1.h");
T.map("/another/dir/foo2.h", "/real/foo2.h");
T.map("/path/virtual/dir/foo3.h", "/real/foo3.h");
T.map("/path/virtual/dir/in/subdir/foo4.h", "/real/foo4.h");
}
TEST(libclang, VirtualFileOverlay_CaseInsensitive) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'case-sensitive': 'false',\n"
" 'roots': [\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/virtual\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo.h\",\n"
" 'external-contents': \"/real/foo.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
"}\n";
TestVFO T(contents);
T.map("/path/virtual/foo.h", "/real/foo.h");
clang_VirtualFileOverlay_setCaseSensitivity(T.VFO, false);
}
TEST(libclang, VirtualFileOverlay_SharedPrefix) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'roots': [\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/foo\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"bar\",\n"
" 'external-contents': \"/real/bar\"\n"
" },\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"bar.h\",\n"
" 'external-contents': \"/real/bar.h\"\n"
" }\n"
" ]\n"
" },\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/foobar\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"baz.h\",\n"
" 'external-contents': \"/real/baz.h\"\n"
" }\n"
" ]\n"
" },\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foobarbaz.h\",\n"
" 'external-contents': \"/real/foobarbaz.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
"}\n";
TestVFO T(contents);
T.map("/path/foo/bar.h", "/real/bar.h");
T.map("/path/foo/bar", "/real/bar");
T.map("/path/foobar/baz.h", "/real/baz.h");
T.map("/path/foobarbaz.h", "/real/foobarbaz.h");
}
TEST(libclang, VirtualFileOverlay_AdjacentDirectory) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'roots': [\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/dir1\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo.h\",\n"
" 'external-contents': \"/real/foo.h\"\n"
" },\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"subdir\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"bar.h\",\n"
" 'external-contents': \"/real/bar.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
" },\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/path/dir2\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"baz.h\",\n"
" 'external-contents': \"/real/baz.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
"}\n";
TestVFO T(contents);
T.map("/path/dir1/foo.h", "/real/foo.h");
T.map("/path/dir1/subdir/bar.h", "/real/bar.h");
T.map("/path/dir2/baz.h", "/real/baz.h");
}
TEST(libclang, VirtualFileOverlay_TopLevel) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'roots': [\n"
" {\n"
" 'type': 'directory',\n"
" 'name': \"/\",\n"
" 'contents': [\n"
" {\n"
" 'type': 'file',\n"
" 'name': \"foo.h\",\n"
" 'external-contents': \"/real/foo.h\"\n"
" }\n"
" ]\n"
" }\n"
" ]\n"
"}\n";
TestVFO T(contents);
T.map("/foo.h", "/real/foo.h");
}
TEST(libclang, VirtualFileOverlay_Empty) {
const char *contents =
"{\n"
" 'version': 0,\n"
" 'roots': [\n"
" ]\n"
"}\n";
TestVFO T(contents);
}
TEST(libclang, ModuleMapDescriptor) {
const char *Contents =
"framework module TestFrame {\n"
" umbrella header \"TestFrame.h\"\n"
"\n"
" export *\n"
" module * { export * }\n"
"}\n";
CXModuleMapDescriptor MMD = clang_ModuleMapDescriptor_create(0);
clang_ModuleMapDescriptor_setFrameworkModuleName(MMD, "TestFrame");
clang_ModuleMapDescriptor_setUmbrellaHeader(MMD, "TestFrame.h");
char *BufPtr;
unsigned BufSize;
clang_ModuleMapDescriptor_writeToBuffer(MMD, 0, &BufPtr, &BufSize);
std::string BufStr(BufPtr, BufSize);
EXPECT_STREQ(Contents, BufStr.c_str());
clang_free(BufPtr);
clang_ModuleMapDescriptor_dispose(MMD);
}
class LibclangReparseTest : public ::testing::Test {
std::set<std::string> Files;
public:
std::string TestDir;
CXIndex Index;
CXTranslationUnit ClangTU;
unsigned TUFlags;
void SetUp() override {
llvm::SmallString<256> Dir;
ASSERT_FALSE(llvm::sys::fs::createUniqueDirectory("libclang-test", Dir));
TestDir = Dir.str();
TUFlags = CXTranslationUnit_DetailedPreprocessingRecord |
clang_defaultEditingTranslationUnitOptions();
Index = clang_createIndex(0, 0);
}
void TearDown() override {
clang_disposeTranslationUnit(ClangTU);
clang_disposeIndex(Index);
for (const std::string &Path : Files)
llvm::sys::fs::remove(Path);
llvm::sys::fs::remove(TestDir);
}
void WriteFile(std::string &Filename, const std::string &Contents) {
if (!llvm::sys::path::is_absolute(Filename)) {
llvm::SmallString<256> Path(TestDir);
llvm::sys::path::append(Path, Filename);
Filename = Path.str();
Files.insert(Filename);
}
std::ofstream OS(Filename);
OS << Contents;
}
void DisplayDiagnostics() {
unsigned NumDiagnostics = clang_getNumDiagnostics(ClangTU);
for (unsigned i = 0; i < NumDiagnostics; ++i) {
auto Diag = clang_getDiagnostic(ClangTU, i);
DEBUG(llvm::dbgs() << clang_getCString(clang_formatDiagnostic(
Diag, clang_defaultDiagnosticDisplayOptions())) << "\n");
clang_disposeDiagnostic(Diag);
}
}
bool ReparseTU(unsigned num_unsaved_files, CXUnsavedFile* unsaved_files) {
if (clang_reparseTranslationUnit(ClangTU, num_unsaved_files, unsaved_files,
clang_defaultReparseOptions(ClangTU))) {
DEBUG(llvm::dbgs() << "Reparse failed\n");
return false;
}
DisplayDiagnostics();
return true;
}
};
TEST_F(LibclangReparseTest, Reparse) {
const char *HeaderTop = "#ifndef H\n#define H\nstruct Foo { int bar;";
const char *HeaderBottom = "\n};\n#endif\n";
const char *CppFile = "#include \"HeaderFile.h\"\nint main() {"
" Foo foo; foo.bar = 7; foo.baz = 8; }\n";
std::string HeaderName = "HeaderFile.h";
std::string CppName = "CppFile.cpp";
WriteFile(CppName, CppFile);
WriteFile(HeaderName, std::string(HeaderTop) + HeaderBottom);
ClangTU = clang_parseTranslationUnit(Index, CppName.c_str(), nullptr, 0,
nullptr, 0, TUFlags);
EXPECT_EQ(1U, clang_getNumDiagnostics(ClangTU));
DisplayDiagnostics();
// Immedaitely reparse.
ASSERT_TRUE(ReparseTU(0, nullptr /* No unsaved files. */));
EXPECT_EQ(1U, clang_getNumDiagnostics(ClangTU));
std::string NewHeaderContents =
std::string(HeaderTop) + "int baz;" + HeaderBottom;
WriteFile(HeaderName, NewHeaderContents);
// Reparse after fix.
ASSERT_TRUE(ReparseTU(0, nullptr /* No unsaved files. */));
EXPECT_EQ(0U, clang_getNumDiagnostics(ClangTU));
}
TEST_F(LibclangReparseTest, ReparseWithModule) {
const char *HeaderTop = "#ifndef H\n#define H\nstruct Foo { int bar;";
const char *HeaderBottom = "\n};\n#endif\n";
const char *MFile = "#include \"HeaderFile.h\"\nint main() {"
" struct Foo foo; foo.bar = 7; foo.baz = 8; }\n";
const char *ModFile = "module A { header \"HeaderFile.h\" }\n";
std::string HeaderName = "HeaderFile.h";
std::string MName = "MFile.m";
std::string ModName = "module.modulemap";
WriteFile(MName, MFile);
WriteFile(HeaderName, std::string(HeaderTop) + HeaderBottom);
WriteFile(ModName, ModFile);
std::string ModulesCache = std::string("-fmodules-cache-path=") + TestDir;
const char *Args[] = { "-fmodules", ModulesCache.c_str(),
"-I", TestDir.c_str() };
int NumArgs = sizeof(Args) / sizeof(Args[0]);
ClangTU = clang_parseTranslationUnit(Index, MName.c_str(), Args, NumArgs,
nullptr, 0, TUFlags);
EXPECT_EQ(1U, clang_getNumDiagnostics(ClangTU));
DisplayDiagnostics();
// Immedaitely reparse.
ASSERT_TRUE(ReparseTU(0, nullptr /* No unsaved files. */));
EXPECT_EQ(1U, clang_getNumDiagnostics(ClangTU));
std::string NewHeaderContents =
std::string(HeaderTop) + "int baz;" + HeaderBottom;
WriteFile(HeaderName, NewHeaderContents);
// Reparse after fix.
ASSERT_TRUE(ReparseTU(0, nullptr /* No unsaved files. */));
EXPECT_EQ(0U, clang_getNumDiagnostics(ClangTU));
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/libclang/CMakeLists.txt
|
add_clang_unittest(libclangTests
LibclangTest.cpp
)
target_link_libraries(libclangTests
libclang
)
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/ClangHLSLTests.vcxproj.user.txt
|
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<LocalDebuggerCommand>${DOS_TAEF_BIN_DIR}\$(PlatformTarget)\Te.exe</LocalDebuggerCommand>
<LocalDebuggerCommand Condition="'$(PlatformTarget)' == 'x64' And Exists('${DOS_TAEF_BIN_DIR}\amd64\Te.exe')">${DOS_TAEF_BIN_DIR}\amd64\Te.exe</LocalDebuggerCommand>
<LocalDebuggerCommandArguments>$(TargetPath) /inproc /p:"HlslDataDir=${DOS_STYLE_SOURCE_DIR}\..\..\test\HLSL" /name:*</LocalDebuggerCommandArguments>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/OptionsTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// OptionsTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for the command-line options APIs. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef UNICODE
#define UNICODE
#endif
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#include <algorithm>
#include <cassert>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "dxc/Test/HLSLTestData.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/HLSLOptions.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/dxcapi.use.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/raw_os_ostream.h"
#include <fstream>
using namespace std;
using namespace hlsl_test;
using namespace hlsl;
using namespace hlsl::options;
/// Use this class to construct MainArgs from constants. Handy to use because
/// DxcOpts will StringRef into it.
class MainArgsArr : public MainArgs {
public:
template <size_t n>
MainArgsArr(const wchar_t *(&arr)[n]) : MainArgs(n, arr) {}
};
#ifdef _WIN32
class OptionsTest {
#else
class OptionsTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(OptionsTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_METHOD(ReadOptionsWhenDefinesThenInit)
TEST_METHOD(ReadOptionsWhenExtensionsThenOK)
TEST_METHOD(ReadOptionsWhenHelpThenShortcut)
TEST_METHOD(ReadOptionsWhenInvalidThenFail)
TEST_METHOD(ReadOptionsConflict)
TEST_METHOD(ReadOptionsWhenValidThenOK)
TEST_METHOD(ReadOptionsWhenJoinedThenOK)
TEST_METHOD(ReadOptionsWhenNoEntryThenOK)
TEST_METHOD(ReadOptionsForOutputObject)
TEST_METHOD(ReadOptionsForDxcWhenApiArgMissingThenFail)
TEST_METHOD(ReadOptionsForApiWhenApiArgMissingThenOK)
TEST_METHOD(ConvertWhenFailThenThrow)
TEST_METHOD(CopyOptionsWhenSingleThenOK)
// TEST_METHOD(CopyOptionsWhenMultipleThenOK)
TEST_METHOD(ReadOptionsJoinedWithSpacesThenOK)
TEST_METHOD(ReadOptionsNoNonLegacyCBuffer)
TEST_METHOD(TestPreprocessOption)
TEST_METHOD(SerializeDxilFlags)
std::unique_ptr<DxcOpts> ReadOptsTest(const MainArgs &mainArgs,
unsigned flagsToInclude,
bool shouldFail = false,
bool shouldMessage = false) {
std::string errorString;
llvm::raw_string_ostream errorStream(errorString);
std::unique_ptr<DxcOpts> opts = llvm::make_unique<DxcOpts>();
int result = ReadDxcOpts(getHlslOptTable(), flagsToInclude, mainArgs,
*(opts.get()), errorStream);
EXPECT_EQ(shouldFail, result != 0);
EXPECT_EQ(shouldMessage, !errorStream.str().empty());
return opts;
}
// Test variant that verifies expected pass condition
// and checks error output to match given message.
void ReadOptsTest(const MainArgs &mainArgs, unsigned flagsToInclude,
bool shouldFail, const char *expectErrorMsg) {
std::string errorString;
llvm::raw_string_ostream errorStream(errorString);
std::unique_ptr<DxcOpts> opts = llvm::make_unique<DxcOpts>();
int result = ReadDxcOpts(getHlslOptTable(), flagsToInclude, mainArgs,
*(opts.get()), errorStream);
EXPECT_EQ(shouldFail, result != 0);
VERIFY_ARE_EQUAL_STR(expectErrorMsg, errorStream.str().c_str());
}
void ReadOptsTest(const MainArgs &mainArgs, unsigned flagsToInclude,
const char *expectErrorMsg) {
ReadOptsTest(mainArgs, flagsToInclude, true /*shouldFail*/, expectErrorMsg);
}
};
TEST_F(OptionsTest, ReadOptionsWhenExtensionsThenOK) {
const wchar_t *Args[] = {
L"exe.exe", L"/E", L"main", L"/T", L"ps_6_0",
L"hlsl.hlsl", L"-external", L"foo.dll", L"-external-fn", L"CreateObj"};
const wchar_t *ArgsNoLib[] = {L"exe.exe", L"/E", L"main",
L"/T", L"ps_6_0", L"hlsl.hlsl",
L"-external-fn", L"CreateObj"};
const wchar_t *ArgsNoFn[] = {L"exe.exe", L"/E", L"main",
L"/T", L"ps_6_0", L"hlsl.hlsl",
L"-external", L"foo.dll"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_ARE_EQUAL_STR("CreateObj", o->ExternalFn.data());
VERIFY_ARE_EQUAL_STR("foo.dll", o->ExternalLib.data());
MainArgsArr ArgsNoLibArr(ArgsNoLib);
ReadOptsTest(ArgsNoLibArr, DxcFlags, true, true);
MainArgsArr ArgsNoFnArr(ArgsNoFn);
ReadOptsTest(ArgsNoFnArr, DxcFlags, true, true);
}
TEST_F(OptionsTest, ReadOptionsForOutputObject) {
const wchar_t *Args[] = {L"exe.exe", L"/E", L"main", L"/T",
L"ps_6_0", L"hlsl.hlsl", L"-Fo", L"hlsl.dxbc"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_ARE_EQUAL_STR("hlsl.dxbc", o->OutputObject.data());
}
TEST_F(OptionsTest, ReadOptionsConflict) {
const wchar_t *matrixArgs[] = {L"exe.exe", L"/E", L"main", L"/T",
L"ps_6_0", L"-Zpr", L"-Zpc", L"hlsl.hlsl"};
MainArgsArr ArgsArr(matrixArgs);
ReadOptsTest(
ArgsArr, DxcFlags,
"Cannot specify /Zpr and /Zpc together, use /? to get usage information");
const wchar_t *controlFlowArgs[] = {L"exe.exe", L"/E", L"main",
L"/T", L"ps_6_0", L"-Gfa",
L"-Gfp", L"hlsl.hlsl"};
MainArgsArr controlFlowArr(controlFlowArgs);
ReadOptsTest(
controlFlowArr, DxcFlags,
"Cannot specify /Gfa and /Gfp together, use /? to get usage information");
const wchar_t *libArgs[] = {L"exe.exe", L"/E", L"main",
L"/T", L"lib_6_1", L"hlsl.hlsl"};
MainArgsArr libArr(libArgs);
ReadOptsTest(
libArr, DxcFlags,
"Must disable validation for unsupported lib_6_1 or lib_6_2 targets.");
}
TEST_F(OptionsTest, ReadOptionsWhenHelpThenShortcut) {
const wchar_t *Args[] = {L"exe.exe", L"--help", L"--unknown-flag"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
EXPECT_EQ(true, o->ShowHelp);
}
TEST_F(OptionsTest, ReadOptionsWhenValidThenOK) {
const wchar_t *Args[] = {L"exe.exe", L"/E", L"main",
L"/T", L"ps_6_0", L"hlsl.hlsl"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_ARE_EQUAL_STR("main", o->EntryPoint.data());
VERIFY_ARE_EQUAL_STR("ps_6_0", o->TargetProfile.data());
VERIFY_ARE_EQUAL_STR("hlsl.hlsl", o->InputFile.data());
}
TEST_F(OptionsTest, ReadOptionsWhenJoinedThenOK) {
const wchar_t *Args[] = {L"exe.exe", L"/Emain", L"/Tps_6_0", L"hlsl.hlsl"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_ARE_EQUAL_STR("main", o->EntryPoint.data());
VERIFY_ARE_EQUAL_STR("ps_6_0", o->TargetProfile.data());
VERIFY_ARE_EQUAL_STR("hlsl.hlsl", o->InputFile.data());
}
TEST_F(OptionsTest, ReadOptionsWhenNoEntryThenOK) {
// It's not an error to omit the entry function name, but it's not
// set to 'main' on behalf of callers either.
const wchar_t *Args[] = {L"exe.exe", L"/T", L"ps_6_0", L"hlsl.hlsl"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_IS_TRUE(o->EntryPoint.empty());
}
TEST_F(OptionsTest, ReadOptionsWhenInvalidThenFail) {
const wchar_t *ArgsNoTarget[] = {L"exe.exe", L"/E", L"main", L"hlsl.hlsl"};
const wchar_t *ArgsNoInput[] = {L"exe.exe", L"/E", L"main", L"/T", L"ps_6_0"};
const wchar_t *ArgsNoArg[] = {L"exe.exe", L"hlsl.hlsl", L"/E", L"main",
L"/T"};
const wchar_t *ArgsUnknown[] = {L"exe.exe",
L"hlsl.hlsl",
L"/E",
L"main",
(L"/T"
L"ps_6_0"),
L"--unknown"};
const wchar_t *ArgsUnknownButIgnore[] = {
L"exe.exe", L"hlsl.hlsl", L"/E", L"main",
L"/T", L"ps_6_0", L"--unknown", L"-Qunused-arguments"};
MainArgsArr ArgsNoTargetArr(ArgsNoTarget), ArgsNoInputArr(ArgsNoInput),
ArgsNoArgArr(ArgsNoArg), ArgsUnknownArr(ArgsUnknown),
ArgsUnknownButIgnoreArr(ArgsUnknownButIgnore);
ReadOptsTest(ArgsNoTargetArr, DxcFlags, true, true);
ReadOptsTest(ArgsNoInputArr, DxcFlags, true, true);
ReadOptsTest(ArgsNoArgArr, DxcFlags, true, true);
ReadOptsTest(ArgsUnknownArr, DxcFlags, true, true);
ReadOptsTest(ArgsUnknownButIgnoreArr, DxcFlags);
}
TEST_F(OptionsTest, ReadOptionsWhenDefinesThenInit) {
const wchar_t *ArgsNoDefines[] = {L"exe.exe", L"/T", L"ps_6_0",
L"/E", L"main", L"hlsl.hlsl"};
const wchar_t *ArgsOneDefine[] = {
L"exe.exe", L"/DNAME1=1", L"/T", L"ps_6_0", L"/E", L"main", L"hlsl.hlsl"};
const wchar_t *ArgsTwoDefines[] = {
L"exe.exe", L"/DNAME1=1", L"/T", L"ps_6_0", L"/D", L"NAME2=2",
L"/E", L"main", L"/T", L"ps_6_0", L"hlsl.hlsl"};
const wchar_t *ArgsEmptyDefine[] = {
L"exe.exe", L"/DNAME1", L"hlsl.hlsl", L"/E", L"main", L"/T", L"ps_6_0",
};
MainArgsArr ArgsNoDefinesArr(ArgsNoDefines), ArgsOneDefineArr(ArgsOneDefine),
ArgsTwoDefinesArr(ArgsTwoDefines), ArgsEmptyDefineArr(ArgsEmptyDefine);
std::unique_ptr<DxcOpts> o;
o = ReadOptsTest(ArgsNoDefinesArr, DxcFlags);
EXPECT_EQ(0U, o->Defines.size());
o = ReadOptsTest(ArgsOneDefineArr, DxcFlags);
EXPECT_EQ(1U, o->Defines.size());
EXPECT_STREQW(L"NAME1", o->Defines.data()[0].Name);
EXPECT_STREQW(L"1", o->Defines.data()[0].Value);
o = ReadOptsTest(ArgsTwoDefinesArr, DxcFlags);
EXPECT_EQ(2U, o->Defines.size());
EXPECT_STREQW(L"NAME1", o->Defines.data()[0].Name);
EXPECT_STREQW(L"1", o->Defines.data()[0].Value);
EXPECT_STREQW(L"NAME2", o->Defines.data()[1].Name);
EXPECT_STREQW(L"2", o->Defines.data()[1].Value);
o = ReadOptsTest(ArgsEmptyDefineArr, DxcFlags);
EXPECT_EQ(1U, o->Defines.size());
EXPECT_STREQW(L"NAME1", o->Defines.data()[0].Name);
EXPECT_EQ(nullptr, o->Defines.data()[0].Value);
}
TEST_F(OptionsTest, ReadOptionsForDxcWhenApiArgMissingThenFail) {
// When an argument specified through an API argument is not specified (eg the
// target model), for the command-line dxc.exe tool, then the validation
// should fail.
const wchar_t *Args[] = {L"exe.exe", L"/E", L"main", L"hlsl.hlsl"};
MainArgsArr mainArgsArr(Args);
std::unique_ptr<DxcOpts> o;
o = ReadOptsTest(mainArgsArr, DxcFlags, true, true);
}
TEST_F(OptionsTest, ReadOptionsForApiWhenApiArgMissingThenOK) {
// When an argument specified through an API argument is not specified (eg the
// target model), for an API, then the validation should not fail.
const wchar_t *Args[] = {L"exe.exe", L"/E", L"main", L"hlsl.hlsl"};
MainArgsArr mainArgsArr(Args);
std::unique_ptr<DxcOpts> o;
o = ReadOptsTest(mainArgsArr, CompilerFlags, false, false);
}
TEST_F(OptionsTest, ConvertWhenFailThenThrow) {
std::wstring wstr;
// Simple test to verify conversion works.
EXPECT_EQ(true, Unicode::UTF8ToWideString("test", &wstr));
EXPECT_STREQW(L"test", wstr.data());
// Simple test to verify conversion works with actual UTF-8 and not just
// ASCII. n with tilde is Unicode 0x00F1, encoded in UTF-8 as 0xC3 0xB1
EXPECT_EQ(true, Unicode::UTF8ToWideString("\xC3\xB1", &wstr));
EXPECT_STREQW(L"\x00F1", wstr.data());
// Fail when the sequence is incomplete.
EXPECT_EQ(false, Unicode::UTF8ToWideString("\xC3", &wstr));
// Throw on failure.
bool thrown = false;
try {
Unicode::UTF8ToWideStringOrThrow("\xC3");
} catch (...) {
thrown = true;
}
EXPECT_EQ(true, thrown);
}
TEST_F(OptionsTest, CopyOptionsWhenSingleThenOK) {
const char *ArgsNoDefines[] = {"/T", "ps_6_0", "/E",
"main", "hlsl.hlsl", "-unknown"};
const llvm::opt::OptTable *table = getHlslOptTable();
unsigned missingIndex = 0, missingArgCount = 0;
llvm::opt::InputArgList args =
table->ParseArgs(ArgsNoDefines, missingIndex, missingArgCount, DxcFlags);
std::vector<std::wstring> outArgs;
CopyArgsToWStrings(args, DxcFlags, outArgs);
EXPECT_EQ(4U, outArgs.size()); // -unknown and hlsl.hlsl are missing
VERIFY_ARE_NOT_EQUAL(outArgs.end(), std::find(outArgs.begin(), outArgs.end(),
std::wstring(L"/T")));
VERIFY_ARE_NOT_EQUAL(outArgs.end(), std::find(outArgs.begin(), outArgs.end(),
std::wstring(L"ps_6_0")));
VERIFY_ARE_NOT_EQUAL(outArgs.end(), std::find(outArgs.begin(), outArgs.end(),
std::wstring(L"/E")));
VERIFY_ARE_NOT_EQUAL(outArgs.end(), std::find(outArgs.begin(), outArgs.end(),
std::wstring(L"main")));
VERIFY_ARE_EQUAL(outArgs.end(), std::find(outArgs.begin(), outArgs.end(),
std::wstring(L"hlsl.hlsl")));
}
TEST_F(OptionsTest, ReadOptionsJoinedWithSpacesThenOK) {
{
// Ensure parsing arguments in joined form with embedded spaces
// between the option and the argument works, for these argument types:
// - JoinedOrSeparateClass (-E, -T)
// - SeparateClass (-external, -external-fn)
const wchar_t *Args[] = {L"exe.exe", L"-E main",
L"/T ps_6_0", L"hlsl.hlsl",
L"-external foo.dll", L"-external-fn CreateObj"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_ARE_EQUAL_STR("main", o->EntryPoint.data());
VERIFY_ARE_EQUAL_STR("ps_6_0", o->TargetProfile.data());
VERIFY_ARE_EQUAL_STR("CreateObj", o->ExternalFn.data());
VERIFY_ARE_EQUAL_STR("foo.dll", o->ExternalLib.data());
}
{
// Ignore trailing spaces in option name for JoinedOrSeparateClass
// Otherwise error messages are not easy for user to interpret
const wchar_t *Args[] = {L"exe.exe", L"-E ", L"main",
L"/T ", L"ps_6_0", L"hlsl.hlsl"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_ARE_EQUAL_STR("main", o->EntryPoint.data());
VERIFY_ARE_EQUAL_STR("ps_6_0", o->TargetProfile.data());
}
{
// Ignore trailing spaces in option name for SeparateClass
// Otherwise error messages are not easy for user to interpret
const wchar_t *Args[] = {L"exe.exe", L"-E", L"main",
L"/T", L"ps_6_0", L"hlsl.hlsl",
L"-external ", L"foo.dll", L"-external-fn ",
L"CreateObj"};
MainArgsArr ArgsArr(Args);
std::unique_ptr<DxcOpts> o = ReadOptsTest(ArgsArr, DxcFlags);
VERIFY_ARE_EQUAL_STR("CreateObj", o->ExternalFn.data());
VERIFY_ARE_EQUAL_STR("foo.dll", o->ExternalLib.data());
}
}
TEST_F(OptionsTest, ReadOptionsNoNonLegacyCBuffer) {
{
const wchar_t *Args[] = {L"exe.exe", L"/T ", L"ps_6_0", L"hlsl.hlsl",
L"-no-legacy-cbuf-layout"};
MainArgsArr ArgsArr(Args);
ReadOptsTest(ArgsArr, DxcFlags, false /*shouldFail*/,
"warning: -no-legacy-cbuf-layout is no longer supported and "
"will be ignored. Future releases will not recognize it.\n");
}
{
const wchar_t *Args[] = {L"exe.exe", L"/T ", L"ps_6_0", L"hlsl.hlsl",
L"-not_use_legacy_cbuf_load"};
MainArgsArr ArgsArr(Args);
ReadOptsTest(ArgsArr, DxcFlags, false /*shouldFail*/,
"warning: -no-legacy-cbuf-layout is no longer supported and "
"will be ignored. Future releases will not recognize it.\n");
}
}
static void VerifyPreprocessOption(llvm::StringRef command,
const char *ExpectOutput,
const char *ErrMsg) {
std::string errorString;
const llvm::opt::OptTable *optionTable = getHlslOptTable();
llvm::SmallVector<llvm::StringRef, 4> args;
command.split(args, " ", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
MainArgs argStrings(args);
DxcOpts dxcOpts;
llvm::raw_string_ostream errorStream(errorString);
int retVal =
ReadDxcOpts(optionTable, DxcFlags, argStrings, dxcOpts, errorStream);
EXPECT_EQ(retVal, 0);
EXPECT_STREQ(dxcOpts.Preprocess.c_str(), ExpectOutput);
errorStream.flush();
EXPECT_STREQ(errorString.c_str(), ErrMsg);
}
TEST_F(OptionsTest, TestPreprocessOption) {
VerifyPreprocessOption("/T ps_6_0 -P input.hlsl", "input.i", "");
VerifyPreprocessOption("/T ps_6_0 -Fi out.pp -P input.hlsl", "out.pp", "");
VerifyPreprocessOption("/T ps_6_0 -P -Fi out.pp input.hlsl", "out.pp", "");
const char *Warning =
"warning: -P out.pp is deprecated, please use -P -Fi out.pp instead.\n";
VerifyPreprocessOption("/T ps_6_0 -P out.pp input.hlsl", "out.pp", Warning);
VerifyPreprocessOption("/T ps_6_0 input.hlsl -P out.pp ", "out.pp", Warning);
}
static void VerifySerializeDxilFlags(llvm::StringRef command,
uint32_t ExpectFlags) {
std::string errorString;
const llvm::opt::OptTable *optionTable = getHlslOptTable();
llvm::SmallVector<llvm::StringRef, 4> args;
command.split(args, " ", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
args.emplace_back("-Tlib_6_3");
args.emplace_back("input.hlsl");
MainArgs argStrings(args);
DxcOpts dxcOpts;
llvm::raw_string_ostream errorStream(errorString);
int retVal =
ReadDxcOpts(optionTable, DxcFlags, argStrings, dxcOpts, errorStream);
EXPECT_EQ(retVal, 0);
errorStream.flush();
EXPECT_EQ(errorString.empty(), true);
EXPECT_EQ(
static_cast<uint32_t>(hlsl::options::ComputeSerializeDxilFlags(dxcOpts)),
ExpectFlags);
}
static uint32_t CombineFlags(llvm::ArrayRef<SerializeDxilFlags> flags) {
uint32_t result = 0;
for (SerializeDxilFlags f : flags)
result |= static_cast<uint32_t>(f);
return result;
}
struct SerializeDxilFlagsTest {
const char *command;
uint32_t flags;
};
using F = SerializeDxilFlags;
TEST_F(OptionsTest, SerializeDxilFlags) {
// Test cases for SerializeDxilFlags
// These cases are generated by group flags and do a full combination.
// [("-Qstrip_rootsignature", {"F::StripRootSignature"}),\
// ("", set())]
// [("-Qkeep_reflect_in_dxil", set()),\
// ("", {"F::StripReflectionFromDxilPart"})]
// [("-Qstrip_reflect", {}), \
// ("", {"F::IncludeReflectionPart"})]
// [("-Zss -Zs", {"F::IncludeDebugNamePart","F::DebugNameDependOnSource"}),\
// ("-Zsb", {"F::IncludeDebugNamePart"}), \
// ("-FdDbgName.pdb", {"F::IncludeDebugNamePart"}), \
// ("-Zi", {"F::IncludeDebugNamePart"}), \
// ("-Zsb -Qembed_debug -Zi",
// {"F::IncludeDebugInfoPart","F::IncludeDebugNamePart"}), \
// ("-FdDbgName.pdb -Qembed_debug -Zi",
// {"F::IncludeDebugInfoPart","F::IncludeDebugNamePart"}), \
// ("", set())]
SerializeDxilFlagsTest Tests[] = {
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Qstrip_reflect -Zss -Zs",
CombineFlags({F::IncludeDebugNamePart, F::DebugNameDependOnSource,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Qstrip_reflect -Zsb",
CombineFlags({F::IncludeDebugNamePart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Qstrip_reflect "
"-FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Qstrip_reflect -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Qstrip_reflect -Zsb "
"-Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeDebugInfoPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Qstrip_reflect "
"-FdDbgName.pdb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeDebugInfoPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Qstrip_reflect ",
CombineFlags({F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Zss -Zs",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::DebugNameDependOnSource, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Zsb",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -Zsb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::IncludeDebugInfoPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil -FdDbgName.pdb "
"-Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::IncludeDebugInfoPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qkeep_reflect_in_dxil ",
CombineFlags({F::IncludeReflectionPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qstrip_reflect -Zss -Zs",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::DebugNameDependOnSource, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qstrip_reflect -Zsb",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qstrip_reflect -FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qstrip_reflect -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Qstrip_reflect -Zsb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeDebugInfoPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qstrip_reflect -FdDbgName.pdb -Qembed_debug "
"-Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeDebugInfoPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Qstrip_reflect ",
CombineFlags({F::StripReflectionFromDxilPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Zss -Zs",
CombineFlags({F::IncludeReflectionPart, F::IncludeDebugNamePart,
F::StripReflectionFromDxilPart, F::DebugNameDependOnSource,
F::StripRootSignature})},
{"-Qstrip_rootsignature -Zsb",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::StripReflectionFromDxilPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::StripReflectionFromDxilPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::StripReflectionFromDxilPart, F::StripRootSignature})},
{"-Qstrip_rootsignature -Zsb -Qembed_debug -Zi",
CombineFlags({F::IncludeReflectionPart, F::IncludeDebugNamePart,
F::StripReflectionFromDxilPart, F::IncludeDebugInfoPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature -FdDbgName.pdb -Qembed_debug -Zi",
CombineFlags({F::IncludeReflectionPart, F::IncludeDebugNamePart,
F::StripReflectionFromDxilPart, F::IncludeDebugInfoPart,
F::StripRootSignature})},
{"-Qstrip_rootsignature ",
CombineFlags({F::IncludeReflectionPart, F::StripReflectionFromDxilPart,
F::StripRootSignature})},
{"-Qkeep_reflect_in_dxil -Qstrip_reflect -Zss -Zs",
CombineFlags({F::IncludeDebugNamePart, F::DebugNameDependOnSource})},
{"-Qkeep_reflect_in_dxil -Qstrip_reflect -Zsb",
CombineFlags({F::IncludeDebugNamePart})},
{"-Qkeep_reflect_in_dxil -Qstrip_reflect -FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart})},
{"-Qkeep_reflect_in_dxil -Qstrip_reflect -Zi",
CombineFlags({F::IncludeDebugNamePart})},
{"-Qkeep_reflect_in_dxil -Qstrip_reflect -Zsb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeDebugInfoPart})},
{"-Qkeep_reflect_in_dxil -Qstrip_reflect -FdDbgName.pdb -Qembed_debug "
"-Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeDebugInfoPart})},
{"-Qkeep_reflect_in_dxil -Qstrip_reflect ",
CombineFlags({SerializeDxilFlags::None})},
{"-Qkeep_reflect_in_dxil -Zss -Zs",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::DebugNameDependOnSource})},
{"-Qkeep_reflect_in_dxil -Zsb",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart})},
{"-Qkeep_reflect_in_dxil -FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart})},
{"-Qkeep_reflect_in_dxil -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart})},
{"-Qkeep_reflect_in_dxil -Zsb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::IncludeDebugInfoPart})},
{"-Qkeep_reflect_in_dxil -FdDbgName.pdb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::IncludeReflectionPart,
F::IncludeDebugInfoPart})},
{"-Qkeep_reflect_in_dxil ", CombineFlags({F::IncludeReflectionPart})},
{"-Qstrip_reflect -Zss -Zs",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::DebugNameDependOnSource})},
{"-Qstrip_reflect -Zsb",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart})},
{"-Qstrip_reflect -FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart})},
{"-Qstrip_reflect -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart})},
{"-Qstrip_reflect -Zsb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeDebugInfoPart})},
{"-Qstrip_reflect -FdDbgName.pdb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeDebugInfoPart})},
{"-Qstrip_reflect ", CombineFlags({F::StripReflectionFromDxilPart})},
{"-Zss -Zs",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::DebugNameDependOnSource, F::IncludeReflectionPart})},
{"-Zsb",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeReflectionPart})},
{"-FdDbgName.pdb",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeReflectionPart})},
{"-Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeReflectionPart})},
{"-Zsb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeDebugInfoPart, F::IncludeReflectionPart})},
{"-FdDbgName.pdb -Qembed_debug -Zi",
CombineFlags({F::IncludeDebugNamePart, F::StripReflectionFromDxilPart,
F::IncludeDebugInfoPart, F::IncludeReflectionPart})},
{"", CombineFlags(
{F::StripReflectionFromDxilPart, F::IncludeReflectionPart})}};
for (const auto &T : Tests) {
VerifySerializeDxilFlags(T.command, T.flags);
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/PixTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// PixTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for the PIX-specific components //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef UNICODE
#define UNICODE
#endif
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/DxilContainer/DxilRuntimeReflection.h"
#include "dxc/DxilRootSignature/DxilRootSignature.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#include "dxc/dxcpix.h"
#ifdef _WIN32
#include <atlfile.h>
#endif
#include "dxc/DXIL/DxilModule.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HLSLTestData.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/HLSLOptions.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/Support/microcom.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSlotTracker.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include <fstream>
#include <../lib/DxilDia/DxcPixLiveVariables_FragmentIterator.h>
#include <dxc/DxilPIXPasses/DxilPIXVirtualRegisters.h>
#include "PixTestUtils.h"
using namespace std;
using namespace hlsl;
using namespace hlsl_test;
using namespace pix_test;
static std::vector<std::string> Tokenize(const std::string &str,
const char *delimiters) {
std::vector<std::string> tokens;
std::string copy = str;
for (auto i = strtok(©[0], delimiters); i != nullptr;
i = strtok(nullptr, delimiters)) {
tokens.push_back(i);
}
return tokens;
}
#ifdef _WIN32
class PixTest {
#else
class PixTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(PixTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
TEST_METHOD(DebugUAV_CS_6_1)
TEST_METHOD(DebugUAV_CS_6_2)
TEST_METHOD(DebugUAV_lib_6_3_through_6_8)
TEST_METHOD(CompileDebugDisasmPDB)
TEST_METHOD(AddToASPayload)
TEST_METHOD(AddToASGroupSharedPayload)
TEST_METHOD(AddToASGroupSharedPayload_MeshletCullSample)
TEST_METHOD(SignatureModification_Empty)
TEST_METHOD(SignatureModification_VertexIdAlready)
TEST_METHOD(SignatureModification_SomethingElseFirst)
TEST_METHOD(PixStructAnnotation_Lib_DualRaygen)
TEST_METHOD(PixStructAnnotation_Lib_RaygenAllocaStructAlignment)
TEST_METHOD(PixStructAnnotation_Simple)
TEST_METHOD(PixStructAnnotation_CopiedStruct)
TEST_METHOD(PixStructAnnotation_MixedSizes)
TEST_METHOD(PixStructAnnotation_StructWithinStruct)
TEST_METHOD(PixStructAnnotation_1DArray)
TEST_METHOD(PixStructAnnotation_2DArray)
TEST_METHOD(PixStructAnnotation_EmbeddedArray)
TEST_METHOD(PixStructAnnotation_FloatN)
TEST_METHOD(PixStructAnnotation_SequentialFloatN)
TEST_METHOD(PixStructAnnotation_EmbeddedFloatN)
TEST_METHOD(PixStructAnnotation_Matrix)
TEST_METHOD(PixStructAnnotation_MemberFunction)
TEST_METHOD(PixStructAnnotation_BigMess)
TEST_METHOD(PixStructAnnotation_AlignedFloat4Arrays)
TEST_METHOD(PixStructAnnotation_Inheritance)
TEST_METHOD(PixStructAnnotation_ResourceAsMember)
TEST_METHOD(PixStructAnnotation_WheresMyDbgValue)
TEST_METHOD(VirtualRegisters_InstructionCounts)
TEST_METHOD(VirtualRegisters_AlignedOffsets)
TEST_METHOD(RootSignatureUpgrade_SubObjects)
TEST_METHOD(RootSignatureUpgrade_Annotation)
TEST_METHOD(DxilPIXDXRInvocationsLog_SanityTest)
TEST_METHOD(DebugInstrumentation_TextOutput)
TEST_METHOD(DebugInstrumentation_BlockReport)
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
HRESULT CreateContainerBuilder(IDxcContainerBuilder **ppResult) {
return m_dllSupport.CreateInstance(CLSID_DxcContainerBuilder, ppResult);
}
std::string GetOption(std::string &cmd, char *opt) {
std::string option = cmd.substr(cmd.find(opt));
option = option.substr(option.find_first_of(' '));
option = option.substr(option.find_first_not_of(' '));
return option.substr(0, option.find_first_of(' '));
}
CComPtr<IDxcBlob> ExtractDxilPart(IDxcBlob *pProgram) {
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
const hlsl::DxilContainerHeader *pContainer = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_IS_NOT_NULL(pContainer);
hlsl::DxilPartIterator partIter =
std::find_if(hlsl::begin(pContainer), hlsl::end(pContainer),
hlsl::DxilPartIsType(hlsl::DFCC_DXIL));
const hlsl::DxilProgramHeader *pProgramHeader =
(const hlsl::DxilProgramHeader *)hlsl::GetDxilPartData(*partIter);
uint32_t bitcodeLength;
const char *pBitcode;
CComPtr<IDxcBlob> pDxilBits;
hlsl::GetDxilProgramBitcode(pProgramHeader, &pBitcode, &bitcodeLength);
VERIFY_SUCCEEDED(pLib->CreateBlobFromBlob(
pProgram, pBitcode - (char *)pProgram->GetBufferPointer(),
bitcodeLength, &pDxilBits));
return pDxilBits;
}
PassOutput RunValueToDeclarePass(IDxcBlob *dxil, int startingLineNumber = 0) {
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(L"-opt-mod-passes");
Options.push_back(L"-dxil-dbg-value-to-dbg-declare");
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
dxil, Options.data(), Options.size(), &pOptimizedModule, &pText));
std::string outputText;
if (pText->GetBufferSize() != 0) {
outputText = reinterpret_cast<const char *>(pText->GetBufferPointer());
}
return {
std::move(pOptimizedModule), {}, Tokenize(outputText.c_str(), "\n")};
}
PassOutput RunDebugPass(IDxcBlob *dxil, int UAVSize = 1024 * 1024) {
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(L"-opt-mod-passes");
Options.push_back(L"-dxil-dbg-value-to-dbg-declare");
Options.push_back(L"-dxil-annotate-with-virtual-regs");
std::wstring debugArg =
L"-hlsl-dxil-debug-instrumentation,UAVSize=" + std::to_wstring(UAVSize);
Options.push_back(debugArg.c_str());
Options.push_back(L"-viewid-state");
Options.push_back(L"-hlsl-dxilemit");
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
dxil, Options.data(), Options.size(), &pOptimizedModule, &pText));
std::string outputText = BlobToUtf8(pText);
return {
std::move(pOptimizedModule), {}, Tokenize(outputText.c_str(), "\n")};
}
CComPtr<IDxcBlob> FindModule(hlsl::DxilFourCC fourCC, IDxcBlob *pSource) {
const UINT32 BC_C0DE = ((INT32)(INT8)'B' | (INT32)(INT8)'C' << 8 |
(INT32)0xDEC0 << 16); // BC0xc0de in big endian
const char *pBitcode = nullptr;
const hlsl::DxilPartHeader *pDxilPartHeader =
(hlsl::DxilPartHeader *)
pSource->GetBufferPointer(); // Initialize assuming that source is
// starting with DXIL part
if (BC_C0DE == *(UINT32 *)pSource->GetBufferPointer()) {
return pSource;
}
if (hlsl::IsValidDxilContainer(
(hlsl::DxilContainerHeader *)pSource->GetBufferPointer(),
pSource->GetBufferSize())) {
hlsl::DxilContainerHeader *pDxilContainerHeader =
(hlsl::DxilContainerHeader *)pSource->GetBufferPointer();
pDxilPartHeader =
*std::find_if(begin(pDxilContainerHeader), end(pDxilContainerHeader),
hlsl::DxilPartIsType(fourCC));
}
if (fourCC == pDxilPartHeader->PartFourCC) {
UINT32 pBlobSize;
const hlsl::DxilProgramHeader *pDxilProgramHeader =
(const hlsl::DxilProgramHeader *)(pDxilPartHeader + 1);
hlsl::GetDxilProgramBitcode(pDxilProgramHeader, &pBitcode, &pBlobSize);
UINT32 offset =
(UINT32)(pBitcode - (const char *)pSource->GetBufferPointer());
CComPtr<IDxcLibrary> library;
IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
CComPtr<IDxcBlob> targetBlob;
library->CreateBlobFromBlob(pSource, offset, pBlobSize, &targetBlob);
return targetBlob;
}
return {};
}
void ReplaceDxilBlobPart(const void *originalShaderBytecode,
SIZE_T originalShaderLength, IDxcBlob *pNewDxilBlob,
IDxcBlob **ppNewShaderOut) {
CComPtr<IDxcLibrary> pLibrary;
IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
CComPtr<IDxcBlob> pNewContainer;
// Use the container assembler to build a new container from the
// recently-modified DXIL bitcode. This container will contain new copies of
// things like input signature etc., which will supersede the ones from the
// original compiled shader's container.
{
CComPtr<IDxcAssembler> pAssembler;
IFT(m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
CComPtr<IDxcOperationResult> pAssembleResult;
VERIFY_SUCCEEDED(
pAssembler->AssembleToContainer(pNewDxilBlob, &pAssembleResult));
CComPtr<IDxcBlobEncoding> pAssembleErrors;
VERIFY_SUCCEEDED(pAssembleResult->GetErrorBuffer(&pAssembleErrors));
if (pAssembleErrors && pAssembleErrors->GetBufferSize() != 0) {
OutputDebugStringA(
static_cast<LPCSTR>(pAssembleErrors->GetBufferPointer()));
VERIFY_SUCCEEDED(E_FAIL);
}
VERIFY_SUCCEEDED(pAssembleResult->GetResult(&pNewContainer));
}
// Now copy over the blobs from the original container that won't have been
// invalidated by changing the shader code itself, using the container
// reflection API
{
// Wrap the original code in a container blob
CComPtr<IDxcBlobEncoding> pContainer;
VERIFY_SUCCEEDED(pLibrary->CreateBlobWithEncodingFromPinned(
static_cast<LPBYTE>(const_cast<void *>(originalShaderBytecode)),
static_cast<UINT32>(originalShaderLength), CP_ACP, &pContainer));
CComPtr<IDxcContainerReflection> pReflection;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&pReflection));
// Load the reflector from the original shader
VERIFY_SUCCEEDED(pReflection->Load(pContainer));
UINT32 partIndex;
if (SUCCEEDED(pReflection->FindFirstPartKind(hlsl::DFCC_PrivateData,
&partIndex))) {
CComPtr<IDxcBlob> pPart;
VERIFY_SUCCEEDED(pReflection->GetPartContent(partIndex, &pPart));
CComPtr<IDxcContainerBuilder> pContainerBuilder;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerBuilder,
&pContainerBuilder));
VERIFY_SUCCEEDED(pContainerBuilder->Load(pNewContainer));
VERIFY_SUCCEEDED(
pContainerBuilder->AddPart(hlsl::DFCC_PrivateData, pPart));
CComPtr<IDxcOperationResult> pBuildResult;
VERIFY_SUCCEEDED(pContainerBuilder->SerializeContainer(&pBuildResult));
CComPtr<IDxcBlobEncoding> pBuildErrors;
VERIFY_SUCCEEDED(pBuildResult->GetErrorBuffer(&pBuildErrors));
if (pBuildErrors && pBuildErrors->GetBufferSize() != 0) {
OutputDebugStringA(
reinterpret_cast<LPCSTR>(pBuildErrors->GetBufferPointer()));
VERIFY_SUCCEEDED(E_FAIL);
}
VERIFY_SUCCEEDED(pBuildResult->GetResult(&pNewContainer));
}
}
*ppNewShaderOut = pNewContainer.Detach();
}
class ModuleAndHangersOn {
std::unique_ptr<llvm::LLVMContext> llvmContext;
std::unique_ptr<llvm::Module> llvmModule;
DxilModule *dxilModule;
public:
ModuleAndHangersOn(IDxcBlob *pBlob) {
// Assume we were given a dxil part first:
const DxilProgramHeader *pProgramHeader =
reinterpret_cast<const DxilProgramHeader *>(
pBlob->GetBufferPointer());
uint32_t partSize = static_cast<uint32_t>(pBlob->GetBufferSize());
// Check if we were given a valid dxil container instead:
const DxilContainerHeader *pContainer = IsDxilContainerLike(
pBlob->GetBufferPointer(), pBlob->GetBufferSize());
if (pContainer != nullptr) {
VERIFY_IS_TRUE(
IsValidDxilContainer(pContainer, pBlob->GetBufferSize()));
// Get Dxil part from container.
DxilPartIterator it =
std::find_if(begin(pContainer), end(pContainer),
DxilPartIsType(DFCC_ShaderDebugInfoDXIL));
VERIFY_IS_FALSE(it == end(pContainer));
pProgramHeader =
reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(*it));
partSize = (*it)->PartSize;
}
VERIFY_IS_TRUE(IsValidDxilProgramHeader(pProgramHeader, partSize));
// Get a pointer to the llvm bitcode.
const char *pIL;
uint32_t pILLength;
GetDxilProgramBitcode(pProgramHeader, &pIL, &pILLength);
// Parse llvm bitcode into a module.
std::unique_ptr<llvm::MemoryBuffer> pBitcodeBuf(
llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(pIL, pILLength), "",
false));
llvmContext.reset(new llvm::LLVMContext);
llvm::ErrorOr<std::unique_ptr<llvm::Module>> pModule(
llvm::parseBitcodeFile(pBitcodeBuf->getMemBufferRef(), *llvmContext));
if (std::error_code ec = pModule.getError()) {
VERIFY_FAIL();
}
llvmModule = std::move(pModule.get());
dxilModule = DxilModule::TryGetDxilModule(llvmModule.get());
}
DxilModule &GetDxilModule() { return *dxilModule; }
};
struct AggregateOffsetAndSize {
unsigned countOfMembers;
unsigned offset;
unsigned size;
};
struct AllocaWrite {
std::string memberName;
uint32_t regBase;
uint32_t regSize;
uint64_t index;
};
struct TestableResults {
std::vector<AggregateOffsetAndSize> OffsetAndSizes;
std::vector<AllocaWrite> AllocaWrites;
};
TestableResults TestStructAnnotationCase(const char *hlsl,
const wchar_t *optimizationLevel,
bool validateCoverage = true,
const wchar_t *profile = L"as_6_5");
void ValidateAllocaWrite(std::vector<AllocaWrite> const &allocaWrites,
size_t index, const char *name);
CComPtr<IDxcBlob> RunShaderAccessTrackingPass(IDxcBlob *blob);
std::string RunDxilPIXAddTidToAmplificationShaderPayloadPass(IDxcBlob *blob);
CComPtr<IDxcBlob> RunDxilPIXMeshShaderOutputPass(IDxcBlob *blob);
CComPtr<IDxcBlob> RunDxilPIXDXRInvocationsLog(IDxcBlob *blob);
void TestPixUAVCase(char const *hlsl, wchar_t const *model,
wchar_t const *entry);
};
bool PixTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
void PixTest::TestPixUAVCase(char const *hlsl, wchar_t const *model,
wchar_t const *entry) {
auto mod = Compile(m_dllSupport, hlsl, model, {}, entry);
CComPtr<IDxcBlob> dxilPart = FindModule(DFCC_ShaderDebugInfoDXIL, mod);
PassOutput passOutput = RunDebugPass(dxilPart);
CComPtr<IDxcBlob> modifiedDxilContainer;
ReplaceDxilBlobPart(mod->GetBufferPointer(), mod->GetBufferSize(),
passOutput.blob, &modifiedDxilContainer);
ModuleAndHangersOn moduleEtc(modifiedDxilContainer);
auto &compilerGeneratedUAV = moduleEtc.GetDxilModule().GetUAV(0);
auto &pixDebugGeneratedUAV = moduleEtc.GetDxilModule().GetUAV(1);
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetClass(),
pixDebugGeneratedUAV.GetClass());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetKind(),
pixDebugGeneratedUAV.GetKind());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetHLSLType(),
pixDebugGeneratedUAV.GetHLSLType());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetSampleCount(),
pixDebugGeneratedUAV.GetSampleCount());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetElementStride(),
pixDebugGeneratedUAV.GetElementStride());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetBaseAlignLog2(),
pixDebugGeneratedUAV.GetBaseAlignLog2());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetCompType(),
pixDebugGeneratedUAV.GetCompType());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetSamplerFeedbackType(),
pixDebugGeneratedUAV.GetSamplerFeedbackType());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.IsGloballyCoherent(),
pixDebugGeneratedUAV.IsGloballyCoherent());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.HasCounter(),
pixDebugGeneratedUAV.HasCounter());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.HasAtomic64Use(),
pixDebugGeneratedUAV.HasAtomic64Use());
VERIFY_ARE_EQUAL(compilerGeneratedUAV.GetGlobalSymbol()->getType(),
pixDebugGeneratedUAV.GetGlobalSymbol()->getType());
}
TEST_F(PixTest, DebugUAV_CS_6_1) {
const char *hlsl = R"(
RWByteAddressBuffer RawUAV : register(u0);
[numthreads(1, 1, 1)]
void CSMain()
{
RawUAV.Store(0, RawUAV.Load(4));
}
)";
TestPixUAVCase(hlsl, L"cs_6_1", L"CSMain");
}
TEST_F(PixTest, DebugUAV_CS_6_2) {
const char *hlsl = R"(
RWByteAddressBuffer RawUAV : register(u0);
[numthreads(1, 1, 1)]
void CSMain()
{
RawUAV.Store(0, RawUAV.Load(4));
}
)";
// In 6.2, rawBufferLoad replaced bufferLoad for UAVs, but we don't
// expect this test to notice the difference. We just test 6.2
TestPixUAVCase(hlsl, L"cs_6_2", L"CSMain");
}
TEST_F(PixTest, DebugUAV_lib_6_3_through_6_8) {
const char *hlsl = R"(
RWByteAddressBuffer RawUAV : register(u0);
struct [raypayload] Payload
{
double a : read(caller, closesthit, anyhit) : write(caller, miss, closesthit);
};
[shader("miss")]
void Miss( inout Payload payload )
{
RawUAV.Store(0, RawUAV.Load(4));
payload.a = 4.2;
})";
TestPixUAVCase(hlsl, L"lib_6_3", L"");
TestPixUAVCase(hlsl, L"lib_6_4", L"");
TestPixUAVCase(hlsl, L"lib_6_5", L"");
TestPixUAVCase(hlsl, L"lib_6_6", L"");
TestPixUAVCase(hlsl, L"lib_6_7", L"");
TestPixUAVCase(hlsl, L"lib_6_8", L"");
}
TEST_F(PixTest, CompileDebugDisasmPDB) {
const char *hlsl = R"(
[RootSignature("")]
float main(float pos : A) : SV_Target {
float x = abs(pos);
float y = sin(pos);
float z = x + y;
return z;
}
)";
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcCompiler2> pCompiler2;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlob> pPdbBlob;
CComHeapPtr<WCHAR> pDebugName;
VERIFY_SUCCEEDED(CreateCompiler(m_dllSupport, &pCompiler));
VERIFY_SUCCEEDED(pCompiler.QueryInterface(&pCompiler2));
CreateBlobFromText(m_dllSupport, hlsl, &pSource);
LPCWSTR args[] = {L"/Zi", L"/Qembed_debug"};
VERIFY_SUCCEEDED(pCompiler2->CompileWithDebug(
pSource, L"source.hlsl", L"main", L"ps_6_0", args, _countof(args),
nullptr, 0, nullptr, &pResult, &pDebugName, &pPdbBlob));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Test that disassembler can consume a PDB container
CComPtr<IDxcBlobEncoding> pDisasm;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pPdbBlob, &pDisasm));
}
CComPtr<IDxcBlob> PixTest::RunShaderAccessTrackingPass(IDxcBlob *blob) {
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(L"-opt-mod-passes");
Options.push_back(L"-hlsl-dxil-pix-shader-access-instrumentation,config=");
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
blob, Options.data(), Options.size(), &pOptimizedModule, &pText));
CComPtr<IDxcAssembler> pAssembler;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
CComPtr<IDxcOperationResult> pAssembleResult;
VERIFY_SUCCEEDED(
pAssembler->AssembleToContainer(pOptimizedModule, &pAssembleResult));
HRESULT hr;
VERIFY_SUCCEEDED(pAssembleResult->GetStatus(&hr));
VERIFY_SUCCEEDED(hr);
CComPtr<IDxcBlob> pNewContainer;
VERIFY_SUCCEEDED(pAssembleResult->GetResult(&pNewContainer));
return pNewContainer;
}
CComPtr<IDxcBlob> PixTest::RunDxilPIXMeshShaderOutputPass(IDxcBlob *blob) {
CComPtr<IDxcBlob> dxil = FindModule(DFCC_ShaderDebugInfoDXIL, blob);
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(L"-opt-mod-passes");
Options.push_back(L"-hlsl-dxil-pix-meshshader-output-instrumentation,expand-"
L"payload=1,UAVSize=8192");
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
dxil, Options.data(), Options.size(), &pOptimizedModule, &pText));
std::string outputText;
if (pText->GetBufferSize() != 0) {
outputText = reinterpret_cast<const char *>(pText->GetBufferPointer());
}
return pOptimizedModule;
}
CComPtr<IDxcBlob> PixTest::RunDxilPIXDXRInvocationsLog(IDxcBlob *blob) {
CComPtr<IDxcBlob> dxil = FindModule(DFCC_ShaderDebugInfoDXIL, blob);
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(
L"-hlsl-dxil-pix-dxr-invocations-log,maxNumEntriesInLog=24");
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
dxil, Options.data(), Options.size(), &pOptimizedModule, &pText));
std::string outputText;
if (pText->GetBufferSize() != 0) {
outputText = reinterpret_cast<const char *>(pText->GetBufferPointer());
}
return pOptimizedModule;
}
std::string
PixTest::RunDxilPIXAddTidToAmplificationShaderPayloadPass(IDxcBlob *blob) {
CComPtr<IDxcBlob> dxil = FindModule(DFCC_ShaderDebugInfoDXIL, blob);
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(L"-opt-mod-passes");
Options.push_back(
L"-hlsl-dxil-PIX-add-tid-to-as-payload,dispatchArgY=1,dispatchArgZ=2");
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
dxil, Options.data(), Options.size(), &pOptimizedModule, &pText));
std::string outputText;
if (pText->GetBufferSize() != 0) {
outputText = reinterpret_cast<const char *>(pText->GetBufferPointer());
}
return outputText;
}
TEST_F(PixTest, AddToASPayload) {
const char *hlsl = R"(
struct MyPayload
{
float f1;
float f2;
};
[numthreads(1, 1, 1)]
void ASMain(uint gid : SV_GroupID)
{
MyPayload payload;
payload.f1 = (float)gid / 4.f;
payload.f2 = (float)gid * 4.f;
DispatchMesh(1, 1, 1, payload);
}
struct PSInput
{
float4 position : SV_POSITION;
};
[outputtopology("triangle")]
[numthreads(3,1,1)]
void MSMain(
in payload MyPayload small,
in uint tid : SV_GroupThreadID,
in uint3 dtid : SV_DispatchThreadID,
out vertices PSInput verts[3],
out indices uint3 triangles[1])
{
SetMeshOutputCounts(3, 1);
verts[tid].position = float4(small.f1, small.f2, 0, 0);
triangles[0] = uint3(0, 1, 2);
}
)";
auto as = Compile(m_dllSupport, hlsl, L"as_6_6", {}, L"ASMain");
RunDxilPIXAddTidToAmplificationShaderPayloadPass(as);
auto ms = Compile(m_dllSupport, hlsl, L"ms_6_6", {}, L"MSMain");
RunDxilPIXMeshShaderOutputPass(ms);
}
unsigned FindOrAddVSInSignatureElementForInstanceOrVertexID(
hlsl::DxilSignature &InputSignature, hlsl::DXIL::SemanticKind semanticKind);
TEST_F(PixTest, SignatureModification_Empty) {
DxilSignature sig(DXIL::ShaderKind::Vertex, DXIL::SignatureKind::Input,
false);
FindOrAddVSInSignatureElementForInstanceOrVertexID(
sig, DXIL::SemanticKind::InstanceID);
FindOrAddVSInSignatureElementForInstanceOrVertexID(
sig, DXIL::SemanticKind::VertexID);
VERIFY_ARE_EQUAL(2ull, sig.GetElements().size());
VERIFY_ARE_EQUAL(sig.GetElement(0).GetKind(), DXIL::SemanticKind::InstanceID);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetCols(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetRows(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetStartCol(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetStartRow(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetKind(), DXIL::SemanticKind::VertexID);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetCols(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetRows(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetStartCol(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetStartRow(), 1);
}
TEST_F(PixTest, SignatureModification_VertexIdAlready) {
DxilSignature sig(DXIL::ShaderKind::Vertex, DXIL::SignatureKind::Input,
false);
auto AddedElement =
llvm::make_unique<DxilSignatureElement>(DXIL::SigPointKind::VSIn);
AddedElement->Initialize(
Semantic::Get(DXIL::SemanticKind::VertexID)->GetName(),
hlsl::CompType::getU32(), DXIL::InterpolationMode::Constant, 1, 1, 0, 0,
0, {0});
AddedElement->SetKind(DXIL::SemanticKind::VertexID);
AddedElement->SetUsageMask(1);
sig.AppendElement(std::move(AddedElement));
FindOrAddVSInSignatureElementForInstanceOrVertexID(
sig, DXIL::SemanticKind::InstanceID);
FindOrAddVSInSignatureElementForInstanceOrVertexID(
sig, DXIL::SemanticKind::VertexID);
VERIFY_ARE_EQUAL(2ull, sig.GetElements().size());
VERIFY_ARE_EQUAL(sig.GetElement(0).GetKind(), DXIL::SemanticKind::VertexID);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetCols(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetRows(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetStartCol(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(0).GetStartRow(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetKind(), DXIL::SemanticKind::InstanceID);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetCols(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetRows(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetStartCol(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetStartRow(), 1);
}
TEST_F(PixTest, SignatureModification_SomethingElseFirst) {
DxilSignature sig(DXIL::ShaderKind::Vertex, DXIL::SignatureKind::Input,
false);
auto AddedElement =
llvm::make_unique<DxilSignatureElement>(DXIL::SigPointKind::VSIn);
AddedElement->Initialize("One", hlsl::CompType::getU32(),
DXIL::InterpolationMode::Constant, 1, 6, 0, 0, 0,
{0});
AddedElement->SetKind(DXIL::SemanticKind::Arbitrary);
AddedElement->SetUsageMask(1);
sig.AppendElement(std::move(AddedElement));
FindOrAddVSInSignatureElementForInstanceOrVertexID(
sig, DXIL::SemanticKind::InstanceID);
FindOrAddVSInSignatureElementForInstanceOrVertexID(
sig, DXIL::SemanticKind::VertexID);
VERIFY_ARE_EQUAL(3ull, sig.GetElements().size());
// Not gonna check the first one cuz that would just be grading our own
// homework
VERIFY_ARE_EQUAL(sig.GetElement(1).GetKind(), DXIL::SemanticKind::InstanceID);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetCols(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetRows(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetStartCol(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(1).GetStartRow(), 1);
VERIFY_ARE_EQUAL(sig.GetElement(2).GetKind(), DXIL::SemanticKind::VertexID);
VERIFY_ARE_EQUAL(sig.GetElement(2).GetCols(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(2).GetRows(), 1u);
VERIFY_ARE_EQUAL(sig.GetElement(2).GetStartCol(), 0);
VERIFY_ARE_EQUAL(sig.GetElement(2).GetStartRow(), 2);
}
TEST_F(PixTest, AddToASGroupSharedPayload) {
const char *hlsl = R"(
struct Contained
{
uint j;
float af[3];
};
struct Bigger
{
half h;
void Init() { h = 1.f; }
Contained a[2];
};
struct MyPayload
{
uint i;
Bigger big[3];
};
groupshared MyPayload payload;
[numthreads(1, 1, 1)]
void main(uint gid : SV_GroupID)
{
DispatchMesh(1, 1, 1, payload);
}
)";
auto as = Compile(m_dllSupport, hlsl, L"as_6_6", {L"-Od"}, L"main");
RunDxilPIXAddTidToAmplificationShaderPayloadPass(as);
}
TEST_F(PixTest, AddToASGroupSharedPayload_MeshletCullSample) {
const char *hlsl = R"(
struct MyPayload
{
uint i[32];
};
groupshared MyPayload payload;
[numthreads(1, 1, 1)]
void main(uint gid : SV_GroupID)
{
DispatchMesh(1, 1, 1, payload);
}
)";
auto as = Compile(m_dllSupport, hlsl, L"as_6_6", {L"-Od"}, L"main");
RunDxilPIXAddTidToAmplificationShaderPayloadPass(as);
}
static llvm::DIType *PeelTypedefs(llvm::DIType *diTy) {
using namespace llvm;
const llvm::DITypeIdentifierMap EmptyMap;
while (1) {
DIDerivedType *diDerivedTy = dyn_cast<DIDerivedType>(diTy);
if (!diDerivedTy)
return diTy;
switch (diTy->getTag()) {
case dwarf::DW_TAG_member:
case dwarf::DW_TAG_inheritance:
case dwarf::DW_TAG_typedef:
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_const_type:
case dwarf::DW_TAG_restrict_type:
diTy = diDerivedTy->getBaseType().resolve(EmptyMap);
break;
default:
return diTy;
}
}
return diTy;
}
static unsigned GetDITypeSizeInBits(llvm::DIType *diTy) {
return PeelTypedefs(diTy)->getSizeInBits();
}
static unsigned GetDITypeAlignmentInBits(llvm::DIType *diTy) {
return PeelTypedefs(diTy)->getAlignInBits();
}
static bool FindStructMemberFromStore(llvm::StoreInst *S,
std::string *OutMemberName) {
using namespace llvm;
Value *Ptr = S->getPointerOperand();
AllocaInst *Alloca = nullptr;
auto &DL = S->getModule()->getDataLayout();
unsigned OffsetInAlloca = 0;
while (Ptr) {
if (auto AI = dyn_cast<AllocaInst>(Ptr)) {
Alloca = AI;
break;
} else if (auto Gep = dyn_cast<GEPOperator>(Ptr)) {
if (Gep->getNumIndices() < 2 || !Gep->hasAllConstantIndices() ||
0 != cast<ConstantInt>(Gep->getOperand(1))->getLimitedValue()) {
return false;
}
auto GepSrcPtr = Gep->getPointerOperand();
Type *GepSrcPtrTy = GepSrcPtr->getType()->getPointerElementType();
Type *PeelingType = GepSrcPtrTy;
for (unsigned i = 1; i < Gep->getNumIndices(); i++) {
uint64_t Idx =
cast<ConstantInt>(Gep->getOperand(1 + i))->getLimitedValue();
if (PeelingType->isStructTy()) {
auto StructTy = cast<StructType>(PeelingType);
unsigned Offset =
DL.getStructLayout(StructTy)->getElementOffsetInBits(Idx);
OffsetInAlloca += Offset;
PeelingType = StructTy->getElementType(Idx);
} else if (PeelingType->isVectorTy()) {
OffsetInAlloca +=
DL.getTypeSizeInBits(PeelingType->getVectorElementType()) * Idx;
PeelingType = PeelingType->getVectorElementType();
} else if (PeelingType->isArrayTy()) {
OffsetInAlloca +=
DL.getTypeSizeInBits(PeelingType->getArrayElementType()) * Idx;
PeelingType = PeelingType->getArrayElementType();
} else {
return false;
}
}
Ptr = GepSrcPtr;
} else {
return false;
}
}
// If there's not exactly one dbg.* inst, give up for now.
if (hlsl::dxilutil::mdv_user_empty(Alloca) ||
std::next(hlsl::dxilutil::mdv_users_begin(Alloca)) !=
hlsl::dxilutil::mdv_users_end(Alloca)) {
return false;
}
auto DI = dyn_cast<DbgDeclareInst>(*hlsl::dxilutil::mdv_users_begin(Alloca));
if (!DI)
return false;
DILocalVariable *diVar = DI->getVariable();
DIExpression *diExpr = DI->getExpression();
const llvm::DITypeIdentifierMap EmptyMap;
DIType *diType = diVar->getType().resolve(EmptyMap);
unsigned MemberOffset = OffsetInAlloca;
if (diExpr->isBitPiece()) {
MemberOffset += diExpr->getBitPieceOffset();
}
diType = PeelTypedefs(diType);
if (!isa<DICompositeType>(diType))
return false;
unsigned OffsetInDI = 0;
std::string MemberName;
//=====================================================
// Find the correct member based on size
while (diType) {
diType = PeelTypedefs(diType);
if (DICompositeType *diCompType = dyn_cast<DICompositeType>(diType)) {
if (diCompType->getTag() == dwarf::DW_TAG_structure_type ||
diCompType->getTag() == dwarf::DW_TAG_class_type) {
bool FoundCompositeMember = false;
for (DINode *Elem : diCompType->getElements()) {
auto diElemType = dyn_cast<DIType>(Elem);
if (!diElemType)
return false;
StringRef CurMemberName;
if (diElemType->getTag() == dwarf::DW_TAG_member) {
CurMemberName = diElemType->getName();
} else if (diElemType->getTag() == dwarf::DW_TAG_inheritance) {
} else {
return false;
}
unsigned CompositeMemberSize = GetDITypeSizeInBits(diElemType);
unsigned CompositeMemberAlignment =
GetDITypeAlignmentInBits(diElemType);
assert(CompositeMemberAlignment);
OffsetInDI =
llvm::RoundUpToAlignment(OffsetInDI, CompositeMemberAlignment);
if (OffsetInDI <= MemberOffset &&
MemberOffset < OffsetInDI + CompositeMemberSize) {
diType = diElemType;
if (CurMemberName.size()) {
if (MemberName.size())
MemberName += ".";
MemberName += CurMemberName;
}
FoundCompositeMember = true;
break;
}
// TODO: How will we match up the padding?
OffsetInDI += CompositeMemberSize;
}
if (!FoundCompositeMember)
return false;
}
// For arrays, just flatten it for now.
// TODO: multi-dimension array
else if (diCompType->getTag() == dwarf::DW_TAG_array_type) {
if (MemberOffset < OffsetInDI ||
MemberOffset >= OffsetInDI + diCompType->getSizeInBits())
return false;
DIType *diArrayElemType = diCompType->getBaseType().resolve(EmptyMap);
{
unsigned CurSize = diCompType->getSizeInBits();
unsigned CurOffset = MemberOffset - OffsetInDI;
for (DINode *SubrangeMD : diCompType->getElements()) {
DISubrange *Range = cast<DISubrange>(SubrangeMD);
unsigned ElemSize = CurSize / Range->getCount();
unsigned Idx = CurOffset / ElemSize;
CurOffset -= ElemSize * Idx;
CurSize = ElemSize;
MemberName += "[";
MemberName += std::to_string(Idx);
MemberName += "]";
}
}
unsigned ArrayElemSize = GetDITypeSizeInBits(diArrayElemType);
unsigned FlattenedIdx = (MemberOffset - OffsetInDI) / ArrayElemSize;
OffsetInDI += FlattenedIdx * ArrayElemSize;
diType = diArrayElemType;
} else {
return false;
}
} else if (DIBasicType *diBasicType = dyn_cast<DIBasicType>(diType)) {
if (OffsetInDI == MemberOffset) {
*OutMemberName = MemberName;
return true;
}
OffsetInDI += diBasicType->getSizeInBits();
return false;
} else {
return false;
}
}
return false;
}
// This function lives in lib\DxilPIXPasses\DxilAnnotateWithVirtualRegister.cpp
// Declared here so we can test it.
uint32_t CountStructMembers(llvm::Type const *pType);
PixTest::TestableResults PixTest::TestStructAnnotationCase(
const char *hlsl, const wchar_t *optimizationLevel, bool validateCoverage,
const wchar_t *profile) {
CComPtr<IDxcBlob> pBlob =
Compile(m_dllSupport, hlsl, profile,
{optimizationLevel, L"-HV", L"2018", L"-enable-16bit-types"});
CComPtr<IDxcBlob> pDxil = FindModule(DFCC_ShaderDebugInfoDXIL, pBlob);
PassOutput passOutput = RunAnnotationPasses(m_dllSupport, pDxil);
auto pAnnotated = passOutput.blob;
CComPtr<IDxcBlob> pAnnotatedContainer;
ReplaceDxilBlobPart(pBlob->GetBufferPointer(), pBlob->GetBufferSize(),
pAnnotated, &pAnnotatedContainer);
#if 0 // handy for debugging
auto disTextW = Disassemble(pAnnotatedContainer);
WEX::Logging::Log::Comment(disTextW.c_str());
#endif
ModuleAndHangersOn moduleEtc(pAnnotatedContainer);
PixTest::TestableResults ret;
// For every dbg.declare, run the member iterator and record what it finds:
auto entryPoints = moduleEtc.GetDxilModule().GetExportedFunctions();
for (auto &entryFunction : entryPoints) {
for (auto &block : entryFunction->getBasicBlockList()) {
for (auto &instruction : block.getInstList()) {
if (auto *dbgDeclare =
llvm::dyn_cast<llvm::DbgDeclareInst>(&instruction)) {
llvm::Value *Address = dbgDeclare->getAddress();
auto *AddressAsAlloca = llvm::dyn_cast<llvm::AllocaInst>(Address);
if (AddressAsAlloca != nullptr) {
auto *Expression = dbgDeclare->getExpression();
std::unique_ptr<dxil_debug_info::MemberIterator> iterator =
dxil_debug_info::CreateMemberIterator(
dbgDeclare,
moduleEtc.GetDxilModule().GetModule()->getDataLayout(),
AddressAsAlloca, Expression);
unsigned int startingBit = 0;
unsigned int coveredBits = 0;
unsigned int memberIndex = 0;
unsigned int memberCount = 0;
while (iterator->Next(&memberIndex)) {
memberCount++;
if (memberIndex == 0) {
startingBit = iterator->OffsetInBits(memberIndex);
coveredBits = iterator->SizeInBits(memberIndex);
} else {
coveredBits = std::max<unsigned int>(
coveredBits, iterator->OffsetInBits(memberIndex) +
iterator->SizeInBits(memberIndex));
}
}
AggregateOffsetAndSize OffsetAndSize = {};
OffsetAndSize.countOfMembers = memberCount;
OffsetAndSize.offset = startingBit;
OffsetAndSize.size = coveredBits;
ret.OffsetAndSizes.push_back(OffsetAndSize);
// Use this independent count of number of struct members to test
// the function that operates on the alloca type:
llvm::Type *pAllocaTy =
AddressAsAlloca->getType()->getElementType();
if (auto *AT = llvm::dyn_cast<llvm::ArrayType>(pAllocaTy)) {
// This is the case where a struct is passed to a function, and
// in these tests there should be only one struct behind the
// pointer.
VERIFY_ARE_EQUAL(AT->getNumElements(), 1u);
pAllocaTy = AT->getArrayElementType();
}
if (auto *ST = llvm::dyn_cast<llvm::StructType>(pAllocaTy)) {
uint32_t countOfMembers = CountStructMembers(ST);
// memberIndex might be greater, because the fragment iterator
// also includes contained derived types as fragments, in
// addition to the members of that contained derived types.
// CountStructMembers only counts the leaf-node types.
VERIFY_ARE_EQUAL(countOfMembers, memberCount);
} else if (pAllocaTy->isFloatingPointTy() ||
pAllocaTy->isIntegerTy()) {
// If there's only one member in the struct in the
// pass-to-function (by pointer) case, then the underlying type
// will have been reduced to the contained type.
VERIFY_ARE_EQUAL(1u, memberCount);
} else {
VERIFY_IS_TRUE(false);
}
}
}
}
}
// The member iterator should find a solid run of bits that is exactly
// covered by exactly one of the members found by the annotation pass:
if (validateCoverage) {
unsigned CurRegIdx = 0;
for (AggregateOffsetAndSize const &cover :
ret.OffsetAndSizes) // For each entry read from member iterators
// and dbg.declares
{
bool found = false;
for (ValueLocation const &valueLocation :
passOutput.valueLocations) // For each allocas and dxil values
{
if (CurRegIdx == (unsigned)valueLocation.base &&
(unsigned)valueLocation.count == cover.countOfMembers) {
VERIFY_IS_FALSE(found);
found = true;
}
}
VERIFY_IS_TRUE(found);
CurRegIdx += cover.countOfMembers;
}
}
// For every store operation to the struct alloca, check that the
// annotation pass correctly determined which alloca
for (auto &block : entryFunction->getBasicBlockList()) {
for (auto &instruction : block.getInstList()) {
if (auto *store = llvm::dyn_cast<llvm::StoreInst>(&instruction)) {
AllocaWrite NewAllocaWrite = {};
if (FindStructMemberFromStore(store, &NewAllocaWrite.memberName)) {
llvm::Value *index;
if (pix_dxil::PixAllocaRegWrite::FromInst(
store, &NewAllocaWrite.regBase, &NewAllocaWrite.regSize,
&index)) {
auto *asInt = llvm::dyn_cast<llvm::ConstantInt>(index);
NewAllocaWrite.index = asInt->getLimitedValue();
ret.AllocaWrites.push_back(NewAllocaWrite);
}
}
}
}
}
}
return ret;
}
void PixTest::ValidateAllocaWrite(std::vector<AllocaWrite> const &allocaWrites,
size_t index, const char *name) {
VERIFY_ARE_EQUAL(index,
allocaWrites[index].regBase + allocaWrites[index].index);
#ifndef NDEBUG
// Compilation may add a prefix to the struct member name:
VERIFY_IS_TRUE(
0 == strncmp(name, allocaWrites[index].memberName.c_str(), strlen(name)));
#endif
}
struct OptimizationChoice {
const wchar_t *Flag;
bool IsOptimized;
};
static const OptimizationChoice OptimizationChoices[] = {
{L"-Od", false},
{L"-O1", true},
};
TEST_F(PixTest, PixStructAnnotation_Lib_DualRaygen) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
RaytracingAccelerationStructure Scene : register(t0, space0);
RWTexture2D<float4> RenderTarget : register(u0);
struct SceneConstantBuffer
{
float4x4 projectionToWorld;
float4 cameraPosition;
float4 lightPosition;
float4 lightAmbientColor;
float4 lightDiffuseColor;
};
ConstantBuffer<SceneConstantBuffer> g_sceneCB : register(b0);
struct RayPayload
{
float4 color;
};
inline void GenerateCameraRay(uint2 index, out float3 origin, out float3 direction)
{
float2 xy = index + 0.5f; // center in the middle of the pixel.
float2 screenPos = xy;// / DispatchRaysDimensions().xy * 2.0 - 1.0;
// Invert Y for DirectX-style coordinates.
screenPos.y = -screenPos.y;
// Unproject the pixel coordinate into a ray.
float4 world = /*mul(*/float4(screenPos, 0, 1)/*, g_sceneCB.projectionToWorld)*/;
//world.xyz /= world.w;
origin = world.xyz; //g_sceneCB.cameraPosition.xyz;
direction = float3(1,0,0);//normalize(world.xyz - origin);
}
void RaygenCommon()
{
float3 rayDir;
float3 origin;
// Generate a ray for a camera pixel corresponding to an index from the dispatched 2D grid.
GenerateCameraRay(DispatchRaysIndex().xy, origin, rayDir);
// Trace the ray.
// Set the ray's extents.
RayDesc ray;
ray.Origin = origin;
ray.Direction = rayDir;
// Set TMin to a non-zero small value to avoid aliasing issues due to floating - point errors.
// TMin should be kept small to prevent missing geometry at close contact areas.
ray.TMin = 0.001;
ray.TMax = 10000.0;
RayPayload payload = { float4(0, 0, 0, 0) };
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);
// Write the raytraced color to the output texture.
// RenderTarget[DispatchRaysIndex().xy] = payload.color;
}
[shader("raygeneration")]
void Raygen0()
{
RaygenCommon();
}
[shader("raygeneration")]
void Raygen1()
{
RaygenCommon();
}
)";
// This is just a crash test until we decide what the right way forward
CComPtr<IDxcBlob> pBlob =
Compile(m_dllSupport, hlsl, L"lib_6_6", {optimization});
CComPtr<IDxcBlob> pDxil = FindModule(DFCC_ShaderDebugInfoDXIL, pBlob);
RunAnnotationPasses(m_dllSupport, pDxil);
}
}
TEST_F(PixTest, PixStructAnnotation_Lib_RaygenAllocaStructAlignment) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RaytracingAccelerationStructure Scene : register(t0, space0);
RWTexture2D<float4> RenderTarget : register(u0);
struct SceneConstantBuffer
{
float4x4 projectionToWorld;
float4 cameraPosition;
float4 lightPosition;
float4 lightAmbientColor;
float4 lightDiffuseColor;
};
ConstantBuffer<SceneConstantBuffer> g_sceneCB : register(b0);
struct RayPayload
{
float4 color;
};
inline void GenerateCameraRay(uint2 index, out float3 origin, out float3 direction)
{
float2 xy = index + 0.5f; // center in the middle of the pixel.
float2 screenPos = xy;// / DispatchRaysDimensions().xy * 2.0 - 1.0;
// Invert Y for DirectX-style coordinates.
screenPos.y = -screenPos.y;
// Unproject the pixel coordinate into a ray.
float4 world = /*mul(*/float4(screenPos, 0, 1)/*, g_sceneCB.projectionToWorld)*/;
//world.xyz /= world.w;
origin = world.xyz; //g_sceneCB.cameraPosition.xyz;
direction = float3(1,0,0);//normalize(world.xyz - origin);
}
void RaygenCommon()
{
float3 rayDir;
float3 origin;
// Generate a ray for a camera pixel corresponding to an index from the dispatched 2D grid.
GenerateCameraRay(DispatchRaysIndex().xy, origin, rayDir);
// Trace the ray.
// Set the ray's extents.
RayDesc ray;
ray.Origin = origin;
ray.Direction = rayDir;
// Set TMin to a non-zero small value to avoid aliasing issues due to floating - point errors.
// TMin should be kept small to prevent missing geometry at close contact areas.
ray.TMin = 0.001;
ray.TMax = 10000.0;
RayPayload payload = { float4(0, 0, 0, 0) };
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);
// Write the raytraced color to the output texture.
// RenderTarget[DispatchRaysIndex().xy] = payload.color;
}
[shader("raygeneration")]
void Raygen()
{
RaygenCommon();
}
)";
auto Testables = TestStructAnnotationCase(hlsl, L"-Od", true, L"lib_6_6");
// Built-in type "RayDesc" has this structure: struct { float3 Origin; float
// TMin; float3 Direction; float TMax; } This is 8 floats, with members at
// offsets 0,3,4,7 respectively.
auto FindAtLeastOneOf = [=](char const *name, uint32_t index) {
VERIFY_IS_TRUE(std::find_if(Testables.AllocaWrites.begin(),
Testables.AllocaWrites.end(),
[&name, &index](AllocaWrite const &aw) {
return 0 == strcmp(aw.memberName.c_str(),
name) &&
aw.index == index;
}) != Testables.AllocaWrites.end());
};
FindAtLeastOneOf("Origin.x", 0);
FindAtLeastOneOf("TMin", 3);
FindAtLeastOneOf("Direction.x", 4);
FindAtLeastOneOf("TMax", 7);
}
TEST_F(PixTest, PixStructAnnotation_Simple) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
uint dummy;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.dummy = 42;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (!Testables.OffsetAndSizes.empty()) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[0].size);
}
VERIFY_ARE_EQUAL(1u, Testables.AllocaWrites.size());
ValidateAllocaWrite(Testables.AllocaWrites, 0, "dummy");
}
}
TEST_F(PixTest, PixStructAnnotation_CopiedStruct) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
uint dummy;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.dummy = 42;
smallPayload p2 = p;
DispatchMesh(1, 1, 1, p2);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
// 2 in unoptimized case (one for each instance of smallPayload)
// 1 in optimized case (cuz p2 aliases over p)
VERIFY_IS_TRUE(Testables.OffsetAndSizes.size() >= 1);
for (const auto &os : Testables.OffsetAndSizes) {
VERIFY_ARE_EQUAL(1u, os.countOfMembers);
VERIFY_ARE_EQUAL(0u, os.offset);
VERIFY_ARE_EQUAL(32u, os.size);
}
VERIFY_ARE_EQUAL(1u, Testables.AllocaWrites.size());
}
}
TEST_F(PixTest, PixStructAnnotation_MixedSizes) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
bool b1;
uint16_t sixteen;
uint32_t thirtytwo;
uint64_t sixtyfour;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.b1 = true;
p.sixteen = 16;
p.thirtytwo = 32;
p.sixtyfour = 64;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (!choice.IsOptimized) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(4u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
// 8 bytes align for uint64_t:
VERIFY_ARE_EQUAL(32u + 16u + 16u /*alignment for next field*/ + 32u +
32u /*alignment for max align*/ + 64u,
Testables.OffsetAndSizes[0].size);
} else {
VERIFY_ARE_EQUAL(4u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[0].size);
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[1].countOfMembers);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[1].offset);
VERIFY_ARE_EQUAL(16u, Testables.OffsetAndSizes[1].size);
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[2].countOfMembers);
VERIFY_ARE_EQUAL(32u + 32u, Testables.OffsetAndSizes[2].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[2].size);
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[3].countOfMembers);
VERIFY_ARE_EQUAL(32u + 32u + 32u + /*padding for alignment*/ 32u,
Testables.OffsetAndSizes[3].offset);
VERIFY_ARE_EQUAL(64u, Testables.OffsetAndSizes[3].size);
}
VERIFY_ARE_EQUAL(4u, Testables.AllocaWrites.size());
ValidateAllocaWrite(Testables.AllocaWrites, 0, "b1");
ValidateAllocaWrite(Testables.AllocaWrites, 1, "sixteen");
ValidateAllocaWrite(Testables.AllocaWrites, 2, "thirtytwo");
ValidateAllocaWrite(Testables.AllocaWrites, 3, "sixtyfour");
}
}
TEST_F(PixTest, PixStructAnnotation_StructWithinStruct) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct Contained
{
uint32_t one;
uint32_t two;
};
struct smallPayload
{
uint32_t before;
Contained contained;
uint32_t after;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.before = 0xb4;
p.contained.one = 1;
p.contained.two = 2;
p.after = 3;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (!choice.IsOptimized) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(4u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(4u * 32u, Testables.OffsetAndSizes[0].size);
} else {
VERIFY_ARE_EQUAL(4u, Testables.OffsetAndSizes.size());
for (unsigned i = 0; i < 4; i++) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[i].countOfMembers);
VERIFY_ARE_EQUAL(i * 32u, Testables.OffsetAndSizes[i].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[i].size);
}
}
ValidateAllocaWrite(Testables.AllocaWrites, 0, "before");
ValidateAllocaWrite(Testables.AllocaWrites, 1, "contained.one");
ValidateAllocaWrite(Testables.AllocaWrites, 2, "contained.two");
ValidateAllocaWrite(Testables.AllocaWrites, 3, "after");
}
}
TEST_F(PixTest, PixStructAnnotation_1DArray) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
uint32_t Array[2];
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.Array[0] = 250;
p.Array[1] = 251;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (!choice.IsOptimized) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(2u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(2u * 32u, Testables.OffsetAndSizes[0].size);
} else {
VERIFY_ARE_EQUAL(2u, Testables.OffsetAndSizes.size());
for (unsigned i = 0; i < 2; i++) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[i].countOfMembers);
VERIFY_ARE_EQUAL(i * 32u, Testables.OffsetAndSizes[i].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[i].size);
}
}
VERIFY_ARE_EQUAL(2u, Testables.AllocaWrites.size());
int Idx = 0;
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "Array[0]");
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "Array[1]");
}
}
TEST_F(PixTest, PixStructAnnotation_2DArray) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
uint32_t TwoDArray[2][3];
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.TwoDArray[0][0] = 250;
p.TwoDArray[0][1] = 251;
p.TwoDArray[0][2] = 252;
p.TwoDArray[1][0] = 253;
p.TwoDArray[1][1] = 254;
p.TwoDArray[1][2] = 255;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (!choice.IsOptimized) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(6u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(2u * 3u * 32u, Testables.OffsetAndSizes[0].size);
} else {
VERIFY_ARE_EQUAL(6u, Testables.OffsetAndSizes.size());
for (unsigned i = 0; i < 6; i++) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[i].countOfMembers);
VERIFY_ARE_EQUAL(i * 32u, Testables.OffsetAndSizes[i].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[i].size);
}
}
VERIFY_ARE_EQUAL(6u, Testables.AllocaWrites.size());
int Idx = 0;
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "TwoDArray[0][0]");
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "TwoDArray[0][1]");
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "TwoDArray[0][2]");
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "TwoDArray[1][0]");
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "TwoDArray[1][1]");
ValidateAllocaWrite(Testables.AllocaWrites, Idx++, "TwoDArray[1][2]");
}
}
TEST_F(PixTest, PixStructAnnotation_EmbeddedArray) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct Contained
{
uint32_t array[3];
};
struct smallPayload
{
uint32_t before;
Contained contained;
uint32_t after;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.before = 0xb4;
p.contained.array[0] = 0;
p.contained.array[1] = 1;
p.contained.array[2] = 2;
p.after = 3;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (!choice.IsOptimized) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(5u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(5u * 32u, Testables.OffsetAndSizes[0].size);
} else {
VERIFY_ARE_EQUAL(5u, Testables.OffsetAndSizes.size());
for (unsigned i = 0; i < 5; i++) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[i].countOfMembers);
VERIFY_ARE_EQUAL(i * 32u, Testables.OffsetAndSizes[i].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[i].size);
}
}
ValidateAllocaWrite(Testables.AllocaWrites, 0, "before");
ValidateAllocaWrite(Testables.AllocaWrites, 1, "contained.array[0]");
ValidateAllocaWrite(Testables.AllocaWrites, 2, "contained.array[1]");
ValidateAllocaWrite(Testables.AllocaWrites, 3, "contained.array[2]");
ValidateAllocaWrite(Testables.AllocaWrites, 4, "after");
}
}
TEST_F(PixTest, PixStructAnnotation_FloatN) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
auto IsOptimized = choice.IsOptimized;
const char *hlsl = R"(
struct smallPayload
{
float2 f2;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.f2 = float2(1,2);
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (IsOptimized) {
VERIFY_ARE_EQUAL(2u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[1].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[0].size);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[1].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[1].size);
} else {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(2u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(32u + 32u, Testables.OffsetAndSizes[0].size);
}
VERIFY_ARE_EQUAL(Testables.AllocaWrites.size(), 2u);
ValidateAllocaWrite(Testables.AllocaWrites, 0, "f2.x");
ValidateAllocaWrite(Testables.AllocaWrites, 1, "f2.y");
}
}
TEST_F(PixTest, PixStructAnnotation_SequentialFloatN) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
float3 color;
float3 dir;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.color = float3(1,2,3);
p.dir = float3(4,5,6);
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (choice.IsOptimized) {
VERIFY_ARE_EQUAL(6u, Testables.OffsetAndSizes.size());
for (unsigned i = 0; i < 6; i++) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[i].countOfMembers);
VERIFY_ARE_EQUAL(i * 32u, Testables.OffsetAndSizes[i].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[i].size);
}
} else {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(6u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(32u * 6u, Testables.OffsetAndSizes[0].size);
}
VERIFY_ARE_EQUAL(6u, Testables.AllocaWrites.size());
ValidateAllocaWrite(Testables.AllocaWrites, 0, "color.x");
ValidateAllocaWrite(Testables.AllocaWrites, 1, "color.y");
ValidateAllocaWrite(Testables.AllocaWrites, 2, "color.z");
ValidateAllocaWrite(Testables.AllocaWrites, 3, "dir.x");
ValidateAllocaWrite(Testables.AllocaWrites, 4, "dir.y");
ValidateAllocaWrite(Testables.AllocaWrites, 5, "dir.z");
}
}
TEST_F(PixTest, PixStructAnnotation_EmbeddedFloatN) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct Embedded
{
float2 f2;
};
struct smallPayload
{
uint32_t i32;
Embedded e;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.i32 = 32;
p.e.f2 = float2(1,2);
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (choice.IsOptimized) {
VERIFY_ARE_EQUAL(3u, Testables.OffsetAndSizes.size());
for (unsigned i = 0; i < 3; i++) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[i].countOfMembers);
VERIFY_ARE_EQUAL(i * 32u, Testables.OffsetAndSizes[i].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[i].size);
}
} else {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(3u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
VERIFY_ARE_EQUAL(32u * 3u, Testables.OffsetAndSizes[0].size);
}
VERIFY_ARE_EQUAL(3u, Testables.AllocaWrites.size());
ValidateAllocaWrite(Testables.AllocaWrites, 0, "i32");
ValidateAllocaWrite(Testables.AllocaWrites, 1, "e.f2.x");
ValidateAllocaWrite(Testables.AllocaWrites, 2, "e.f2.y");
}
}
TEST_F(PixTest, PixStructAnnotation_Matrix) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
float4x4 mat;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.mat = float4x4( 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15, 16);
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
// Can't test member iterator until dbg.declare instructions are emitted
// when structs contain pointers-to-pointers
VERIFY_ARE_EQUAL(16u, Testables.AllocaWrites.size());
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
std::string expected = std::string("mat._") + std::to_string(i + 1) +
std::to_string(j + 1);
ValidateAllocaWrite(Testables.AllocaWrites, i * 4 + j,
expected.c_str());
}
}
}
}
TEST_F(PixTest, PixStructAnnotation_MemberFunction) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
struct smallPayload
{
int i;
};
float2 signNotZero(float2 v)
{
return (v > 0.0f ? float(1).xx : float(-1).xx);
}
float2 unpackUnorm2(uint packed)
{
return (1.0 / 65535.0) * float2((packed >> 16) & 0xffff, packed & 0xffff);
}
float3 unpackOctahedralSnorm(float2 e)
{
float3 v = float3(e.xy, 1.0f - abs(e.x) - abs(e.y));
if (v.z < 0.0f) v.xy = (1.0f - abs(v.yx)) * signNotZero(v.xy);
return normalize(v);
}
float3 unpackOctahedralUnorm(float2 e)
{
return unpackOctahedralSnorm(e * 2.0f - 1.0f);
}
float2 unpackHalf2(uint packed)
{
return float2(f16tof32(packed >> 16), f16tof32(packed & 0xffff));
}
struct Gbuffer
{
float3 worldNormal;
float3 objectNormal; //offset:12
float linearZ; //24
float prevLinearZ; //28
float fwidthLinearZ; //32
float fwidthObjectNormal; //36
uint materialType; //40
uint2 materialParams0; //44
uint4 materialParams1; //52 <--------- this is the variable that's being covered twice (52*8 = 416 416)
uint instanceId; //68 <------- and there's one dword left over, as expected
void load(int2 pixelPos, Texture2DArray<uint4> gbTex)
{
uint4 data0 = gbTex.Load(int4(pixelPos, 0, 0));
uint4 data1 = gbTex.Load(int4(pixelPos, 1, 0));
uint4 data2 = gbTex.Load(int4(pixelPos, 2, 0));
worldNormal = unpackOctahedralUnorm(unpackUnorm2(data0.x));
linearZ = f16tof32((data0.y >> 8) & 0xffff);
materialType = (data0.y & 0xff);
materialParams0 = data0.zw;
materialParams1 = data1.xyzw;
instanceId = data2.x;
prevLinearZ = asfloat(data2.y);
objectNormal = unpackOctahedralUnorm(unpackUnorm2(data2.z));
float2 fwidth = unpackHalf2(data2.w);
fwidthLinearZ = fwidth.x;
fwidthObjectNormal = fwidth.y;
}
};
Gbuffer loadGbuffer(int2 pixelPos, Texture2DArray<uint4> gbTex)
{
Gbuffer output;
output.load(pixelPos, gbTex);
return output;
}
Texture2DArray<uint4> g_gbuffer : register(t0, space0);
[numthreads(1, 1, 1)]
void main()
{
const Gbuffer gbuffer = loadGbuffer(int2(0,0), g_gbuffer);
smallPayload p;
p.i = gbuffer.materialParams1.x + gbuffer.materialParams1.y + gbuffer.materialParams1.z + gbuffer.materialParams1.w;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization, true);
// TODO: Make 'this' work
// Can't validate # of writes: rel and dbg are different
// VERIFY_ARE_EQUAL(43, Testables.AllocaWrites.size());
// Can't test individual writes until struct member names are returned:
// for (int i = 0; i < 51; ++i)
//{
// ValidateAllocaWrite(Testables.AllocaWrites, i, "");
//}
}
}
TEST_F(PixTest, PixStructAnnotation_BigMess) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct BigStruct
{
uint64_t bigInt;
double bigDouble;
};
struct EmbeddedStruct
{
uint32_t OneInt;
uint32_t TwoDArray[2][2];
};
struct smallPayload
{
uint dummy;
uint vertexCount;
uint primitiveCount;
EmbeddedStruct embeddedStruct;
#ifdef PAYLOAD_MATRICES
float4x4 mat;
#endif
uint64_t bigOne;
half littleOne;
BigStruct bigStruct[2];
uint lastCheck;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
// Adding enough instructions to make the shader interesting to debug:
p.dummy = 42;
p.vertexCount = 3;
p.primitiveCount = 1;
p.embeddedStruct.OneInt = 123;
p.embeddedStruct.TwoDArray[0][0] = 252;
p.embeddedStruct.TwoDArray[0][1] = 253;
p.embeddedStruct.TwoDArray[1][0] = 254;
p.embeddedStruct.TwoDArray[1][1] = 255;
#ifdef PAYLOAD_MATRICES
p.mat = float4x4( 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15, 16);
#endif
p.bigOne = 123456789;
p.littleOne = 1.0;
p.bigStruct[0].bigInt = 10;
p.bigStruct[0].bigDouble = 2.0;
p.bigStruct[1].bigInt = 20;
p.bigStruct[1].bigDouble = 4.0;
p.lastCheck = 27;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
if (!choice.IsOptimized) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes.size());
VERIFY_ARE_EQUAL(15u, Testables.OffsetAndSizes[0].countOfMembers);
VERIFY_ARE_EQUAL(0u, Testables.OffsetAndSizes[0].offset);
constexpr uint32_t BigStructBitSize = 64 * 2;
constexpr uint32_t EmbeddedStructBitSize = 32 * 5;
VERIFY_ARE_EQUAL(3u * 32u + EmbeddedStructBitSize + 64u + 16u +
16u /*alignment for next field*/ +
BigStructBitSize * 2u + 32u +
32u /*align to max align*/,
Testables.OffsetAndSizes[0].size);
} else {
VERIFY_ARE_EQUAL(15u, Testables.OffsetAndSizes.size());
// First 8 members
for (unsigned i = 0; i < 8; i++) {
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[i].countOfMembers);
VERIFY_ARE_EQUAL(i * 32u, Testables.OffsetAndSizes[i].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[i].size);
}
// bigOne
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[8].countOfMembers);
VERIFY_ARE_EQUAL(256u, Testables.OffsetAndSizes[8].offset);
VERIFY_ARE_EQUAL(64u, Testables.OffsetAndSizes[8].size);
// littleOne
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[9].countOfMembers);
VERIFY_ARE_EQUAL(320u, Testables.OffsetAndSizes[9].offset);
VERIFY_ARE_EQUAL(16u, Testables.OffsetAndSizes[9].size);
// Each member of BigStruct[2]
for (unsigned i = 0; i < 4; i++) {
int idx = i + 10;
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[idx].countOfMembers);
VERIFY_ARE_EQUAL(384 + i * 64u, Testables.OffsetAndSizes[idx].offset);
VERIFY_ARE_EQUAL(64u, Testables.OffsetAndSizes[idx].size);
}
VERIFY_ARE_EQUAL(1u, Testables.OffsetAndSizes[14].countOfMembers);
VERIFY_ARE_EQUAL(640u, Testables.OffsetAndSizes[14].offset);
VERIFY_ARE_EQUAL(32u, Testables.OffsetAndSizes[14].size);
}
VERIFY_ARE_EQUAL(15u, Testables.AllocaWrites.size());
size_t Index = 0;
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "dummy");
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "vertexCount");
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "primitiveCount");
ValidateAllocaWrite(Testables.AllocaWrites, Index++,
"embeddedStruct.OneInt");
ValidateAllocaWrite(Testables.AllocaWrites, Index++,
"embeddedStruct.TwoDArray[0][0]");
ValidateAllocaWrite(Testables.AllocaWrites, Index++,
"embeddedStruct.TwoDArray[0][1]");
ValidateAllocaWrite(Testables.AllocaWrites, Index++,
"embeddedStruct.TwoDArray[1][0]");
ValidateAllocaWrite(Testables.AllocaWrites, Index++,
"embeddedStruct.TwoDArray[1][1]");
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "bigOne");
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "littleOne");
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "bigStruct[0].bigInt");
ValidateAllocaWrite(Testables.AllocaWrites, Index++,
"bigStruct[0].bigDouble");
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "bigStruct[1].bigInt");
ValidateAllocaWrite(Testables.AllocaWrites, Index++,
"bigStruct[1].bigDouble");
ValidateAllocaWrite(Testables.AllocaWrites, Index++, "lastCheck");
}
}
TEST_F(PixTest, PixStructAnnotation_AlignedFloat4Arrays) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct LinearSHSampleData
{
float4 linearTerms[3];
float4 hdrColorAO;
float4 visibilitySH;
} g_lhSampleData;
struct smallPayload
{
LinearSHSampleData lhSampleData;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.lhSampleData.linearTerms[0].x = g_lhSampleData.linearTerms[0].x;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
// Can't test offsets and sizes until dbg.declare instructions are emitted
// when floatn is used
// (https://github.com/microsoft/DirectXShaderCompiler/issues/2920)
// VERIFY_ARE_EQUAL(20, Testables.AllocaWrites.size());
}
}
TEST_F(PixTest, PixStructAnnotation_Inheritance) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct Base
{
float floatValue;
};
typedef Base BaseTypedef;
struct Derived : BaseTypedef
{
int intValue;
};
[numthreads(1, 1, 1)]
void main()
{
Derived p;
p.floatValue = 1.;
p.intValue = 2;
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
// Can't test offsets and sizes until dbg.declare instructions are emitted
// when floatn is used
// (https://github.com/microsoft/DirectXShaderCompiler/issues/2920)
// VERIFY_ARE_EQUAL(20, Testables.AllocaWrites.size());
}
}
TEST_F(PixTest, PixStructAnnotation_ResourceAsMember) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
Buffer g_texture;
struct smallPayload
{
float value;
};
struct WithEmbeddedObject
{
Buffer texture;
};
void DispatchIt(WithEmbeddedObject eo)
{
smallPayload p;
p.value = eo.texture.Load(0);
DispatchMesh(1, 1, 1, p);
}
[numthreads(1, 1, 1)]
void main()
{
WithEmbeddedObject eo;
eo.texture = g_texture;
DispatchIt(eo);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
// Can't test offsets and sizes until dbg.declare instructions are emitted
// when floatn is used
// (https://github.com/microsoft/DirectXShaderCompiler/issues/2920)
// VERIFY_ARE_EQUAL(20, Testables.AllocaWrites.size());
}
}
TEST_F(PixTest, PixStructAnnotation_WheresMyDbgValue) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
struct smallPayload
{
float f1;
float2 f2;
};
[numthreads(1, 1, 1)]
void main()
{
smallPayload p;
p.f1 = 1;
p.f2 = float2(2,3);
DispatchMesh(1, 1, 1, p);
}
)";
auto Testables = TestStructAnnotationCase(hlsl, optimization);
// Can't test offsets and sizes until dbg.declare instructions are emitted
// when floatn is used
// (https://github.com/microsoft/DirectXShaderCompiler/issues/2920)
VERIFY_ARE_EQUAL(3u, Testables.AllocaWrites.size());
}
}
TEST_F(PixTest, VirtualRegisters_InstructionCounts) {
if (m_ver.SkipDxilVersion(1, 5))
return;
for (auto choice : OptimizationChoices) {
auto optimization = choice.Flag;
const char *hlsl = R"(
RaytracingAccelerationStructure Scene : register(t0, space0);
RWTexture2D<float4> RenderTarget : register(u0);
struct SceneConstantBuffer
{
float4x4 projectionToWorld;
float4 cameraPosition;
float4 lightPosition;
float4 lightAmbientColor;
float4 lightDiffuseColor;
};
ConstantBuffer<SceneConstantBuffer> g_sceneCB : register(b0);
struct RayPayload
{
float4 color;
};
inline void GenerateCameraRay(uint2 index, out float3 origin, out float3 direction)
{
float2 xy = index + 0.5f; // center in the middle of the pixel.
float2 screenPos = xy;// / DispatchRaysDimensions().xy * 2.0 - 1.0;
// Invert Y for DirectX-style coordinates.
screenPos.y = -screenPos.y;
// Unproject the pixel coordinate into a ray.
float4 world = /*mul(*/float4(screenPos, 0, 1)/*, g_sceneCB.projectionToWorld)*/;
//world.xyz /= world.w;
origin = world.xyz; //g_sceneCB.cameraPosition.xyz;
direction = float3(1,0,0);//normalize(world.xyz - origin);
}
void RaygenCommon()
{
float3 rayDir;
float3 origin;
// Generate a ray for a camera pixel corresponding to an index from the dispatched 2D grid.
GenerateCameraRay(DispatchRaysIndex().xy, origin, rayDir);
// Trace the ray.
// Set the ray's extents.
RayDesc ray;
ray.Origin = origin;
ray.Direction = rayDir;
// Set TMin to a non-zero small value to avoid aliasing issues due to floating - point errors.
// TMin should be kept small to prevent missing geometry at close contact areas.
ray.TMin = 0.001;
ray.TMax = 10000.0;
RayPayload payload = { float4(0, 0, 0, 0) };
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);
// Write the raytraced color to the output texture.
// RenderTarget[DispatchRaysIndex().xy] = payload.color;
}
[shader("raygeneration")]
void Raygen0()
{
RaygenCommon();
}
[shader("raygeneration")]
void Raygen1()
{
RaygenCommon();
}
typedef BuiltInTriangleIntersectionAttributes MyAttributes;
[shader("closesthit")]
void InnerClosestHitShader(inout RayPayload payload, in MyAttributes attr)
{
payload.color = float4(0,1,0,0);
}
[shader("miss")]
void MyMissShader(inout RayPayload payload)
{
payload.color = float4(1, 0, 0, 0);
})";
CComPtr<IDxcBlob> pBlob =
Compile(m_dllSupport, hlsl, L"lib_6_6", {optimization});
CComPtr<IDxcBlob> pDxil = FindModule(DFCC_ShaderDebugInfoDXIL, pBlob);
auto outputLines = RunAnnotationPasses(m_dllSupport, pDxil).lines;
const char instructionRangeLabel[] = "InstructionRange:";
// The numbering pass should have counted instructions for each
// "interesting" (to PIX) function and output its start and (end+1)
// instruction ordinal. End should always be a reasonable number of
// instructions (>10) and end should always be higher than start, and all
// four functions above should be represented.
int countOfInstructionRangeLines = 0;
for (auto const &line : outputLines) {
auto tokens = Tokenize(line, " ");
if (tokens.size() >= 4) {
if (tokens[0] == instructionRangeLabel) {
countOfInstructionRangeLines++;
int instructionStart = atoi(tokens[1].c_str());
int instructionEnd = atoi(tokens[2].c_str());
VERIFY_IS_TRUE(instructionEnd > 10);
VERIFY_IS_TRUE(instructionEnd > instructionStart);
auto found1 = tokens[3].find("Raygen0@@YAXXZ") != std::string::npos;
auto found2 = tokens[3].find("Raygen1@@YAXXZ") != std::string::npos;
auto foundClosest =
tokens[3].find("InnerClosestHit") != std::string::npos;
auto foundMiss = tokens[3].find("MyMiss") != std::string::npos;
VERIFY_IS_TRUE(found1 || found2 || foundClosest || foundMiss);
}
}
}
VERIFY_ARE_EQUAL(4, countOfInstructionRangeLines);
// Non-library target:
const char *PixelShader = R"(
[RootSignature("")]
float main(float pos : A) : SV_Target {
float x = abs(pos);
float y = sin(pos);
float z = x + y;
return z;
}
)";
pBlob = Compile(m_dllSupport, PixelShader, L"ps_6_6", {optimization});
pDxil = FindModule(DFCC_ShaderDebugInfoDXIL, pBlob);
outputLines = RunAnnotationPasses(m_dllSupport, pDxil).lines;
countOfInstructionRangeLines = 0;
for (auto const &line : outputLines) {
auto tokens = Tokenize(line, " ");
if (tokens.size() >= 4) {
if (tokens[0] == instructionRangeLabel) {
countOfInstructionRangeLines++;
int instructionStart = atoi(tokens[1].c_str());
int instructionEnd = atoi(tokens[2].c_str());
VERIFY_IS_TRUE(instructionStart == 0);
VERIFY_IS_TRUE(instructionEnd > 10);
VERIFY_IS_TRUE(instructionEnd > instructionStart);
auto foundMain = tokens[3].find("main") != std::string::npos;
VERIFY_IS_TRUE(foundMain);
}
}
}
VERIFY_ARE_EQUAL(1, countOfInstructionRangeLines);
// Now check that the initial value parameter works:
const int startingInstructionOrdinal = 1234;
outputLines =
RunAnnotationPasses(m_dllSupport, pDxil, startingInstructionOrdinal)
.lines;
countOfInstructionRangeLines = 0;
for (auto const &line : outputLines) {
auto tokens = Tokenize(line, " ");
if (tokens.size() >= 4) {
if (tokens[0] == instructionRangeLabel) {
countOfInstructionRangeLines++;
int instructionStart = atoi(tokens[1].c_str());
int instructionEnd = atoi(tokens[2].c_str());
VERIFY_IS_TRUE(instructionStart == startingInstructionOrdinal);
VERIFY_IS_TRUE(instructionEnd > instructionStart);
auto foundMain = tokens[3].find("main") != std::string::npos;
VERIFY_IS_TRUE(foundMain);
}
}
}
VERIFY_ARE_EQUAL(1, countOfInstructionRangeLines);
}
}
TEST_F(PixTest, VirtualRegisters_AlignedOffsets) {
if (m_ver.SkipDxilVersion(1, 5))
return;
{
const char *hlsl = R"(
cbuffer cbEveryFrame : register(b0)
{
int i32;
float f32;
};
struct VS_OUTPUT_ENV
{
float4 Pos : SV_Position;
float2 Tex : TEXCOORD0;
};
float4 main(VS_OUTPUT_ENV input) : SV_Target
{
// (BTW we load from i32 and f32 (which are resident in a cb) so that these local variables aren't optimized away)
bool i1 = i32 != 0;
min16uint u16 = (min16uint)(i32 / 4);
min16int s16 = (min16int)(i32/4) * -1; // signed s16 gets -8
min12int s12 = (min12int)(i32/8) * -1; // signed s12 gets -4
half h = (half) f32 / 2.f; // f32 is initialized to 32.0 in8he CB, so the 16-bit type now has "16.0" in it
min16float mf16 = (min16float) f32 / -2.f;
min10float mf10 = (min10float) f32 / -4.f;
return float4((float)(i1 + u16) / 2.f, (float)(s16 + s12) / -128.f, h / 128.f, mf16 / 128.f + mf10 / 256.f);
}
)";
// This is little more than a crash test, designed to exercise a previously
// over-active assert..
std::vector<std::pair<const wchar_t *, std::vector<const wchar_t *>>>
argSets = {
{L"ps_6_0", {L"-Od"}},
{L"ps_6_2", {L"-Od", L"-HV", L"2018", L"-enable-16bit-types"}}};
for (auto const &args : argSets) {
CComPtr<IDxcBlob> pBlob =
Compile(m_dllSupport, hlsl, args.first, args.second);
CComPtr<IDxcBlob> pDxil = FindModule(DFCC_ShaderDebugInfoDXIL, pBlob);
RunAnnotationPasses(m_dllSupport, pDxil);
}
}
}
static void VerifyOperationSucceeded(IDxcOperationResult *pResult) {
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
if (FAILED(result)) {
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
CA2W errorsWide(BlobToUtf8(pErrors).c_str());
WEX::Logging::Log::Comment(errorsWide);
}
VERIFY_SUCCEEDED(result);
}
TEST_F(PixTest, RootSignatureUpgrade_SubObjects) {
const char *source = R"x(
GlobalRootSignature so_GlobalRootSignature =
{
"RootConstants(num32BitConstants=1, b8), "
};
StateObjectConfig so_StateObjectConfig =
{
STATE_OBJECT_FLAGS_ALLOW_LOCAL_DEPENDENCIES_ON_EXTERNAL_DEFINITONS
};
LocalRootSignature so_LocalRootSignature1 =
{
"RootConstants(num32BitConstants=3, b2), "
"UAV(u6),RootFlags(LOCAL_ROOT_SIGNATURE)"
};
LocalRootSignature so_LocalRootSignature2 =
{
"RootConstants(num32BitConstants=3, b2), "
"UAV(u8, flags=DATA_STATIC), "
"RootFlags(LOCAL_ROOT_SIGNATURE)"
};
RaytracingShaderConfig so_RaytracingShaderConfig =
{
128, // max payload size
32 // max attribute size
};
RaytracingPipelineConfig so_RaytracingPipelineConfig =
{
2 // max trace recursion depth
};
TriangleHitGroup MyHitGroup =
{
"MyAnyHit", // AnyHit
"MyClosestHit", // ClosestHit
};
SubobjectToExportsAssociation so_Association1 =
{
"so_LocalRootSignature1", // subobject name
"MyRayGen" // export association
};
SubobjectToExportsAssociation so_Association2 =
{
"so_LocalRootSignature2", // subobject name
"MyAnyHit" // export association
};
struct MyPayload
{
float4 color;
};
[shader("raygeneration")]
void MyRayGen()
{
}
[shader("closesthit")]
void MyClosestHit(inout MyPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
}
[shader("anyhit")]
void MyAnyHit(inout MyPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
}
[shader("miss")]
void MyMiss(inout MyPayload payload)
{
}
)x";
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
CComPtr<IDxcBlobEncoding> pSource;
Utf8ToBlob(m_dllSupport, source, &pSource);
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"", L"lib_6_6",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcBlob> compiled;
VERIFY_SUCCEEDED(pResult->GetResult(&compiled));
auto optimizedContainer = RunShaderAccessTrackingPass(compiled);
const char *pBlobContent =
reinterpret_cast<const char *>(optimizedContainer->GetBufferPointer());
unsigned blobSize = optimizedContainer->GetBufferSize();
const hlsl::DxilContainerHeader *pContainerHeader =
hlsl::IsDxilContainerLike(pBlobContent, blobSize);
const hlsl::DxilPartHeader *pPartHeader =
GetDxilPartByType(pContainerHeader, hlsl::DFCC_RuntimeData);
VERIFY_ARE_NOT_EQUAL(pPartHeader, nullptr);
hlsl::RDAT::DxilRuntimeData rdat(GetDxilPartData(pPartHeader),
pPartHeader->PartSize);
auto const subObjectTableReader = rdat.GetSubobjectTable();
// There are 9 subobjects in the HLSL above:
VERIFY_ARE_EQUAL(subObjectTableReader.Count(), 9u);
bool foundGlobalRS = false;
for (uint32_t i = 0; i < subObjectTableReader.Count(); ++i) {
auto subObject = subObjectTableReader[i];
hlsl::DXIL::SubobjectKind subobjectKind = subObject.getKind();
switch (subobjectKind) {
case hlsl::DXIL::SubobjectKind::GlobalRootSignature: {
foundGlobalRS = true;
VERIFY_IS_TRUE(0 ==
strcmp(subObject.getName(), "so_GlobalRootSignature"));
auto rootSigReader = subObject.getRootSignature();
DxilVersionedRootSignatureDesc const *rootSignature = nullptr;
DeserializeRootSignature(rootSigReader.getData(),
rootSigReader.sizeData(), &rootSignature);
VERIFY_ARE_EQUAL(rootSignature->Version,
DxilRootSignatureVersion::Version_1_1);
VERIFY_ARE_EQUAL(rootSignature->Desc_1_1.NumParameters, 2u);
VERIFY_ARE_EQUAL(rootSignature->Desc_1_1.pParameters[1].ParameterType,
DxilRootParameterType::UAV);
VERIFY_ARE_EQUAL(rootSignature->Desc_1_1.pParameters[1].ShaderVisibility,
DxilShaderVisibility::All);
VERIFY_ARE_EQUAL(
rootSignature->Desc_1_1.pParameters[1].Descriptor.RegisterSpace,
static_cast<uint32_t>(-2));
VERIFY_ARE_EQUAL(
rootSignature->Desc_1_1.pParameters[1].Descriptor.ShaderRegister, 0u);
DeleteRootSignature(rootSignature);
break;
}
}
}
VERIFY_IS_TRUE(foundGlobalRS);
}
TEST_F(PixTest, RootSignatureUpgrade_Annotation) {
const char *dynamicTextureAccess = R"x(
Texture1D<float4> tex[5] : register(t3);
SamplerState SS[3] : register(s2);
[RootSignature("DescriptorTable(SRV(t3, numDescriptors=5)),\
DescriptorTable(Sampler(s2, numDescriptors=3))")]
float4 main(int i : A, float j : B) : SV_TARGET
{
float4 r = tex[i].Sample(SS[i], i);
return r;
}
)x";
auto compiled = Compile(m_dllSupport, dynamicTextureAccess, L"ps_6_6");
auto pOptimizedContainer = RunShaderAccessTrackingPass(compiled);
const char *pBlobContent =
reinterpret_cast<const char *>(pOptimizedContainer->GetBufferPointer());
unsigned blobSize = pOptimizedContainer->GetBufferSize();
const hlsl::DxilContainerHeader *pContainerHeader =
hlsl::IsDxilContainerLike(pBlobContent, blobSize);
const hlsl::DxilPartHeader *pPartHeader =
GetDxilPartByType(pContainerHeader, hlsl::DFCC_RootSignature);
VERIFY_ARE_NOT_EQUAL(pPartHeader, nullptr);
hlsl::RootSignatureHandle RSH;
RSH.LoadSerialized((const uint8_t *)GetDxilPartData(pPartHeader),
pPartHeader->PartSize);
RSH.Deserialize();
auto const *desc = RSH.GetDesc();
bool foundGlobalRS = false;
VERIFY_ARE_EQUAL(desc->Version, hlsl::DxilRootSignatureVersion::Version_1_1);
VERIFY_ARE_EQUAL(desc->Desc_1_1.NumParameters, 3u);
for (unsigned int i = 0; i < desc->Desc_1_1.NumParameters; ++i) {
hlsl::DxilRootParameter1 const *param = desc->Desc_1_1.pParameters + i;
switch (param->ParameterType) {
case hlsl::DxilRootParameterType::UAV:
VERIFY_ARE_EQUAL(param->Descriptor.RegisterSpace,
static_cast<uint32_t>(-2));
VERIFY_ARE_EQUAL(param->Descriptor.ShaderRegister, 0u);
foundGlobalRS = true;
break;
}
}
VERIFY_IS_TRUE(foundGlobalRS);
}
TEST_F(PixTest, DxilPIXDXRInvocationsLog_SanityTest) {
const char *source = R"x(
struct MyPayload
{
float4 color;
};
[shader("raygeneration")]
void MyRayGen()
{
}
[shader("closesthit")]
void MyClosestHit(inout MyPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
}
[shader("anyhit")]
void MyAnyHit(inout MyPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
}
[shader("miss")]
void MyMiss(inout MyPayload payload)
{
}
)x";
auto compiledLib = Compile(m_dllSupport, source, L"lib_6_6", {});
RunDxilPIXDXRInvocationsLog(compiledLib);
}
TEST_F(PixTest, DebugInstrumentation_TextOutput) {
const char *source = R"x(
float4 main() : SV_Target {
return float4(0,0,0,0);
})x";
auto compiled = Compile(m_dllSupport, source, L"ps_6_0", {});
auto output = RunDebugPass(compiled, 8 /*ludicrously low UAV size limit*/);
bool foundStaticOverflow = false;
bool foundCounterOffset = false;
bool foundThreshold = false;
for (auto const &line : output.lines) {
if (line.find("StaticOverflow:12") != std::string::npos)
foundStaticOverflow = true;
if (line.find("InterestingCounterOffset:3") != std::string::npos)
foundCounterOffset = true;
if (line.find("OverflowThreshold:1") != std::string::npos)
foundThreshold = true;
}
VERIFY_IS_TRUE(foundStaticOverflow);
}
TEST_F(PixTest, DebugInstrumentation_BlockReport) {
const char *source = R"x(
RWStructuredBuffer<int> UAV: register(u0);
float4 main() : SV_Target {
// basic int variable
int v = UAV[0];
if(v == 0)
UAV[1] = v;
else
UAV[2] = v;
// float with indexed alloca
float f[2];
f[0] = UAV[4];
f[1] = UAV[5];
if(v == 2)
f[0] = v;
else
f[1] = v;
float farray2[2];
farray2[0] = UAV[4];
farray2[1] = UAV[5];
if(v == 4)
farray2[0] = v;
else
farray2[1] = v;
double d = UAV[8];
int64_t i64 = UAV[9];
return float4(d,i64,0,0);
})x";
auto compiled = Compile(m_dllSupport, source, L"ps_6_0", {L"-Od"});
auto output = RunDebugPass(compiled);
bool foundBlock = false;
bool foundRet = false;
bool foundUnnumberedVoidProllyADXNothing = false;
bool found32BitAssignment = false;
bool foundFloatAssignment = false;
bool foundDoubleAssignment = false;
bool found64BitAssignment = false;
bool found32BitAllocaStore = false;
for (auto const &line : output.lines) {
if (line.find("Block#") != std::string::npos) {
if (line.find("r,0,r;") != std::string::npos)
foundRet = true;
if (line.find("v,0,v;") != std::string::npos)
foundUnnumberedVoidProllyADXNothing = true;
if (line.find("3,3,a;") != std::string::npos)
found32BitAssignment = true;
if (line.find("d,13,a;") != std::string::npos)
foundDoubleAssignment = true;
if (line.find("f,19,a;") != std::string::npos)
foundFloatAssignment = true;
if (line.find("6,16,a;") != std::string::npos)
found64BitAssignment = true;
if (line.find("3,3,s,2+0;") != std::string::npos)
found32BitAllocaStore = true;
foundBlock = true;
}
}
VERIFY_IS_TRUE(foundBlock);
VERIFY_IS_TRUE(foundRet);
VERIFY_IS_TRUE(foundUnnumberedVoidProllyADXNothing);
VERIFY_IS_TRUE(found32BitAssignment);
VERIFY_IS_TRUE(found64BitAssignment);
VERIFY_IS_TRUE(foundFloatAssignment);
VERIFY_IS_TRUE(foundDoubleAssignment);
VERIFY_IS_TRUE(found32BitAllocaStore);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/CompilerTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// CompilerTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for the compiler API. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef UNICODE
#define UNICODE
#endif
// clang-format off
// Includes on Windows are highly order dependent.
#include <memory>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <cfloat>
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/Support/D3DReflection.h"
#include "dxc/dxcapi.h"
#ifdef _WIN32
#include "dxc/dxcpix.h"
#include <atlfile.h>
#include <d3dcompiler.h>
#include "dia2.h"
#else // _WIN32
#ifndef __ANDROID__
#include <execinfo.h>
#define CaptureStackBackTrace(FramesToSkip, FramesToCapture, BackTrace, \
BackTraceHash) \
backtrace(BackTrace, FramesToCapture)
#endif // __ANDROID__
#endif // _WIN32
#include "dxc/Test/HLSLTestData.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/Test/DxcTestUtils.h"
#include "llvm/Support/raw_os_ostream.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/Support/microcom.h"
#include "dxc/Support/HLSLOptions.h"
#include "dxc/Support/Unicode.h"
#include <fstream>
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
// clang-format on
// These are helper macros for adding slashes down below
// based on platform. The PP_ prefixed ones are for matching
// slashes in preprocessed HLSLs, since backslashes that
// appear in #line directives are double backslashes.
#ifdef _WIN32
#define SLASH_W L"\\"
#define SLASH "\\"
#else
#define SLASH_W L"/"
#define SLASH "/"
#endif
using namespace std;
using namespace hlsl_test;
class TestIncludeHandler : public IDxcIncludeHandler {
DXC_MICROCOM_REF_FIELD(m_dwRef)
public:
DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
dxc::DxcDllSupport &m_dllSupport;
HRESULT m_defaultErrorCode = E_FAIL;
TestIncludeHandler(dxc::DxcDllSupport &dllSupport)
: m_dwRef(0), m_dllSupport(dllSupport), callIndex(0) {}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject);
}
struct LoadSourceCallInfo {
std::wstring Filename; // Filename as written in #include statement
LoadSourceCallInfo(LPCWSTR pFilename) : Filename(pFilename) {}
};
std::vector<LoadSourceCallInfo> CallInfos;
std::wstring GetAllFileNames() const {
std::wstringstream s;
for (size_t i = 0; i < CallInfos.size(); ++i) {
s << CallInfos[i].Filename << ';';
}
return s.str();
}
struct LoadSourceCallResult {
HRESULT hr;
std::string source;
UINT32 codePage;
LoadSourceCallResult() : hr(E_FAIL), codePage(0) {}
LoadSourceCallResult(const char *pSource, UINT32 codePage = CP_UTF8)
: hr(S_OK), source(pSource), codePage(codePage) {}
LoadSourceCallResult(const void *pSource, size_t size,
UINT32 codePage = CP_ACP)
: hr(S_OK), source((const char *)pSource, size), codePage(codePage) {}
};
std::vector<LoadSourceCallResult> CallResults;
size_t callIndex;
HRESULT STDMETHODCALLTYPE LoadSource(
LPCWSTR pFilename, // Filename as written in #include statement
IDxcBlob **ppIncludeSource // Resultant source object for included file
) override {
CallInfos.push_back(LoadSourceCallInfo(pFilename));
*ppIncludeSource = nullptr;
if (callIndex >= CallResults.size()) {
return m_defaultErrorCode;
}
if (FAILED(CallResults[callIndex].hr)) {
return CallResults[callIndex++].hr;
}
MultiByteStringToBlob(m_dllSupport, CallResults[callIndex].source,
CallResults[callIndex].codePage, ppIncludeSource);
return CallResults[callIndex++].hr;
}
};
#ifdef _WIN32
class CompilerTest {
#else
class CompilerTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(CompilerTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
TEST_METHOD(CompileWhenDefinesThenApplied)
TEST_METHOD(CompileWhenDefinesManyThenApplied)
TEST_METHOD(CompileWhenEmptyThenFails)
TEST_METHOD(CompileWhenIncorrectThenFails)
TEST_METHOD(CompileWhenWorksThenDisassembleWorks)
TEST_METHOD(CompileWhenDebugWorksThenStripDebug)
TEST_METHOD(CompileWhenWorksThenAddRemovePrivate)
TEST_METHOD(CompileThenAddCustomDebugName)
TEST_METHOD(CompileThenTestReflectionWithProgramHeader)
TEST_METHOD(CompileThenTestPdbUtils)
TEST_METHOD(CompileThenTestPdbUtilsWarningOpt)
TEST_METHOD(CompileThenTestPdbInPrivate)
TEST_METHOD(CompileThenTestPdbUtilsStripped)
TEST_METHOD(CompileThenTestPdbUtilsEmptyEntry)
TEST_METHOD(CompileThenTestPdbUtilsRelativePath)
TEST_METHOD(CompileSameFilenameAndEntryThenTestPdbUtilsArgs)
TEST_METHOD(CompileWithRootSignatureThenStripRootSignature)
TEST_METHOD(CompileThenSetRootSignatureThenValidate)
TEST_METHOD(CompileSetPrivateThenWithStripPrivate)
TEST_METHOD(CompileWithMultiplePrivateOptionsThenFail)
TEST_METHOD(TestPdbUtilsWithEmptyDefine)
void CompileThenTestReflectionThreadSize(const char *source,
const WCHAR *target, UINT expectedX,
UINT expectedY, UINT expectedZ);
TEST_METHOD(CompileThenTestReflectionThreadSizeMS)
TEST_METHOD(CompileThenTestReflectionThreadSizeAS)
TEST_METHOD(CompileThenTestReflectionThreadSizeCS)
void TestResourceBindingImpl(const char *bindingFileContent,
const std::wstring &errors = std::wstring(),
bool noIncludeHandler = false);
TEST_METHOD(CompileWithResourceBindingFileThenOK)
TEST_METHOD(CompileWhenIncludeThenLoadInvoked)
TEST_METHOD(CompileWhenIncludeThenLoadUsed)
TEST_METHOD(CompileWhenIncludeAbsoluteThenLoadAbsolute)
TEST_METHOD(CompileWhenIncludeLocalThenLoadRelative)
TEST_METHOD(CompileWhenIncludeSystemThenLoadNotRelative)
TEST_METHOD(CompileWhenAllIncludeCombinations)
TEST_METHOD(TestPdbUtilsPathNormalizations)
TEST_METHOD(CompileWithIncludeThenTestNoLexicalBlockFile)
TEST_METHOD(CompileWhenIncludeSystemMissingThenLoadAttempt)
TEST_METHOD(CompileWhenIncludeFlagsThenIncludeUsed)
TEST_METHOD(CompileThenCheckDisplayIncludeProcess)
TEST_METHOD(CompileThenPrintTimeReport)
TEST_METHOD(CompileThenPrintTimeTrace)
TEST_METHOD(CompileWhenIncludeMissingThenFail)
TEST_METHOD(CompileWhenIncludeHasPathThenOK)
TEST_METHOD(CompileWhenIncludeEmptyThenOK)
TEST_METHOD(CompileWhenODumpThenPassConfig)
TEST_METHOD(CompileWhenODumpThenCheckNoSink)
TEST_METHOD(CompileWhenODumpThenOptimizerMatch)
TEST_METHOD(CompileWhenVdThenProducesDxilContainer)
void TestEncodingImpl(const void *sourceData, size_t sourceSize,
UINT32 codePage, const void *includedData,
size_t includedSize, const WCHAR *encoding = nullptr);
TEST_METHOD(CompileWithEncodeFlagTestSource)
#if _ITERATOR_DEBUG_LEVEL == 0
// CompileWhenNoMemThenOOM can properly detect leaks only when debug iterators
// are disabled
BEGIN_TEST_METHOD(CompileWhenNoMemThenOOM)
// Disabled because there are problems where we try to allocate memory in
// destructors, which causes more bad_alloc() throws while unwinding
// bad_alloc(), which asserts If only failing one allocation, there are
// allocations where failing them is lost, such as in ~raw_string_ostream(),
// where it flushes, then eats bad_alloc(), if thrown.
TEST_METHOD_PROPERTY(L"Ignore", L"true")
END_TEST_METHOD()
#endif
TEST_METHOD(CompileWhenShaderModelMismatchAttributeThenFail)
TEST_METHOD(CompileBadHlslThenFail)
TEST_METHOD(CompileLegacyShaderModelThenFail)
TEST_METHOD(CompileWhenRecursiveAlbeitStaticTermThenFail)
TEST_METHOD(CompileWhenRecursiveThenFail)
TEST_METHOD(CompileHlsl2015ThenFail)
TEST_METHOD(CompileHlsl2016ThenOK)
TEST_METHOD(CompileHlsl2017ThenOK)
TEST_METHOD(CompileHlsl2018ThenOK)
TEST_METHOD(CompileHlsl2019ThenFail)
TEST_METHOD(CompileHlsl2020ThenFail)
TEST_METHOD(CompileHlsl2021ThenOK)
TEST_METHOD(CompileHlsl2022ThenFail)
TEST_METHOD(CodeGenFloatingPointEnvironment)
TEST_METHOD(CodeGenLibCsEntry)
TEST_METHOD(CodeGenLibCsEntry2)
TEST_METHOD(CodeGenLibCsEntry3)
TEST_METHOD(CodeGenLibEntries)
TEST_METHOD(CodeGenLibEntries2)
TEST_METHOD(CodeGenLibResource)
TEST_METHOD(CodeGenLibUnusedFunc)
TEST_METHOD(CodeGenRootSigProfile)
TEST_METHOD(CodeGenRootSigProfile2)
TEST_METHOD(CodeGenRootSigProfile5)
TEST_METHOD(CodeGenVectorIsnan)
TEST_METHOD(CodeGenVectorAtan2)
TEST_METHOD(PreprocessWhenValidThenOK)
TEST_METHOD(LibGVStore)
TEST_METHOD(PreprocessWhenExpandTokenPastingOperandThenAccept)
TEST_METHOD(PreprocessWithDebugOptsThenOk)
TEST_METHOD(PreprocessCheckBuiltinIsOk)
TEST_METHOD(WhenSigMismatchPCFunctionThenFail)
TEST_METHOD(CompileOtherModesWithDebugOptsThenOk)
TEST_METHOD(BatchSamples)
TEST_METHOD(BatchD3DReflect)
TEST_METHOD(BatchDxil)
TEST_METHOD(BatchHLSL)
TEST_METHOD(BatchInfra)
TEST_METHOD(BatchPasses)
TEST_METHOD(BatchShaderTargets)
TEST_METHOD(BatchValidation)
TEST_METHOD(BatchPIX)
TEST_METHOD(CodeGenHashStabilityD3DReflect)
TEST_METHOD(CodeGenHashStabilityDisassembler)
TEST_METHOD(CodeGenHashStabilityDXIL)
TEST_METHOD(CodeGenHashStabilityHLSL)
TEST_METHOD(CodeGenHashStabilityInfra)
TEST_METHOD(CodeGenHashStabilityPIX)
TEST_METHOD(CodeGenHashStabilityRewriter)
TEST_METHOD(CodeGenHashStabilitySamples)
TEST_METHOD(CodeGenHashStabilityShaderTargets)
TEST_METHOD(CodeGenHashStabilityValidation)
TEST_METHOD(SubobjectCodeGenErrors)
BEGIN_TEST_METHOD(ManualFileCheckTest)
TEST_METHOD_PROPERTY(L"Ignore", L"true")
END_TEST_METHOD()
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
void CreateBlobPinned(LPCVOID data, SIZE_T size, UINT32 codePage,
IDxcBlobEncoding **ppBlob) {
CComPtr<IDxcLibrary> library;
IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
IFT(library->CreateBlobWithEncodingFromPinned(data, size, codePage,
ppBlob));
}
void CreateBlobFromFile(LPCWSTR name, IDxcBlobEncoding **ppBlob) {
CComPtr<IDxcLibrary> library;
IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
const std::wstring path = hlsl_test::GetPathToHlslDataFile(name);
IFT(library->CreateBlobFromFile(path.c_str(), nullptr, ppBlob));
}
void CreateBlobFromText(const char *pText, IDxcBlobEncoding **ppBlob) {
CreateBlobPinned(pText, strlen(pText) + 1, CP_UTF8, ppBlob);
}
HRESULT CreateCompiler(IDxcCompiler **ppResult) {
return m_dllSupport.CreateInstance(CLSID_DxcCompiler, ppResult);
}
void TestPdbUtils(bool bSlim, bool bLegacy, bool bStrip,
bool bTestEntryPoint);
HRESULT CreateContainerBuilder(IDxcContainerBuilder **ppResult) {
return m_dllSupport.CreateInstance(CLSID_DxcContainerBuilder, ppResult);
}
template <typename T, typename TDefault, typename TIface>
void WriteIfValue(TIface *pSymbol, std::wstringstream &o,
TDefault defaultValue, LPCWSTR valueLabel,
HRESULT (__stdcall TIface::*pFn)(T *)) {
T value;
HRESULT hr = (pSymbol->*(pFn))(&value);
if (SUCCEEDED(hr) && value != defaultValue) {
o << L", " << valueLabel << L": " << value;
}
}
std::string GetOption(std::string &cmd, char *opt) {
std::string option = cmd.substr(cmd.find(opt));
option = option.substr(option.find_first_of(' '));
option = option.substr(option.find_first_not_of(' '));
return option.substr(0, option.find_first_of(' '));
}
void CodeGenTest(std::wstring name) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
name.insert(0, L"..\\CodeGenHLSL\\");
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromFile(name.c_str(), &pSource);
std::string cmdLine = GetFirstLine(name.c_str());
llvm::StringRef argsRef = cmdLine;
llvm::SmallVector<llvm::StringRef, 8> splitArgs;
argsRef.split(splitArgs, " ");
hlsl::options::MainArgs argStrings(splitArgs);
std::string errorString;
llvm::raw_string_ostream errorStream(errorString);
hlsl::options::DxcOpts opts;
IFT(ReadDxcOpts(hlsl::options::getHlslOptTable(), /*flagsToInclude*/ 0,
argStrings, opts, errorStream));
std::wstring entry =
Unicode::UTF8ToWideStringOrThrow(opts.EntryPoint.str().c_str());
std::wstring profile =
Unicode::UTF8ToWideStringOrThrow(opts.TargetProfile.str().c_str());
std::vector<std::wstring> argLists;
CopyArgsToWStrings(opts.Args, hlsl::options::CoreOption, argLists);
std::vector<LPCWSTR> args;
args.reserve(argLists.size());
for (const std::wstring &a : argLists)
args.push_back(a.data());
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, name.c_str(), entry.c_str(), profile.c_str(), args.data(),
args.size(), opts.Defines.data(), opts.Defines.size(), nullptr,
&pResult));
VERIFY_IS_NOT_NULL(pResult, L"Failed to compile - pResult NULL");
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
if (FAILED(result)) {
CComPtr<IDxcBlobEncoding> pErr;
IFT(pResult->GetErrorBuffer(&pErr));
std::string errString(BlobToUtf8(pErr));
CA2W errStringW(errString.c_str());
WEX::Logging::Log::Comment(L"Failed to compile - errors follow");
WEX::Logging::Log::Comment(errStringW);
}
VERIFY_SUCCEEDED(result);
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
if (opts.IsRootSignatureProfile())
return;
CComPtr<IDxcBlobEncoding> pDisassembleBlob;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembleBlob));
std::string disassembleString(BlobToUtf8(pDisassembleBlob));
VERIFY_ARE_NOT_EQUAL(0U, disassembleString.size());
}
void CodeGenTestHashFullPath(LPCWSTR fullPath) {
FileRunTestResult t =
FileRunTestResult::RunHashTestFromFileCommands(fullPath);
if (t.RunResult != 0) {
CA2W commentWide(t.ErrorMessage.c_str());
WEX::Logging::Log::Comment(commentWide);
WEX::Logging::Log::Error(L"Run result is not zero");
}
}
void CodeGenTestHash(LPCWSTR name, bool implicitDir) {
std::wstring path = name;
if (implicitDir) {
path.insert(0, L"..\\CodeGenHLSL\\");
path = hlsl_test::GetPathToHlslDataFile(path.c_str());
}
CodeGenTestHashFullPath(path.c_str());
}
void CodeGenTestCheckBatchHash(std::wstring suitePath,
bool implicitDir = true) {
using namespace llvm;
using namespace WEX::TestExecution;
if (implicitDir)
suitePath.insert(0, L"..\\HLSLFileCheck\\");
::llvm::sys::fs::MSFileSystem *msfPtr;
VERIFY_SUCCEEDED(CreateMSFileSystemForDisk(&msfPtr));
std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr);
::llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
IFTLLVM(pts.error_code());
CW2A pUtf8Filename(suitePath.c_str());
if (!llvm::sys::path::is_absolute(pUtf8Filename.m_psz)) {
suitePath = hlsl_test::GetPathToHlslDataFile(suitePath.c_str());
}
CW2A utf8SuitePath(suitePath.c_str());
unsigned numTestsRun = 0;
std::error_code EC;
llvm::SmallString<128> DirNative;
llvm::sys::path::native(utf8SuitePath.m_psz, DirNative);
for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC), DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
// Check whether this entry has an extension typically associated with
// headers.
if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
.Cases(".hlsl", ".ll", true)
.Default(false))
continue;
StringRef filename = Dir->path();
std::string filetag = Dir->path();
filetag += "<HASH>";
CA2W wRelTag(filetag.data());
CA2W wRelPath(filename.data());
WEX::Logging::Log::StartGroup(wRelTag);
CodeGenTestHash(wRelPath, /*implicitDir*/ false);
WEX::Logging::Log::EndGroup(wRelTag);
numTestsRun++;
}
VERIFY_IS_GREATER_THAN(numTestsRun, (unsigned)0,
L"No test files found in batch directory.");
}
void CodeGenTestCheckFullPath(LPCWSTR fullPath, LPCWSTR dumpPath = nullptr) {
// Create file system if needed
llvm::sys::fs::MSFileSystem *msfPtr =
llvm::sys::fs::GetCurrentThreadFileSystem();
std::unique_ptr<llvm::sys::fs::MSFileSystem> msf;
if (!msfPtr) {
VERIFY_SUCCEEDED(CreateMSFileSystemForDisk(&msfPtr));
msf.reset(msfPtr);
}
llvm::sys::fs::AutoPerThreadSystem pts(msfPtr);
IFTLLVM(pts.error_code());
FileRunTestResult t = FileRunTestResult::RunFromFileCommands(
fullPath,
/*pPluginToolsPaths*/ nullptr, dumpPath);
if (t.RunResult != 0) {
CA2W commentWide(t.ErrorMessage.c_str());
WEX::Logging::Log::Comment(commentWide);
WEX::Logging::Log::Error(L"Run result is not zero");
}
}
void CodeGenTestCheck(LPCWSTR name, bool implicitDir = true,
LPCWSTR dumpPath = nullptr) {
std::wstring path = name;
std::wstring dumpStr;
if (implicitDir) {
path.insert(0, L"..\\CodeGenHLSL\\");
path = hlsl_test::GetPathToHlslDataFile(path.c_str());
if (!dumpPath) {
dumpStr = hlsl_test::GetPathToHlslDataFile(path.c_str(),
FILECHECKDUMPDIRPARAM);
dumpPath = dumpStr.empty() ? nullptr : dumpStr.c_str();
}
}
CodeGenTestCheckFullPath(path.c_str(), dumpPath);
}
void CodeGenTestCheckBatchDir(std::wstring suitePath,
bool implicitDir = true) {
using namespace llvm;
using namespace WEX::TestExecution;
if (implicitDir)
suitePath.insert(0, L"..\\HLSLFileCheck\\");
::llvm::sys::fs::MSFileSystem *msfPtr;
VERIFY_SUCCEEDED(CreateMSFileSystemForDisk(&msfPtr));
std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr);
::llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
IFTLLVM(pts.error_code());
std::wstring dumpPath;
CW2A pUtf8Filename(suitePath.c_str());
if (!llvm::sys::path::is_absolute(pUtf8Filename.m_psz)) {
dumpPath = hlsl_test::GetPathToHlslDataFile(suitePath.c_str(),
FILECHECKDUMPDIRPARAM);
suitePath = hlsl_test::GetPathToHlslDataFile(suitePath.c_str());
}
CW2A utf8SuitePath(suitePath.c_str());
unsigned numTestsRun = 0;
std::error_code EC;
llvm::SmallString<128> DirNative;
llvm::sys::path::native(utf8SuitePath.m_psz, DirNative);
for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC), DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
// Check whether this entry has an extension typically associated with
// headers.
if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
.Cases(".hlsl", ".ll", true)
.Default(false))
continue;
StringRef filename = Dir->path();
CA2W wRelPath(filename.data());
std::wstring dumpStr;
if (!dumpPath.empty() &&
suitePath.compare(0, suitePath.size(), wRelPath.m_psz,
suitePath.size()) == 0) {
dumpStr = dumpPath + (wRelPath.m_psz + suitePath.size());
}
class ScopedLogGroup {
LPWSTR m_path;
public:
ScopedLogGroup(LPWSTR path) : m_path(path) {
WEX::Logging::Log::StartGroup(m_path);
}
~ScopedLogGroup() { WEX::Logging::Log::EndGroup(m_path); }
};
ScopedLogGroup cleanup(wRelPath);
CodeGenTestCheck(wRelPath, /*implicitDir*/ false,
dumpStr.empty() ? nullptr : dumpStr.c_str());
numTestsRun++;
}
VERIFY_IS_GREATER_THAN(numTestsRun, (unsigned)0,
L"No test files found in batch directory.");
}
std::string VerifyCompileFailed(LPCSTR pText, LPCWSTR pTargetProfile,
LPCSTR pErrorMsg) {
return VerifyCompileFailed(pText, pTargetProfile, pErrorMsg, L"main");
}
std::string VerifyCompileFailed(LPCSTR pText, LPCWSTR pTargetProfile,
LPCSTR pErrorMsg, LPCWSTR pEntryPoint) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(pText, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", pEntryPoint,
pTargetProfile, nullptr, 0, nullptr, 0,
nullptr, &pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_FAILED(status);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
if (pErrorMsg && *pErrorMsg) {
CheckOperationResultMsgs(pResult, &pErrorMsg, 1, false, false);
}
return BlobToUtf8(pErrors);
}
void VerifyOperationSucceeded(IDxcOperationResult *pResult) {
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
if (FAILED(result)) {
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
CA2W errorsWide(BlobToUtf8(pErrors).c_str());
WEX::Logging::Log::Comment(errorsWide);
}
VERIFY_SUCCEEDED(result);
}
std::string VerifyOperationFailed(IDxcOperationResult *pResult) {
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_FAILED(result);
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
return BlobToUtf8(pErrors);
}
#ifdef _WIN32 // - exclude dia stuff
HRESULT CreateDiaSourceForCompile(const char *hlsl,
IDiaDataSource **ppDiaSource) {
if (!ppDiaSource)
return E_POINTER;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(hlsl, &pSource);
LPCWSTR args[] = {L"/Zi", L"/Qembed_debug"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args),
nullptr, 0, nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Disassemble the compiled (stripped) program.
{
CComPtr<IDxcBlobEncoding> pDisassembly;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembly));
std::string disText = BlobToUtf8(pDisassembly);
CA2W disTextW(disText.c_str());
// WEX::Logging::Log::Comment(disTextW);
}
// CONSIDER: have the dia data source look for the part if passed a whole
// container.
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pProgramStream;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
const hlsl::DxilContainerHeader *pContainer = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_IS_NOT_NULL(pContainer);
hlsl::DxilPartIterator partIter =
std::find_if(hlsl::begin(pContainer), hlsl::end(pContainer),
hlsl::DxilPartIsType(hlsl::DFCC_ShaderDebugInfoDXIL));
const hlsl::DxilProgramHeader *pProgramHeader =
(const hlsl::DxilProgramHeader *)hlsl::GetDxilPartData(*partIter);
uint32_t bitcodeLength;
const char *pBitcode;
CComPtr<IDxcBlob> pProgramPdb;
hlsl::GetDxilProgramBitcode(pProgramHeader, &pBitcode, &bitcodeLength);
VERIFY_SUCCEEDED(pLib->CreateBlobFromBlob(
pProgram, pBitcode - (char *)pProgram->GetBufferPointer(),
bitcodeLength, &pProgramPdb));
// Disassemble the program with debug information.
{
CComPtr<IDxcBlobEncoding> pDbgDisassembly;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgramPdb, &pDbgDisassembly));
std::string disText = BlobToUtf8(pDbgDisassembly);
CA2W disTextW(disText.c_str());
// WEX::Logging::Log::Comment(disTextW);
}
// Create a short text dump of debug information.
VERIFY_SUCCEEDED(
pLib->CreateStreamFromBlobReadOnly(pProgramPdb, &pProgramStream));
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaSource));
VERIFY_SUCCEEDED(pDiaSource->loadDataFromIStream(pProgramStream));
*ppDiaSource = pDiaSource.Detach();
return S_OK;
}
#endif // _WIN32 - exclude dia stuff
};
// Useful for debugging.
#if SUPPORT_FXC_PDB
#include <d3dcompiler.h>
#pragma comment(lib, "d3dcompiler.lib")
HRESULT GetBlobPdb(IDxcBlob *pBlob, IDxcBlob **ppDebugInfo) {
return D3DGetBlobPart(pBlob->GetBufferPointer(), pBlob->GetBufferSize(),
D3D_BLOB_PDB, 0, (ID3DBlob **)ppDebugInfo);
}
std::string FourCCStr(uint32_t val) {
std::stringstream o;
char c[5];
c[0] = val & 0xFF;
c[1] = (val & 0xFF00) >> 8;
c[2] = (val & 0xFF0000) >> 16;
c[3] = (val & 0xFF000000) >> 24;
c[4] = '\0';
o << c << " (" << std::hex << val << std::dec << ")";
return o.str();
}
std::string DumpParts(IDxcBlob *pBlob) {
std::stringstream o;
hlsl::DxilContainerHeader *pContainer =
(hlsl::DxilContainerHeader *)pBlob->GetBufferPointer();
o << "Container:" << std::endl
<< " Size: " << pContainer->ContainerSizeInBytes << std::endl
<< " FourCC: " << FourCCStr(pContainer->HeaderFourCC) << std::endl
<< " Part count: " << pContainer->PartCount << std::endl;
for (uint32_t i = 0; i < pContainer->PartCount; ++i) {
hlsl::DxilPartHeader *pPart = hlsl::GetDxilContainerPart(pContainer, i);
o << "Part " << i << std::endl
<< " FourCC: " << FourCCStr(pPart->PartFourCC) << std::endl
<< " Size: " << pPart->PartSize << std::endl;
}
return o.str();
}
HRESULT CreateDiaSourceFromDxbcBlob(IDxcLibrary *pLib, IDxcBlob *pDxbcBlob,
IDiaDataSource **ppDiaSource) {
HRESULT hr = S_OK;
CComPtr<IDxcBlob> pdbBlob;
CComPtr<IStream> pPdbStream;
CComPtr<IDiaDataSource> pDiaSource;
IFR(GetBlobPdb(pDxbcBlob, &pdbBlob));
IFR(pLib->CreateStreamFromBlobReadOnly(pdbBlob, &pPdbStream));
IFR(CoCreateInstance(CLSID_DiaSource, NULL, CLSCTX_INPROC_SERVER,
__uuidof(IDiaDataSource), (void **)&pDiaSource));
IFR(pDiaSource->loadDataFromIStream(pPdbStream));
*ppDiaSource = pDiaSource.Detach();
return hr;
}
#endif
bool CompilerTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
TEST_F(CompilerTest, CompileWhenDefinesThenApplied) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
DxcDefine defines[] = {{L"F4", L"float4"}};
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("F4 main() : SV_Target { return 0; }", &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, defines,
_countof(defines), nullptr, &pResult));
}
TEST_F(CompilerTest, CompileWhenDefinesManyThenApplied) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
LPCWSTR args[] = {L"/DVAL1=1", L"/DVAL2=2", L"/DVAL3=3", L"/DVAL4=2",
L"/DVAL5=4", L"/DNVAL1", L"/DNVAL2", L"/DNVAL3",
L"/DNVAL4", L"/DNVAL5", L"/DCVAL1=1", L"/DCVAL2=2",
L"/DCVAL3=3", L"/DCVAL4=2", L"/DCVAL5=4", L"/DCVALNONE="};
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target {\r\n"
"#ifndef VAL1\r\n"
"#error VAL1 not defined\r\n"
"#endif\r\n"
"#ifndef NVAL5\r\n"
"#error NVAL5 not defined\r\n"
"#endif\r\n"
"#ifndef CVALNONE\r\n"
"#error CVALNONE not defined\r\n"
"#endif\r\n"
"return 0; }",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, nullptr, &pResult));
HRESULT compileStatus;
VERIFY_SUCCEEDED(pResult->GetStatus(&compileStatus));
if (FAILED(compileStatus)) {
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
OutputDebugStringA((LPCSTR)pErrors->GetBufferPointer());
}
VERIFY_SUCCEEDED(compileStatus);
}
TEST_F(CompilerTest, CompileWhenEmptyThenFails) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pSourceBad;
LPCWSTR pProfile = L"ps_6_0";
LPCWSTR pEntryPoint = L"main";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
CreateBlobFromText("float4 main() : SV_Target { return undef; }",
&pSourceBad);
// correct version
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", pEntryPoint,
pProfile, nullptr, 0, nullptr, 0, nullptr,
&pResult));
pResult.Release();
// correct version with compilation errors
VERIFY_SUCCEEDED(pCompiler->Compile(pSourceBad, L"source.hlsl", pEntryPoint,
pProfile, nullptr, 0, nullptr, 0, nullptr,
&pResult));
pResult.Release();
// null source
VERIFY_FAILED(pCompiler->Compile(nullptr, L"source.hlsl", pEntryPoint,
pProfile, nullptr, 0, nullptr, 0, nullptr,
&pResult));
// null profile
VERIFY_FAILED(pCompiler->Compile(pSourceBad, L"source.hlsl", pEntryPoint,
nullptr, nullptr, 0, nullptr, 0, nullptr,
&pResult));
// null source name succeeds
VERIFY_SUCCEEDED(pCompiler->Compile(pSourceBad, nullptr, pEntryPoint,
pProfile, nullptr, 0, nullptr, 0, nullptr,
&pResult));
pResult.Release();
// empty source name (as opposed to null) also suceeds
VERIFY_SUCCEEDED(pCompiler->Compile(pSourceBad, L"", pEntryPoint, pProfile,
nullptr, 0, nullptr, 0, nullptr,
&pResult));
pResult.Release();
// null result
VERIFY_FAILED(pCompiler->Compile(pSource, L"source.hlsl", pEntryPoint,
pProfile, nullptr, 0, nullptr, 0, nullptr,
nullptr));
}
TEST_F(CompilerTest, CompileWhenIncorrectThenFails) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4_undefined main() : SV_Target { return 0; }",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_FAILED(result);
CComPtr<IDxcBlobEncoding> pErrorBuffer;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrorBuffer));
std::string errorString(BlobToUtf8(pErrorBuffer));
VERIFY_ARE_NOT_EQUAL(0U, errorString.size());
// Useful for examining actual error message:
// CA2W errorStringW(errorString.c_str());
// WEX::Logging::Log::Comment(errorStringW.m_psz);
}
TEST_F(CompilerTest, CompileWhenWorksThenDisassembleWorks) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
CComPtr<IDxcBlobEncoding> pDisassembleBlob;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembleBlob));
std::string disassembleString(BlobToUtf8(pDisassembleBlob));
VERIFY_ARE_NOT_EQUAL(0U, disassembleString.size());
// Useful for examining disassembly:
// CA2W disassembleStringW(disassembleString.c_str());
// WEX::Logging::Log::Comment(disassembleStringW.m_psz);
}
TEST_F(CompilerTest, CompileWhenDebugWorksThenStripDebug) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main(float4 pos : SV_Position) : SV_Target {\r\n"
" float4 local = abs(pos);\r\n"
" return local;\r\n"
"}",
&pSource);
LPCWSTR args[] = {L"/Zi", L"/Qembed_debug"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Check if it contains debug blob
hlsl::DxilContainerHeader *pHeader = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_SUCCEEDED(
hlsl::IsValidDxilContainer(pHeader, pProgram->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(
pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL);
VERIFY_IS_NOT_NULL(pPartHeader);
// Check debug info part does not exist after strip debug info
CComPtr<IDxcBlob> pNewProgram;
CComPtr<IDxcContainerBuilder> pBuilder;
VERIFY_SUCCEEDED(CreateContainerBuilder(&pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pProgram));
VERIFY_SUCCEEDED(
pBuilder->RemovePart(hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
pResult.Release();
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pNewProgram));
pHeader = hlsl::IsDxilContainerLike(pNewProgram->GetBufferPointer(),
pNewProgram->GetBufferSize());
VERIFY_SUCCEEDED(
hlsl::IsValidDxilContainer(pHeader, pNewProgram->GetBufferSize()));
pPartHeader = hlsl::GetDxilPartByType(
pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL);
VERIFY_IS_NULL(pPartHeader);
}
TEST_F(CompilerTest, CompileWhenWorksThenAddRemovePrivate) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target {\r\n"
" return 0;\r\n"
"}",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Append private data blob
CComPtr<IDxcContainerBuilder> pBuilder;
VERIFY_SUCCEEDED(CreateContainerBuilder(&pBuilder));
std::string privateTxt("private data");
CComPtr<IDxcBlobEncoding> pPrivate;
CreateBlobFromText(privateTxt.c_str(), &pPrivate);
VERIFY_SUCCEEDED(pBuilder->Load(pProgram));
VERIFY_SUCCEEDED(
pBuilder->AddPart(hlsl::DxilFourCC::DFCC_PrivateData, pPrivate));
pResult.Release();
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
CComPtr<IDxcBlob> pNewProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pNewProgram));
hlsl::DxilContainerHeader *pContainerHeader = hlsl::IsDxilContainerLike(
pNewProgram->GetBufferPointer(), pNewProgram->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(pContainerHeader,
pNewProgram->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(
pContainerHeader, hlsl::DxilFourCC::DFCC_PrivateData);
VERIFY_IS_NOT_NULL(pPartHeader);
// compare data
std::string privatePart((const char *)(pPartHeader + 1), privateTxt.size());
VERIFY_IS_TRUE(strcmp(privatePart.c_str(), privateTxt.c_str()) == 0);
// Remove private data blob
pBuilder.Release();
VERIFY_SUCCEEDED(CreateContainerBuilder(&pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pNewProgram));
VERIFY_SUCCEEDED(pBuilder->RemovePart(hlsl::DxilFourCC::DFCC_PrivateData));
pResult.Release();
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
pNewProgram.Release();
VERIFY_SUCCEEDED(pResult->GetResult(&pNewProgram));
pContainerHeader = hlsl::IsDxilContainerLike(pNewProgram->GetBufferPointer(),
pNewProgram->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(pContainerHeader,
pNewProgram->GetBufferSize()));
pPartHeader = hlsl::GetDxilPartByType(pContainerHeader,
hlsl::DxilFourCC::DFCC_PrivateData);
VERIFY_IS_NULL(pPartHeader);
}
TEST_F(CompilerTest, CompileThenAddCustomDebugName) {
// container builders prior to 1.3 did not support adding debug name parts
if (m_ver.SkipDxilVersion(1, 3))
return;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target {\r\n"
" return 0;\r\n"
"}",
&pSource);
LPCWSTR args[] = {L"/Zi", L"/Qembed_debug", L"/Zss"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Append private data blob
CComPtr<IDxcContainerBuilder> pBuilder;
VERIFY_SUCCEEDED(CreateContainerBuilder(&pBuilder));
const char pNewName[] = "MyOwnUniqueName.lld";
// include null terminator:
size_t nameBlobPartSize =
sizeof(hlsl::DxilShaderDebugName) + _countof(pNewName);
// round up to four-byte size:
size_t allocatedSize = (nameBlobPartSize + 3) & ~3;
auto pNameBlobContent =
reinterpret_cast<hlsl::DxilShaderDebugName *>(malloc(allocatedSize));
ZeroMemory(pNameBlobContent,
allocatedSize); // just to make sure trailing nulls are nulls.
pNameBlobContent->Flags = 0;
pNameBlobContent->NameLength =
_countof(pNewName) - 1; // this is not supposed to include null terminator
memcpy(pNameBlobContent + 1, pNewName, _countof(pNewName));
CComPtr<IDxcBlobEncoding> pDebugName;
CreateBlobPinned(pNameBlobContent, allocatedSize, DXC_CP_ACP, &pDebugName);
VERIFY_SUCCEEDED(pBuilder->Load(pProgram));
// should fail since it already exists:
VERIFY_FAILED(
pBuilder->AddPart(hlsl::DxilFourCC::DFCC_ShaderDebugName, pDebugName));
VERIFY_SUCCEEDED(
pBuilder->RemovePart(hlsl::DxilFourCC::DFCC_ShaderDebugName));
VERIFY_SUCCEEDED(
pBuilder->AddPart(hlsl::DxilFourCC::DFCC_ShaderDebugName, pDebugName));
pResult.Release();
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
CComPtr<IDxcBlob> pNewProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pNewProgram));
hlsl::DxilContainerHeader *pContainerHeader = hlsl::IsDxilContainerLike(
pNewProgram->GetBufferPointer(), pNewProgram->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(pContainerHeader,
pNewProgram->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(
pContainerHeader, hlsl::DxilFourCC::DFCC_ShaderDebugName);
VERIFY_IS_NOT_NULL(pPartHeader);
// compare data
VERIFY_IS_TRUE(memcmp(pPartHeader + 1, pNameBlobContent, allocatedSize) == 0);
free(pNameBlobContent);
// Remove private data blob
pBuilder.Release();
VERIFY_SUCCEEDED(CreateContainerBuilder(&pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pNewProgram));
VERIFY_SUCCEEDED(
pBuilder->RemovePart(hlsl::DxilFourCC::DFCC_ShaderDebugName));
pResult.Release();
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
pNewProgram.Release();
VERIFY_SUCCEEDED(pResult->GetResult(&pNewProgram));
pContainerHeader = hlsl::IsDxilContainerLike(pNewProgram->GetBufferPointer(),
pNewProgram->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(pContainerHeader,
pNewProgram->GetBufferSize()));
pPartHeader = hlsl::GetDxilPartByType(pContainerHeader,
hlsl::DxilFourCC::DFCC_ShaderDebugName);
VERIFY_IS_NULL(pPartHeader);
}
TEST_F(CompilerTest, CompileThenTestReflectionWithProgramHeader) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcOperationResult> pOperationResult;
const char *source = R"x(
cbuffer cb : register(b1) {
float foo;
};
[RootSignature("CBV(b1)")]
float4 main(float a : A) : SV_Target {
return a + foo;
}
)x";
std::string included_File = "#define ZERO 0";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(source, &pSource);
const WCHAR *args[] = {
L"-Zi",
};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, nullptr, &pOperationResult));
HRESULT CompileStatus = S_OK;
VERIFY_SUCCEEDED(pOperationResult->GetStatus(&CompileStatus));
VERIFY_SUCCEEDED(CompileStatus);
CComPtr<IDxcResult> pResult;
VERIFY_SUCCEEDED(pOperationResult.QueryInterface(&pResult));
CComPtr<IDxcBlob> pPdbBlob;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdbBlob), nullptr));
CComPtr<IDxcContainerReflection> pContainerReflection;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&pContainerReflection));
VERIFY_SUCCEEDED(pContainerReflection->Load(pPdbBlob));
UINT32 index = 0;
VERIFY_SUCCEEDED(pContainerReflection->FindFirstPartKind(
hlsl::DFCC_ShaderDebugInfoDXIL, &index));
CComPtr<IDxcBlob> pDebugDxilBlob;
VERIFY_SUCCEEDED(
pContainerReflection->GetPartContent(index, &pDebugDxilBlob));
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
DxcBuffer buf = {};
buf.Ptr = pDebugDxilBlob->GetBufferPointer();
buf.Size = pDebugDxilBlob->GetBufferSize();
CComPtr<ID3D12ShaderReflection> pReflection;
VERIFY_SUCCEEDED(pUtils->CreateReflection(&buf, IID_PPV_ARGS(&pReflection)));
ID3D12ShaderReflectionConstantBuffer *cb =
pReflection->GetConstantBufferByName("cb");
VERIFY_IS_TRUE(cb != nullptr);
}
void CompilerTest::CompileThenTestReflectionThreadSize(const char *source,
const WCHAR *target,
UINT expectedX,
UINT expectedY,
UINT expectedZ) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcOperationResult> pOperationResult;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(source, &pSource);
const WCHAR *args[] = {
L"-Zs",
};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main", target,
args, _countof(args), nullptr, 0, nullptr,
&pOperationResult));
HRESULT CompileStatus = S_OK;
VERIFY_SUCCEEDED(pOperationResult->GetStatus(&CompileStatus));
VERIFY_SUCCEEDED(CompileStatus);
CComPtr<IDxcBlob> pBlob;
VERIFY_SUCCEEDED(pOperationResult->GetResult(&pBlob));
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
DxcBuffer buf = {};
buf.Ptr = pBlob->GetBufferPointer();
buf.Size = pBlob->GetBufferSize();
CComPtr<ID3D12ShaderReflection> pReflection;
VERIFY_SUCCEEDED(pUtils->CreateReflection(&buf, IID_PPV_ARGS(&pReflection)));
UINT x = 0, y = 0, z = 0;
VERIFY_SUCCEEDED(pReflection->GetThreadGroupSize(&x, &y, &z));
VERIFY_ARE_EQUAL(x, expectedX);
VERIFY_ARE_EQUAL(y, expectedY);
VERIFY_ARE_EQUAL(z, expectedZ);
}
TEST_F(CompilerTest, CompileThenTestReflectionThreadSizeCS) {
const char *source = R"x(
[numthreads(2, 3, 1)]
void main()
{
}
)x";
CompileThenTestReflectionThreadSize(source, L"cs_6_5", 2, 3, 1);
}
TEST_F(CompilerTest, CompileThenTestReflectionThreadSizeAS) {
const char *source = R"x(
struct Payload {
float2 dummy;
float4 pos;
float color[2];
};
[numthreads(2, 3, 1)]
void main()
{
Payload pld;
pld.dummy = float2(1.0,2.0);
pld.pos = float4(3.0,4.0,5.0,6.0);
pld.color[0] = 7.0;
pld.color[1] = 8.0;
DispatchMesh(2, 3, 1, pld);
}
)x";
CompileThenTestReflectionThreadSize(source, L"as_6_5", 2, 3, 1);
}
TEST_F(CompilerTest, CompileThenTestReflectionThreadSizeMS) {
const char *source = R"x(
[NumThreads(2,3,1)]
[OutputTopology("triangle")]
void main() {
int x = 2;
}
)x";
CompileThenTestReflectionThreadSize(source, L"ms_6_5", 2, 3, 1);
}
static void VerifyPdbUtil(
dxc::DxcDllSupport &dllSupport, IDxcBlob *pBlob, IDxcPdbUtils *pPdbUtils,
const WCHAR *pMainFileName,
llvm::ArrayRef<std::pair<const WCHAR *, const WCHAR *>> ExpectedArgs,
llvm::ArrayRef<std::pair<const WCHAR *, const WCHAR *>> ExpectedFlags,
llvm::ArrayRef<const WCHAR *> ExpectedDefines, IDxcCompiler *pCompiler,
bool HasVersion, bool IsFullPDB, bool HasHashAndPdbName,
bool TestReflection, bool TestEntryPoint, const std::string &MainSource,
const std::string &IncludedFile) {
std::wstring MainFileName = std::wstring(L"." SLASH_W) + pMainFileName;
VERIFY_SUCCEEDED(pPdbUtils->Load(pBlob));
// Compiler version comparison
if (!HasVersion) {
CComPtr<IDxcVersionInfo> pVersion;
VERIFY_FAILED(pPdbUtils->GetVersionInfo(&pVersion));
} else {
CComPtr<IDxcVersionInfo> pVersion;
VERIFY_SUCCEEDED(pPdbUtils->GetVersionInfo(&pVersion));
CComPtr<IDxcVersionInfo2> pVersion2;
VERIFY_IS_NOT_NULL(pVersion);
VERIFY_SUCCEEDED(pVersion.QueryInterface(&pVersion2));
CComPtr<IDxcVersionInfo3> pVersion3;
VERIFY_SUCCEEDED(pVersion.QueryInterface(&pVersion3));
CComPtr<IDxcVersionInfo> pCompilerVersion;
pCompiler->QueryInterface(&pCompilerVersion);
if (pCompilerVersion) {
UINT32 uCompilerMajor = 0;
UINT32 uCompilerMinor = 0;
UINT32 uCompilerFlags = 0;
VERIFY_SUCCEEDED(
pCompilerVersion->GetVersion(&uCompilerMajor, &uCompilerMinor));
VERIFY_SUCCEEDED(pCompilerVersion->GetFlags(&uCompilerFlags));
UINT32 uMajor = 0;
UINT32 uMinor = 0;
UINT32 uFlags = 0;
VERIFY_SUCCEEDED(pVersion->GetVersion(&uMajor, &uMinor));
VERIFY_SUCCEEDED(pVersion->GetFlags(&uFlags));
VERIFY_ARE_EQUAL(uMajor, uCompilerMajor);
VERIFY_ARE_EQUAL(uMinor, uCompilerMinor);
VERIFY_ARE_EQUAL(uFlags, uCompilerFlags);
// IDxcVersionInfo2
UINT32 uCommitCount = 0;
CComHeapPtr<char> CommitVersionHash;
VERIFY_SUCCEEDED(
pVersion2->GetCommitInfo(&uCommitCount, &CommitVersionHash));
CComPtr<IDxcVersionInfo2> pCompilerVersion2;
if (SUCCEEDED(pCompiler->QueryInterface(&pCompilerVersion2))) {
UINT32 uCompilerCommitCount = 0;
CComHeapPtr<char> CompilerCommitVersionHash;
VERIFY_SUCCEEDED(pCompilerVersion2->GetCommitInfo(
&uCompilerCommitCount, &CompilerCommitVersionHash));
VERIFY_IS_TRUE(0 ==
strcmp(CommitVersionHash, CompilerCommitVersionHash));
VERIFY_ARE_EQUAL(uCommitCount, uCompilerCommitCount);
}
// IDxcVersionInfo3
CComHeapPtr<char> VersionString;
VERIFY_SUCCEEDED(pVersion3->GetCustomVersionString(&VersionString));
VERIFY_IS_TRUE(VersionString && strlen(VersionString) != 0);
{
CComPtr<IDxcVersionInfo3> pCompilerVersion3;
VERIFY_SUCCEEDED(pCompiler->QueryInterface(&pCompilerVersion3));
CComHeapPtr<char> CompilerVersionString;
VERIFY_SUCCEEDED(
pCompilerVersion3->GetCustomVersionString(&CompilerVersionString));
VERIFY_IS_TRUE(0 == strcmp(CompilerVersionString, VersionString));
}
}
}
// Target profile
{
CComBSTR str;
VERIFY_SUCCEEDED(pPdbUtils->GetTargetProfile(&str));
VERIFY_ARE_EQUAL_WSTR(L"ps_6_0", str.m_str);
}
// Entry point
{
CComBSTR str;
VERIFY_SUCCEEDED(pPdbUtils->GetEntryPoint(&str));
if (TestEntryPoint) {
VERIFY_ARE_EQUAL_WSTR(L"main", str.m_str);
} else {
VERIFY_ARE_EQUAL_WSTR(L"PSMain", str.m_str);
}
}
// PDB file path
if (HasHashAndPdbName) {
CComBSTR pName;
VERIFY_SUCCEEDED(pPdbUtils->GetName(&pName));
std::wstring suffix = L".pdb";
VERIFY_IS_TRUE(pName.Length() >= suffix.size());
VERIFY_IS_TRUE(0 == std::memcmp(suffix.c_str(),
&pName[pName.Length() - suffix.size()],
suffix.size()));
}
// Main file name
{
CComBSTR pPdbMainFileName;
VERIFY_SUCCEEDED(pPdbUtils->GetMainFileName(&pPdbMainFileName));
VERIFY_ARE_EQUAL(MainFileName, pPdbMainFileName.m_str);
}
// There is hash and hash is not empty
if (HasHashAndPdbName) {
CComPtr<IDxcBlob> pHash;
VERIFY_SUCCEEDED(pPdbUtils->GetHash(&pHash));
hlsl::DxilShaderHash EmptyHash = {};
VERIFY_ARE_EQUAL(pHash->GetBufferSize(), sizeof(EmptyHash));
VERIFY_IS_FALSE(0 == std::memcmp(pHash->GetBufferPointer(), &EmptyHash,
sizeof(EmptyHash)));
}
// Source files
{
UINT32 uSourceCount = 0;
VERIFY_SUCCEEDED(pPdbUtils->GetSourceCount(&uSourceCount));
for (UINT32 i = 0; i < uSourceCount; i++) {
CComBSTR pFileName;
CComPtr<IDxcBlobEncoding> pFileContent;
VERIFY_SUCCEEDED(pPdbUtils->GetSourceName(i, &pFileName));
VERIFY_SUCCEEDED(pPdbUtils->GetSource(i, &pFileContent));
CComPtr<IDxcBlobUtf8> pFileContentUtf8;
VERIFY_SUCCEEDED(pFileContent.QueryInterface(&pFileContentUtf8));
llvm::StringRef FileContentRef(pFileContentUtf8->GetStringPointer(),
pFileContentUtf8->GetStringLength());
if (MainFileName == pFileName.m_str) {
VERIFY_ARE_EQUAL(FileContentRef, MainSource);
} else {
VERIFY_ARE_EQUAL(FileContentRef, IncludedFile);
}
}
}
// Defines
{
UINT32 uDefineCount = 0;
std::map<std::wstring, int> tally;
VERIFY_SUCCEEDED(pPdbUtils->GetDefineCount(&uDefineCount));
VERIFY_IS_TRUE(uDefineCount == 2);
for (UINT32 i = 0; i < uDefineCount; i++) {
CComBSTR def;
VERIFY_SUCCEEDED(pPdbUtils->GetDefine(i, &def));
tally[std::wstring(def)]++;
}
auto Expected = ExpectedDefines;
for (size_t i = 0; i < Expected.size(); i++) {
auto it = tally.find(Expected[i]);
VERIFY_IS_TRUE(it != tally.end() && it->second == 1);
tally.erase(it);
}
VERIFY_IS_TRUE(tally.size() == 0);
}
// Arg pairs
{
std::vector<std::pair<std::wstring, std::wstring>> ArgPairs;
UINT32 uCount = 0;
VERIFY_SUCCEEDED(pPdbUtils->GetArgPairCount(&uCount));
for (unsigned i = 0; i < uCount; i++) {
CComBSTR pName;
CComBSTR pValue;
VERIFY_SUCCEEDED(pPdbUtils->GetArgPair(i, &pName, &pValue));
VERIFY_IS_TRUE(pName || pValue);
std::pair<std::wstring, std::wstring> NewPair;
if (pName)
NewPair.first = std::wstring(pName);
if (pValue)
NewPair.second = std::wstring(pValue);
ArgPairs.push_back(std::move(NewPair));
}
for (size_t i = 0; i < ExpectedArgs.size(); i++) {
auto ExpectedPair = ExpectedArgs[i];
bool Found = false;
for (size_t j = 0; j < ArgPairs.size(); j++) {
auto Pair = ArgPairs[j];
if ((!ExpectedPair.first || Pair.first == ExpectedPair.first) &&
(!ExpectedPair.second || Pair.second == ExpectedPair.second)) {
Found = true;
break;
}
}
VERIFY_SUCCEEDED(Found);
}
}
auto TestArgumentPair =
[](llvm::ArrayRef<std::wstring> Args,
llvm::ArrayRef<std::pair<const WCHAR *, const WCHAR *>> Expected) {
for (size_t i = 0; i < Expected.size(); i++) {
auto Pair = Expected[i];
bool found = false;
for (size_t j = 0; j < Args.size(); j++) {
if (!Pair.second && Args[j] == Pair.first) {
found = true;
break;
} else if (!Pair.first && Args[j] == Pair.second) {
found = true;
break;
} else if (Pair.first && Pair.second && Args[j] == Pair.first &&
j + 1 < Args.size() && Args[j + 1] == Pair.second) {
found = true;
break;
}
}
VERIFY_IS_TRUE(found);
}
};
// Flags
{
UINT32 uCount = 0;
std::vector<std::wstring> Flags;
VERIFY_SUCCEEDED(pPdbUtils->GetFlagCount(&uCount));
VERIFY_IS_TRUE(uCount == ExpectedFlags.size());
for (UINT32 i = 0; i < uCount; i++) {
CComBSTR item;
VERIFY_SUCCEEDED(pPdbUtils->GetFlag(i, &item));
Flags.push_back(std::wstring(item));
}
TestArgumentPair(Flags, ExpectedFlags);
}
// Args
{
UINT32 uCount = 0;
std::vector<std::wstring> Args;
VERIFY_SUCCEEDED(pPdbUtils->GetArgCount(&uCount));
for (UINT32 i = 0; i < uCount; i++) {
CComBSTR item;
VERIFY_SUCCEEDED(pPdbUtils->GetArg(i, &item));
Args.push_back(std::wstring(item));
}
TestArgumentPair(Args, ExpectedArgs);
}
// Shader reflection
if (TestReflection) {
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
DxcBuffer buf = {};
buf.Ptr = pBlob->GetBufferPointer();
buf.Size = pBlob->GetBufferSize();
buf.Encoding = CP_ACP;
CComPtr<ID3D12ShaderReflection> pRefl;
VERIFY_SUCCEEDED(pUtils->CreateReflection(&buf, IID_PPV_ARGS(&pRefl)));
D3D12_SHADER_DESC desc = {};
VERIFY_SUCCEEDED(pRefl->GetDesc(&desc));
VERIFY_ARE_EQUAL(desc.ConstantBuffers, 1u);
ID3D12ShaderReflectionConstantBuffer *pCB =
pRefl->GetConstantBufferByIndex(0);
D3D12_SHADER_BUFFER_DESC cbDesc = {};
VERIFY_SUCCEEDED(pCB->GetDesc(&cbDesc));
VERIFY_IS_TRUE(0 == strcmp(cbDesc.Name, "MyCbuffer"));
VERIFY_ARE_EQUAL(cbDesc.Variables, 1u);
ID3D12ShaderReflectionVariable *pVar = pCB->GetVariableByIndex(0);
D3D12_SHADER_VARIABLE_DESC varDesc = {};
VERIFY_SUCCEEDED(pVar->GetDesc(&varDesc));
VERIFY_ARE_EQUAL(varDesc.uFlags, D3D_SVF_USED);
VERIFY_IS_TRUE(0 == strcmp(varDesc.Name, "my_cbuf_foo"));
VERIFY_ARE_EQUAL(varDesc.Size, sizeof(float) * 4);
}
// Make the pix debug info
if (IsFullPDB) {
VERIFY_IS_TRUE(pPdbUtils->IsFullPDB());
} else {
VERIFY_IS_FALSE(pPdbUtils->IsFullPDB());
}
// Limit dia tests to Windows.
#ifdef _WIN32
// Now, test that dia interface doesn't crash (even if it fails).
{
CComPtr<IDiaDataSource> pDataSource;
VERIFY_SUCCEEDED(
dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDataSource));
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CComPtr<IStream> pStream;
VERIFY_SUCCEEDED(pLib->CreateStreamFromBlobReadOnly(pBlob, &pStream));
if (SUCCEEDED(pDataSource->loadDataFromIStream(pStream))) {
CComPtr<IDiaSession> pSession;
if (SUCCEEDED(pDataSource->openSession(&pSession))) {
CComPtr<IDxcPixDxilDebugInfoFactory> pFactory;
VERIFY_SUCCEEDED(pSession->QueryInterface(&pFactory));
CComPtr<IDxcPixCompilationInfo> pCompilationInfo;
if (SUCCEEDED(pFactory->NewDxcPixCompilationInfo(&pCompilationInfo))) {
CComBSTR args;
CComBSTR defs;
CComBSTR mainName;
CComBSTR entryPoint;
CComBSTR entryPointFile;
CComBSTR target;
pCompilationInfo->GetArguments(&args);
pCompilationInfo->GetMacroDefinitions(&defs);
pCompilationInfo->GetEntryPoint(&entryPoint);
pCompilationInfo->GetEntryPointFile(&entryPointFile);
pCompilationInfo->GetHlslTarget(&target);
for (DWORD i = 0;; i++) {
CComBSTR sourceName;
CComBSTR sourceContent;
if (FAILED(pCompilationInfo->GetSourceFile(i, &sourceName,
&sourceContent)))
break;
}
}
CComPtr<IDxcPixDxilDebugInfo> pDebugInfo;
pFactory->NewDxcPixDxilDebugInfo(&pDebugInfo);
}
}
}
#endif
}
TEST_F(CompilerTest, CompileThenTestPdbUtilsStripped) {
if (m_ver.SkipDxilVersion(1, 5))
return;
CComPtr<TestIncludeHandler> pInclude;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcOperationResult> pOperationResult;
std::string main_source = "#include \"helper.h\"\r\n"
"float4 PSMain() : SV_Target { return ZERO; }";
std::string included_File = "#define ZERO 0";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(main_source.c_str(), &pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back(included_File.c_str());
const WCHAR *pArgs[] = {L"/Zi", L"/Od", L"-flegacy-macro-expansion",
L"-Qstrip_debug", L"/DTHIS_IS_A_DEFINE=HELLO"};
const DxcDefine pDefines[] = {{L"THIS_IS_ANOTHER_DEFINE", L"1"}};
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, L"source.hlsl", L"PSMain", L"ps_6_0", pArgs, _countof(pArgs),
pDefines, _countof(pDefines), pInclude, &pOperationResult));
CComPtr<IDxcBlob> pCompiledBlob;
VERIFY_SUCCEEDED(pOperationResult->GetResult(&pCompiledBlob));
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
VERIFY_SUCCEEDED(pPdbUtils->Load(pCompiledBlob));
// PDB file path
{
CComBSTR pName;
VERIFY_SUCCEEDED(pPdbUtils->GetName(&pName));
std::wstring suffix = L".pdb";
VERIFY_IS_TRUE(pName.Length() >= suffix.size());
VERIFY_IS_TRUE(0 == std::memcmp(suffix.c_str(),
&pName[pName.Length() - suffix.size()],
suffix.size()));
}
// There is hash and hash is not empty
{
CComPtr<IDxcBlob> pHash;
VERIFY_SUCCEEDED(pPdbUtils->GetHash(&pHash));
hlsl::DxilShaderHash EmptyHash = {};
VERIFY_ARE_EQUAL(pHash->GetBufferSize(), sizeof(EmptyHash));
VERIFY_IS_FALSE(0 == std::memcmp(pHash->GetBufferPointer(), &EmptyHash,
sizeof(EmptyHash)));
}
{
VERIFY_IS_FALSE(pPdbUtils->IsFullPDB());
UINT32 uSourceCount = 0;
VERIFY_SUCCEEDED(pPdbUtils->GetSourceCount(&uSourceCount));
VERIFY_ARE_EQUAL(uSourceCount, 0u);
}
}
void CompilerTest::TestPdbUtils(bool bSlim, bool bSourceInDebugModule,
bool bStrip, bool bTestEntryPoint) {
CComPtr<TestIncludeHandler> pInclude;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcOperationResult> pOperationResult;
std::string entryPointName = bTestEntryPoint ? "main" : "PSMain";
std::wstring entryPointNameWide = bTestEntryPoint ? L"" : L"PSMain";
std::string main_source = R"x(
#include "helper.h"
cbuffer MyCbuffer : register(b1) {
float4 my_cbuf_foo;
}
[RootSignature("CBV(b1)")]
float4 )x" + entryPointName +
R"x(() : SV_Target {
return ZERO + my_cbuf_foo;
}
)x";
std::string included_File = "#define ZERO 0";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(main_source.c_str(), &pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back(included_File.c_str());
std::vector<const WCHAR *> args;
std::vector<std::pair<const WCHAR *, const WCHAR *>> expectedArgs;
std::vector<std::pair<const WCHAR *, const WCHAR *>> expectedFlags;
std::vector<const WCHAR *> expectedDefines;
auto AddArg = [&args, &expectedFlags, &expectedArgs](
const WCHAR *arg, const WCHAR *value, bool isDefine) {
args.push_back(arg);
if (value)
args.push_back(value);
std::pair<const WCHAR *, const WCHAR *> pair(arg, value);
expectedArgs.push_back(pair);
if (!isDefine) {
expectedFlags.push_back(pair);
}
};
AddArg(L"-Od", nullptr, false);
AddArg(L"-flegacy-macro-expansion", nullptr, false);
if (bStrip) {
AddArg(L"-Qstrip_debug", nullptr, false);
} else {
AddArg(L"-Qembed_debug", nullptr, false);
}
if (bSourceInDebugModule) {
AddArg(L"-Qsource_in_debug_module", nullptr, false);
}
if (bSlim) {
AddArg(L"-Zs", nullptr, false);
} else {
AddArg(L"-Zi", nullptr, false);
}
AddArg(L"-D", L"THIS_IS_A_DEFINE=HELLO", true);
const DxcDefine pDefines[] = {{L"THIS_IS_ANOTHER_DEFINE", L"1"}};
expectedDefines.push_back(L"THIS_IS_ANOTHER_DEFINE=1");
expectedDefines.push_back(L"THIS_IS_A_DEFINE=HELLO");
VERIFY_SUCCEEDED(
pCompiler->Compile(pSource, L"source.hlsl", entryPointNameWide.data(),
L"ps_6_0", args.data(), args.size(), pDefines,
_countof(pDefines), pInclude, &pOperationResult));
HRESULT CompileStatus = S_OK;
VERIFY_SUCCEEDED(pOperationResult->GetStatus(&CompileStatus));
VERIFY_SUCCEEDED(CompileStatus);
CComPtr<IDxcBlob> pCompiledBlob;
VERIFY_SUCCEEDED(pOperationResult->GetResult(&pCompiledBlob));
CComPtr<IDxcResult> pResult;
VERIFY_SUCCEEDED(pOperationResult.QueryInterface(&pResult));
CComPtr<IDxcBlob> pPdbBlob;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdbBlob), nullptr));
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
CComPtr<IDxcBlob> pProgramHeaderBlob;
if (bSourceInDebugModule) {
CComPtr<IDxcContainerReflection> pRef;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pRef));
VERIFY_SUCCEEDED(pRef->Load(pPdbBlob));
UINT32 uIndex = 0;
VERIFY_SUCCEEDED(
pRef->FindFirstPartKind(hlsl::DFCC_ShaderDebugInfoDXIL, &uIndex));
VERIFY_SUCCEEDED(pRef->GetPartContent(uIndex, &pProgramHeaderBlob));
VerifyPdbUtil(
m_dllSupport, pProgramHeaderBlob, pPdbUtils, L"source.hlsl",
expectedArgs, expectedFlags, expectedDefines, pCompiler,
/*HasVersion*/ false,
/*IsFullPDB*/ true,
/*HasHashAndPdbName*/ false,
/*TestReflection*/ false, // Reflection creation interface doesn't
// support just the DxilProgramHeader.
/*TestEntryPoint*/ bTestEntryPoint, main_source, included_File);
}
VerifyPdbUtil(m_dllSupport, pPdbBlob, pPdbUtils, L"source.hlsl", expectedArgs,
expectedFlags, expectedDefines, pCompiler,
/*HasVersion*/ true,
/*IsFullPDB*/ !bSlim,
/*HasHashAndPdbName*/ true,
/*TestReflection*/ true,
/*TestEntryPoint*/ bTestEntryPoint, main_source, included_File);
if (!bStrip) {
VerifyPdbUtil(m_dllSupport, pCompiledBlob, pPdbUtils, L"source.hlsl",
expectedArgs, expectedFlags, expectedDefines, pCompiler,
/*HasVersion*/ false,
/*IsFullPDB*/ true,
/*HasHashAndPdbName*/ true,
/*TestReflection*/ true,
/*TestEntryPoint*/ bTestEntryPoint, main_source,
included_File);
}
{
CComPtr<IDxcPdbUtils2> pPdbUtils2;
VERIFY_SUCCEEDED(pPdbUtils.QueryInterface(&pPdbUtils2));
{
CComPtr<IDxcPdbUtils> pPdbUtils_Again;
VERIFY_SUCCEEDED(pPdbUtils2.QueryInterface(&pPdbUtils_Again));
{
CComPtr<IDxcPdbUtils2> pPdbUtils2_Again;
VERIFY_SUCCEEDED(pPdbUtils_Again.QueryInterface(&pPdbUtils2_Again));
VERIFY_ARE_EQUAL(pPdbUtils2_Again, pPdbUtils2);
VERIFY_ARE_EQUAL(pPdbUtils2.p->AddRef(), 5u);
VERIFY_ARE_EQUAL(pPdbUtils2.p->Release(), 4u);
}
VERIFY_ARE_EQUAL(pPdbUtils_Again, pPdbUtils);
VERIFY_ARE_EQUAL(pPdbUtils2.p->AddRef(), 4u);
VERIFY_ARE_EQUAL(pPdbUtils2.p->Release(), 3u);
}
VERIFY_ARE_EQUAL(pPdbUtils2.p->AddRef(), 3u);
VERIFY_ARE_EQUAL(pPdbUtils2.p->Release(), 2u);
}
VERIFY_ARE_EQUAL(pPdbUtils.p->AddRef(), 2u);
VERIFY_ARE_EQUAL(pPdbUtils.p->Release(), 1u);
}
TEST_F(CompilerTest, CompileThenTestPdbUtils) {
if (m_ver.SkipDxilVersion(1, 5))
return;
TestPdbUtils(/*bSlim*/ true, /*bSourceInDebugModule*/ false, /*strip*/ true,
/*bTestEntryPoint*/ false); // Slim PDB, where source info is
// stored in its own part, and debug
// module is NOT present
TestPdbUtils(/*bSlim*/ false, /*bSourceInDebugModule*/ true, /*strip*/ false,
/*bTestEntryPoint*/ false); // Old PDB format, where source info
// is embedded in the module
TestPdbUtils(/*bSlim*/ false, /*bSourceInDebugModule*/ false, /*strip*/ false,
/*bTestEntryPoint*/ false); // Full PDB, where source info is
// stored in its own part, and a
// debug module which is present
TestPdbUtils(/*bSlim*/ false, /*bSourceInDebugModule*/ true, /*strip*/ true,
/*bTestEntryPoint*/ false); // Legacy PDB, where source info is
// embedded in the module
TestPdbUtils(/*bSlim*/ false, /*bSourceInDebugModule*/ true, /*strip*/ true,
/*bTestEntryPoint*/ true); // Same as above, except this time we
// test the default entry point.
TestPdbUtils(
/*bSlim*/ false, /*bSourceInDebugModule*/ false, /*strip*/ true,
/*bTestEntryPoint*/ false); // Full PDB, where source info is stored in
// its own part, and debug module is present
}
TEST_F(CompilerTest, CompileThenTestPdbUtilsWarningOpt) {
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
std::string main_source = R"x(
cbuffer MyCbuffer : register(b1) {
float4 my_cbuf_foo;
}
[RootSignature("CBV(b1)")]
float4 main() : SV_Target {
return my_cbuf_foo;
}
)x";
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcCompiler3> pCompiler3;
VERIFY_SUCCEEDED(pCompiler.QueryInterface(&pCompiler3));
const WCHAR *args[] = {
L"/Zs", L".\redundant_input", L"-Wno-parentheses-equality",
L"hlsl.hlsl", L"/Tps_6_0", L"/Emain",
};
DxcBuffer buf = {};
buf.Ptr = main_source.c_str();
buf.Size = main_source.size();
buf.Encoding = CP_UTF8;
CComPtr<IDxcResult> pResult;
VERIFY_SUCCEEDED(pCompiler3->Compile(&buf, args, _countof(args), nullptr,
IID_PPV_ARGS(&pResult)));
CComPtr<IDxcBlob> pPdb;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdb), nullptr));
auto TestPdb = [](IDxcPdbUtils *pPdbUtils) {
UINT32 uArgsCount = 0;
VERIFY_SUCCEEDED(pPdbUtils->GetArgCount(&uArgsCount));
bool foundArg = false;
for (UINT32 i = 0; i < uArgsCount; i++) {
CComBSTR pArg;
VERIFY_SUCCEEDED(pPdbUtils->GetArg(i, &pArg));
if (pArg) {
std::wstring arg(pArg);
if (arg == L"-Wno-parentheses-equality" ||
arg == L"/Wno-parentheses-equality") {
foundArg = true;
} else {
// Make sure arg value "no-parentheses-equality" doesn't show up
// as its own argument token.
VERIFY_ARE_NOT_EQUAL(arg, L"no-parentheses-equality");
// Make sure the presence of the argument ".\redundant_input"
// doesn't cause "<input>" to show up.
VERIFY_ARE_NOT_EQUAL(arg, L"<input>");
}
}
}
VERIFY_IS_TRUE(foundArg);
UINT32 uFlagsCount = 0;
VERIFY_SUCCEEDED(pPdbUtils->GetFlagCount(&uFlagsCount));
bool foundFlag = false;
for (UINT32 i = 0; i < uFlagsCount; i++) {
CComBSTR pFlag;
VERIFY_SUCCEEDED(pPdbUtils->GetFlag(i, &pFlag));
if (pFlag) {
std::wstring arg(pFlag);
if (arg == L"-Wno-parentheses-equality" ||
arg == L"/Wno-parentheses-equality") {
foundFlag = true;
} else {
// Make sure arg value "no-parentheses-equality" doesn't show up
// as its own flag token.
VERIFY_ARE_NOT_EQUAL(arg, L"no-parentheses-equality");
}
}
}
VERIFY_IS_TRUE(foundFlag);
CComBSTR pMainFileName;
VERIFY_SUCCEEDED(pPdbUtils->GetMainFileName(&pMainFileName));
std::wstring mainFileName = static_cast<const wchar_t *>(pMainFileName);
VERIFY_ARE_EQUAL(mainFileName, L"." SLASH_W L"hlsl.hlsl");
};
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
VERIFY_SUCCEEDED(pPdbUtils->Load(pPdb));
TestPdb(pPdbUtils);
}
TEST_F(CompilerTest, CompileThenTestPdbInPrivate) {
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
std::string main_source = R"x(
cbuffer MyCbuffer : register(b1) {
float4 my_cbuf_foo;
}
[RootSignature("CBV(b1)")]
float4 main() : SV_Target {
return my_cbuf_foo;
}
)x";
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(pUtils->CreateBlobFromPinned(
main_source.c_str(), main_source.size(), CP_UTF8, &pSource));
const WCHAR *args[] = {
L"/Zs",
L"/Qpdb_in_private",
};
CComPtr<IDxcOperationResult> pOpResult;
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
args, _countof(args), nullptr, 0, nullptr,
&pOpResult));
CComPtr<IDxcResult> pResult;
VERIFY_SUCCEEDED(pOpResult.QueryInterface(&pResult));
CComPtr<IDxcBlob> pShader;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_OBJECT, IID_PPV_ARGS(&pShader), nullptr));
CComPtr<IDxcContainerReflection> pRefl;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pRefl));
VERIFY_SUCCEEDED(pRefl->Load(pShader));
UINT32 uIndex = 0;
VERIFY_SUCCEEDED(pRefl->FindFirstPartKind(hlsl::DFCC_PrivateData, &uIndex));
CComPtr<IDxcBlob> pPdbBlob;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdbBlob), nullptr));
CComPtr<IDxcBlob> pPrivatePdbBlob;
VERIFY_SUCCEEDED(pRefl->GetPartContent(uIndex, &pPrivatePdbBlob));
VERIFY_ARE_EQUAL(pPdbBlob->GetBufferSize(), pPrivatePdbBlob->GetBufferSize());
VERIFY_ARE_EQUAL(0, memcmp(pPdbBlob->GetBufferPointer(),
pPrivatePdbBlob->GetBufferPointer(),
pPdbBlob->GetBufferSize()));
}
TEST_F(CompilerTest, CompileThenTestPdbUtilsRelativePath) {
std::string main_source = R"x(
#include "helper.h"
cbuffer MyCbuffer : register(b1) {
float4 my_cbuf_foo;
}
[RootSignature("CBV(b1)")]
float4 main() : SV_Target {
return my_cbuf_foo;
}
)x";
CComPtr<IDxcCompiler3> pCompiler;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
DxcBuffer SourceBuf = {};
SourceBuf.Ptr = main_source.c_str();
SourceBuf.Size = main_source.size();
SourceBuf.Encoding = CP_UTF8;
std::vector<const WCHAR *> args;
args.push_back(L"/Tps_6_0");
args.push_back(L"/Zs");
args.push_back(L"shaders/Shader.hlsl");
CComPtr<TestIncludeHandler> pInclude;
std::string included_File = "#define ZERO 0";
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back(included_File.c_str());
CComPtr<IDxcResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(&SourceBuf, args.data(), args.size(),
pInclude, IID_PPV_ARGS(&pResult)));
CComPtr<IDxcBlob> pPdb;
CComPtr<IDxcBlobWide> pPdbName;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdb), &pPdbName));
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
VERIFY_SUCCEEDED(pPdbUtils->Load(pPdb));
}
TEST_F(CompilerTest, CompileSameFilenameAndEntryThenTestPdbUtilsArgs) {
// This is a regression test for a bug where if entry point has the same
// value as the input filename, the entry point gets omitted from the arg
// list in debug module and PDB, making them useless for recompilation.
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
std::string shader = R"x(
[RootSignature("")] float PSMain() : SV_Target {
return 0;
}
)x";
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(DxcCreateInstance(CLSID_DxcUtils, IID_PPV_ARGS(&pUtils)));
CComPtr<IDxcOperationResult> pOpResult;
std::wstring EntryPoint = L"PSMain";
CComPtr<IDxcBlobEncoding> pShaderBlob;
VERIFY_SUCCEEDED(pUtils->CreateBlob(shader.data(),
shader.size() * sizeof(shader[0]),
DXC_CP_UTF8, &pShaderBlob));
const WCHAR *OtherInputs[] = {
L"AnotherInput1",
L"AnotherInput2",
L"AnotherInput3",
L"AnotherInput4",
};
const WCHAR *Args[] = {
OtherInputs[0], OtherInputs[1], L"-Od",
OtherInputs[2], L"-Zi", OtherInputs[3],
};
VERIFY_SUCCEEDED(pCompiler->Compile(
pShaderBlob, EntryPoint.c_str(), EntryPoint.c_str(), L"ps_6_0", Args,
_countof(Args), nullptr, 0, nullptr, &pOpResult));
HRESULT compileStatus = S_OK;
VERIFY_SUCCEEDED(pOpResult->GetStatus(&compileStatus));
VERIFY_SUCCEEDED(compileStatus);
CComPtr<IDxcBlob> pDxil;
VERIFY_SUCCEEDED(pOpResult->GetResult(&pDxil));
CComPtr<IDxcResult> pResult;
VERIFY_SUCCEEDED(pOpResult.QueryInterface(&pResult));
CComPtr<IDxcBlob> pPdb;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdb), nullptr));
IDxcBlob *PdbLikes[] = {
pDxil,
pPdb,
};
for (IDxcBlob *pPdbLike : PdbLikes) {
CComPtr<IDxcPdbUtils2> pPdbUtils;
VERIFY_SUCCEEDED(
DxcCreateInstance(CLSID_DxcPdbUtils, IID_PPV_ARGS(&pPdbUtils)));
VERIFY_SUCCEEDED(pPdbUtils->Load(pPdbLike));
CComPtr<IDxcBlobWide> pEntryPoint;
VERIFY_SUCCEEDED(pPdbUtils->GetEntryPoint(&pEntryPoint));
VERIFY_IS_NOT_NULL(pEntryPoint);
VERIFY_ARE_EQUAL(std::wstring(pEntryPoint->GetStringPointer(),
pEntryPoint->GetStringLength()),
EntryPoint);
std::set<std::wstring> ArgSet;
UINT uNumArgs = 0;
VERIFY_SUCCEEDED(pPdbUtils->GetArgCount(&uNumArgs));
for (UINT i = 0; i < uNumArgs; i++) {
CComPtr<IDxcBlobWide> pArg;
VERIFY_SUCCEEDED(pPdbUtils->GetArg(i, &pArg));
ArgSet.insert(
std::wstring(pArg->GetStringPointer(), pArg->GetStringLength()));
}
for (const WCHAR *OtherInputs : OtherInputs) {
VERIFY_ARE_EQUAL(ArgSet.end(), ArgSet.find(OtherInputs));
}
VERIFY_ARE_NOT_EQUAL(ArgSet.end(), ArgSet.find(L"-Od"));
VERIFY_ARE_NOT_EQUAL(ArgSet.end(), ArgSet.find(L"-Zi"));
}
}
TEST_F(CompilerTest, CompileThenTestPdbUtilsEmptyEntry) {
std::string main_source = R"x(
cbuffer MyCbuffer : register(b1) {
float4 my_cbuf_foo;
}
[RootSignature("CBV(b1)")]
float4 main() : SV_Target {
return my_cbuf_foo;
}
)x";
CComPtr<IDxcCompiler3> pCompiler;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
DxcBuffer SourceBuf = {};
SourceBuf.Ptr = main_source.c_str();
SourceBuf.Size = main_source.size();
SourceBuf.Encoding = CP_UTF8;
std::vector<const WCHAR *> args;
args.push_back(L"/Tps_6_0");
args.push_back(L"/Zi");
CComPtr<IDxcResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(&SourceBuf, args.data(), args.size(),
nullptr, IID_PPV_ARGS(&pResult)));
CComPtr<IDxcBlob> pPdb;
CComPtr<IDxcBlobWide> pPdbName;
VERIFY_SUCCEEDED(
pResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdb), &pPdbName));
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
VERIFY_SUCCEEDED(pPdbUtils->Load(pPdb));
CComBSTR pEntryName;
VERIFY_SUCCEEDED(pPdbUtils->GetEntryPoint(&pEntryName));
VERIFY_ARE_EQUAL_WSTR(L"main", pEntryName.m_str);
}
TEST_F(CompilerTest, TestPdbUtilsWithEmptyDefine) {
#include "TestHeaders/TestDxilWithEmptyDefine.h"
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcBlobEncoding> pBlob;
VERIFY_SUCCEEDED(pUtils->CreateBlobFromPinned(
g_TestDxilWithEmptyDefine, sizeof(g_TestDxilWithEmptyDefine), CP_ACP,
&pBlob));
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
VERIFY_SUCCEEDED(pPdbUtils->Load(pBlob));
UINT32 uCount = 0;
VERIFY_SUCCEEDED(pPdbUtils->GetDefineCount(&uCount));
for (UINT i = 0; i < uCount; i++) {
CComBSTR pDefine;
VERIFY_SUCCEEDED(pPdbUtils->GetDefine(i, &pDefine));
}
}
void CompilerTest::TestResourceBindingImpl(const char *bindingFileContent,
const std::wstring &errors,
bool noIncludeHandler) {
class IncludeHandler : public IDxcIncludeHandler {
DXC_MICROCOM_REF_FIELD(m_dwRef)
public:
DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject);
}
CComPtr<IDxcBlob> pBindingFileBlob;
IncludeHandler() : m_dwRef(0) {}
HRESULT STDMETHODCALLTYPE LoadSource(
LPCWSTR pFilename, // Filename as written in #include statement
IDxcBlob **ppIncludeSource // Resultant source object for included file
) override {
if (0 == wcscmp(pFilename, L"binding-file.txt")) {
return pBindingFileBlob.QueryInterface(ppIncludeSource);
}
return E_FAIL;
}
};
CComPtr<IDxcBlobEncoding> pBindingFileBlob;
CreateBlobFromText(bindingFileContent, &pBindingFileBlob);
CComPtr<IncludeHandler> pIncludeHandler;
if (!noIncludeHandler) {
pIncludeHandler = new IncludeHandler();
pIncludeHandler->pBindingFileBlob = pBindingFileBlob;
}
const char *source = R"x(
cbuffer cb {
float a;
};
cbuffer resource {
float b;
};
SamplerState samp0;
Texture2D resource;
RWTexture1D<float> uav_0;
[RootSignature("CBV(b10,space=30), CBV(b42,space=999), DescriptorTable(Sampler(s1,space=2)), DescriptorTable(SRV(t1,space=2)), DescriptorTable(UAV(u0,space=0))")]
float main(float2 uv : UV, uint i : I) :SV_Target {
return a + b + resource.Sample(samp0, uv).r + uav_0[i];
}
)x";
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcOperationResult> pResult;
const WCHAR *args[] = {L"-import-binding-table", L"binding-file.txt"};
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(source, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pIncludeHandler, &pResult));
HRESULT compileResult = S_OK;
VERIFY_SUCCEEDED(pResult->GetStatus(&compileResult));
if (errors.empty()) {
VERIFY_SUCCEEDED(compileResult);
} else {
VERIFY_FAILED(compileResult);
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
BOOL bEncodingKnown = FALSE;
UINT32 uCodePage = 0;
VERIFY_SUCCEEDED(pErrors->GetEncoding(&bEncodingKnown, &uCodePage));
std::wstring actualError = BlobToWide(pErrors);
if (actualError.find(errors) == std::wstring::npos) {
VERIFY_SUCCEEDED(E_FAIL);
}
}
}
TEST_F(CompilerTest, CompileWithResourceBindingFileThenOK) {
// Normal test
// List of things tested in this first test:
// - Arbitrary capitalization of the headers
// - Quotes
// - Optional trailing commas
// - Arbitrary spaces
// - Resources with the same names (but different classes)
// - Using include handler
//
TestResourceBindingImpl(
R"(
ResourceName, binding, spacE
"cb", b10, 0x1e ,
resource, b42, 999 ,
samp0, s1, 0x02 ,
resource, t1, 2
uav_0, u0, 0,
)");
// Reordered the columns 1
TestResourceBindingImpl(
R"(
ResourceName, space, Binding,
"cb", 0x1e , b10,
resource, 999 , b42,
samp0, 0x02 , s1,
resource, 2, t1,
uav_0, 0, u0,
)",
std::wstring());
// Reordered the columns 2
TestResourceBindingImpl(
R"(
space, binding, ResourceName,
0x1e , b10, "cb",
999 , b42, resource,
0x02 , s1, samp0,
2, t1, resource,
0, u0, uav_0,
)");
// Extra cell at the end of row
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b10, 0x1e ,
resource, b42, 999 ,
samp0, s1, 0x02, extra_cell
resource, t1, 2
uav_0, u0, 0,
)",
L"Unexpected cell at the end of row. There should only be 3");
// Missing cell in row
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b10, 0x1e ,
resource, b42, 999 ,
samp0, s1,
resource, t1, 2
uav_0, u0, 0,
)",
L"Row ended after just 2 columns. Expected 3.");
// Missing column
TestResourceBindingImpl(
R"(
ResourceName, Binding,
"cb", b10,
)",
L"Input format is csv with headings: ResourceName, Binding, Space.");
// Empty file
TestResourceBindingImpl(" \r\n ", L"Unexpected EOF when parsing cell.");
// Invalid resource binding type
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", 10, 30,
)",
L"Invalid resource class");
// Invalid resource binding type 2
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", e10, 30,
)",
L"Invalid resource class.");
// Index Integer out of bounds
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b99999999999999999999999999999999999, 30,
)",
L"'99999999999999999999999999999999999' is out of range of an 32-bit "
L"unsigned integer.");
// Empty resource
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", , 30,
)",
L"Resource binding cannot be empty.");
// Index Integer out of bounds
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b, 30,
)",
L"'b' is not a valid resource binding.");
// Integer out of bounds
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b10, 99999999999999999999999999999999999,
)",
L"'99999999999999999999999999999999999' is out of range of an 32-bit "
L"unsigned integer.");
// Integer out of bounds 2
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b10, 0xffffffffffffffffffffffffffffff,
)",
L"'0xffffffffffffffffffffffffffffff' is out of range of an 32-bit "
L"unsigned integer.");
// Integer invalid
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b10, abcd,
)",
L"'abcd' is not a valid 32-bit unsigned integer.");
// Integer empty
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b10, ,
)",
L"Expected unsigned 32-bit integer for resource space, but got empty "
L"cell.");
// No Include handler
TestResourceBindingImpl(
R"(
ResourceName, Binding, space
"cb", b10, 30,
)",
L"Binding table binding file 'binding-file.txt' specified, but no "
L"include handler was given",
/* noIncludeHandler */ true);
// Comma in a cell
TestResourceBindingImpl(
R"(
ResourceName, Binding, spacE, extra_column,
"cb", b10, 0x1e , " ,, ,",
resource, b42, 999 , " ,, ,",
samp0, s1, 0x02 , " ,, ,",
resource, t1, 2, " ,, ,",
uav_0, u0, 0, " ,, ,",
)");
// Newline in the middle of a quote
TestResourceBindingImpl(
R"(
ResourceName, Binding, spacE, extra_column,
"cb", b10, 0x1e , " ,, ,",
resource, b42, 999 , " ,, ,",
samp0, s1, 0x02 , " ,, ,",
resource, t1, 2, " ,, ,",
uav_0, u0, 0, " ,
)",
L"Unexpected newline inside quotation.");
}
TEST_F(CompilerTest, CompileWithRootSignatureThenStripRootSignature) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("[RootSignature(\"\")] \r\n"
"float4 main(float a : A) : SV_Target {\r\n"
" return a;\r\n"
"}",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
VERIFY_IS_NOT_NULL(pResult);
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
VERIFY_IS_NOT_NULL(pProgram);
hlsl::DxilContainerHeader *pContainerHeader = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_SUCCEEDED(
hlsl::IsValidDxilContainer(pContainerHeader, pProgram->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(
pContainerHeader, hlsl::DxilFourCC::DFCC_RootSignature);
VERIFY_IS_NOT_NULL(pPartHeader);
pResult.Release();
// Remove root signature
CComPtr<IDxcBlob> pProgramRootSigRemoved;
CComPtr<IDxcContainerBuilder> pBuilder;
VERIFY_SUCCEEDED(CreateContainerBuilder(&pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pProgram));
VERIFY_SUCCEEDED(pBuilder->RemovePart(hlsl::DxilFourCC::DFCC_RootSignature));
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgramRootSigRemoved));
pContainerHeader =
hlsl::IsDxilContainerLike(pProgramRootSigRemoved->GetBufferPointer(),
pProgramRootSigRemoved->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(
pContainerHeader, pProgramRootSigRemoved->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeaderShouldBeNull = hlsl::GetDxilPartByType(
pContainerHeader, hlsl::DxilFourCC::DFCC_RootSignature);
VERIFY_IS_NULL(pPartHeaderShouldBeNull);
pBuilder.Release();
pResult.Release();
// Add root signature back
CComPtr<IDxcBlobEncoding> pRootSignatureBlob;
CComPtr<IDxcLibrary> pLibrary;
CComPtr<IDxcBlob> pProgramRootSigAdded;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
VERIFY_SUCCEEDED(pLibrary->CreateBlobWithEncodingFromPinned(
hlsl::GetDxilPartData(pPartHeader), pPartHeader->PartSize, 0,
&pRootSignatureBlob));
VERIFY_SUCCEEDED(CreateContainerBuilder(&pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pProgramRootSigRemoved));
pBuilder->AddPart(hlsl::DxilFourCC::DFCC_RootSignature, pRootSignatureBlob);
pBuilder->SerializeContainer(&pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgramRootSigAdded));
pContainerHeader =
hlsl::IsDxilContainerLike(pProgramRootSigAdded->GetBufferPointer(),
pProgramRootSigAdded->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(
pContainerHeader, pProgramRootSigAdded->GetBufferSize()));
pPartHeader = hlsl::GetDxilPartByType(pContainerHeader,
hlsl::DxilFourCC::DFCC_RootSignature);
VERIFY_IS_NOT_NULL(pPartHeader);
}
TEST_F(CompilerTest, CompileThenSetRootSignatureThenValidate) {
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CComPtr<IDxcOperationResult> pResult;
HRESULT status;
// Compile with Root Signature in Shader source
CComPtr<IDxcBlobEncoding> pSourceBlobWithRS;
CComPtr<IDxcBlob> pProgramSourceRS;
CreateBlobFromText("[RootSignature(\"\")] \r\n"
"float4 main(float a : A) : SV_Target {\r\n"
" return a;\r\n"
"}",
&pSourceBlobWithRS);
VERIFY_SUCCEEDED(pCompiler->Compile(pSourceBlobWithRS, L"source.hlsl",
L"main", L"ps_6_0", nullptr, 0, nullptr,
0, nullptr, &pResult));
VERIFY_IS_NOT_NULL(pResult);
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgramSourceRS));
VERIFY_IS_NOT_NULL(pProgramSourceRS);
// Verify RS
hlsl::DxilContainerHeader *pContainerHeader = hlsl::IsDxilContainerLike(
pProgramSourceRS->GetBufferPointer(), pProgramSourceRS->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(
pContainerHeader, pProgramSourceRS->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(
pContainerHeader, hlsl::DxilFourCC::DFCC_RootSignature);
VERIFY_IS_NOT_NULL(pPartHeader);
// Extract the serialized root signature
CComPtr<IDxcBlob> pRSBlob;
CComPtr<IDxcResult> pResultSourceRS;
pResult.QueryInterface(&pResultSourceRS);
VERIFY_SUCCEEDED(pResultSourceRS->GetOutput(DXC_OUT_ROOT_SIGNATURE,
IID_PPV_ARGS(&pRSBlob), nullptr));
VERIFY_IS_NOT_NULL(pRSBlob);
// Add Serialized Root Signature source to include handler
CComPtr<TestIncludeHandler> pInclude;
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back(pRSBlob->GetBufferPointer(),
pRSBlob->GetBufferSize());
// Compile with Set Root Signature
pResult.Release();
CComPtr<IDxcBlobEncoding> pSourceNoRS;
CComPtr<IDxcBlob> pProgramSetRS;
CreateBlobFromText("float4 main(float a : A) : SV_Target {\r\n"
" return a;\r\n"
"}",
&pSourceNoRS);
LPCWSTR args[] = {L"-setrootsignature", L"rootsignaturesource.hlsl"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSourceNoRS, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude, &pResult));
VERIFY_IS_NOT_NULL(pResult);
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgramSetRS));
VERIFY_IS_NOT_NULL(pProgramSetRS);
// Verify RS in container
hlsl::DxilContainerHeader *pContainerHeaderSet = hlsl::IsDxilContainerLike(
pProgramSetRS->GetBufferPointer(), pProgramSetRS->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(pContainerHeaderSet,
pProgramSetRS->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeaderSet = hlsl::GetDxilPartByType(
pContainerHeaderSet, hlsl::DxilFourCC::DFCC_RootSignature);
VERIFY_IS_NOT_NULL(pPartHeaderSet);
// Extract the serialized root signature
CComPtr<IDxcBlob> pRSBlobSet;
CComPtr<IDxcResult> pResultSetRS;
pResult.QueryInterface(&pResultSetRS);
VERIFY_SUCCEEDED(pResultSetRS->GetOutput(DXC_OUT_ROOT_SIGNATURE,
IID_PPV_ARGS(&pRSBlobSet), nullptr));
VERIFY_IS_NOT_NULL(pRSBlobSet);
// Verify RS equal from source and using setrootsignature option
VERIFY_ARE_EQUAL(pRSBlob->GetBufferSize(), pRSBlobSet->GetBufferSize());
VERIFY_ARE_EQUAL(0, memcmp(pRSBlob->GetBufferPointer(),
pRSBlobSet->GetBufferPointer(),
pRSBlob->GetBufferSize()));
// Change root signature and validate
pResult.Release();
CComPtr<IDxcBlobEncoding> pReplaceRS;
CComPtr<IDxcBlob> pProgramReplaceRS;
CreateBlobFromText("[RootSignature(\" CBV(b1) \")] \r\n"
"float4 main(float a : A) : SV_Target {\r\n"
" return a;\r\n"
"}",
&pReplaceRS);
// Add Serialized Root Signature source to include handler
CComPtr<TestIncludeHandler> pInclude3;
pInclude3 = new TestIncludeHandler(m_dllSupport);
pInclude3->CallResults.emplace_back(pRSBlob->GetBufferPointer(),
pRSBlob->GetBufferSize());
VERIFY_SUCCEEDED(pCompiler->Compile(pReplaceRS, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude3, &pResult));
VERIFY_IS_NOT_NULL(pResult);
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgramReplaceRS));
VERIFY_IS_NOT_NULL(pProgramReplaceRS);
// Verify RS
hlsl::DxilContainerHeader *pContainerHeaderReplace =
hlsl::IsDxilContainerLike(pProgramReplaceRS->GetBufferPointer(),
pProgramReplaceRS->GetBufferSize());
VERIFY_SUCCEEDED(hlsl::IsValidDxilContainer(
pContainerHeaderReplace, pProgramReplaceRS->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeaderReplace = hlsl::GetDxilPartByType(
pContainerHeaderReplace, hlsl::DxilFourCC::DFCC_RootSignature);
VERIFY_IS_NOT_NULL(pPartHeaderReplace);
// Extract the serialized root signature
CComPtr<IDxcBlob> pRSBlobReplace;
CComPtr<IDxcResult> pResultReplace;
pResult.QueryInterface(&pResultReplace);
VERIFY_SUCCEEDED(pResultReplace->GetOutput(
DXC_OUT_ROOT_SIGNATURE, IID_PPV_ARGS(&pRSBlobReplace), nullptr));
VERIFY_IS_NOT_NULL(pRSBlobReplace);
// Verify RS equal from source and replacing existing RS using
// setrootsignature option
VERIFY_ARE_EQUAL(pRSBlob->GetBufferSize(), pRSBlobReplace->GetBufferSize());
VERIFY_ARE_EQUAL(0, memcmp(pRSBlob->GetBufferPointer(),
pRSBlobReplace->GetBufferPointer(),
pRSBlob->GetBufferSize()));
}
TEST_F(CompilerTest, CompileSetPrivateThenWithStripPrivate) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target {\r\n"
" return 0;\r\n"
"}",
&pSource);
std::string privateTxt("private data");
CComPtr<IDxcBlobEncoding> pPrivate;
CreateBlobFromText(privateTxt.c_str(), &pPrivate);
// Add private data source to include handler
CComPtr<TestIncludeHandler> pInclude;
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back(pPrivate->GetBufferPointer(),
pPrivate->GetBufferSize());
LPCWSTR args[] = {L"-setprivate", L"privatesource.hlsl"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
hlsl::DxilContainerHeader *pContainerHeader = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_SUCCEEDED(
hlsl::IsValidDxilContainer(pContainerHeader, pProgram->GetBufferSize()));
hlsl::DxilPartHeader *pPartHeader = hlsl::GetDxilPartByType(
pContainerHeader, hlsl::DxilFourCC::DFCC_PrivateData);
VERIFY_IS_NOT_NULL(pPartHeader);
// Compare private data
std::string privatePart((const char *)(pPartHeader + 1), privateTxt.size());
VERIFY_IS_TRUE(strcmp(privatePart.c_str(), privateTxt.c_str()) == 0);
pResult.Release();
pProgram.Release();
// Add private data source to include handler
CComPtr<TestIncludeHandler> pInclude2;
pInclude2 = new TestIncludeHandler(m_dllSupport);
pInclude2->CallResults.emplace_back(pPrivate->GetBufferPointer(),
pPrivate->GetBufferSize());
LPCWSTR args2[] = {L"-setprivate", L"privatesource.hlsl", L"-Qstrip_priv"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args2, _countof(args2),
nullptr, 0, pInclude2, &pResult));
// Check error message when using Qstrip_private and setprivate together
HRESULT status;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_FAILED(status);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
LPCSTR pErrorMsg = "Cannot specify /Qstrip_priv and /setprivate together.";
CheckOperationResultMsgs(pResult, &pErrorMsg, 1, false, false);
}
TEST_F(CompilerTest, CompileWithMultiplePrivateOptionsThenFail) {
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
std::string main_source = R"x(
cbuffer MyCbuffer : register(b1) {
float4 my_cbuf_foo;
}
[RootSignature("CBV(b1)")]
float4 main() : SV_Target {
return my_cbuf_foo;
}
)x";
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(pUtils->CreateBlobFromPinned(
main_source.c_str(), main_source.size(), CP_UTF8, &pSource));
const WCHAR *args[] = {L"/Zs", L"/Qpdb_in_private", L"/Qstrip_priv"};
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
args, _countof(args), nullptr, 0, nullptr,
&pResult));
HRESULT status;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_FAILED(status);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
LPCSTR pErrorMsg =
"Cannot specify /Qstrip_priv and /Qpdb_in_private together.";
CheckOperationResultMsgs(pResult, &pErrorMsg, 1, false, false);
pResult.Release();
const WCHAR *args2[] = {L"/Zs", L"/Qpdb_in_private", L"/setprivate",
L"privatesource.hlsl"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
args2, _countof(args2), nullptr, 0,
nullptr, &pResult));
pErrors.Release();
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_FAILED(status);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
LPCSTR pErrorMsg2 =
"Cannot specify /Qpdb_in_private and /setprivate together.";
CheckOperationResultMsgs(pResult, &pErrorMsg2, 1, false, false);
}
TEST_F(CompilerTest, CompileWhenIncludeThenLoadInvoked) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"helper.h\"\r\n"
"float4 main() : SV_Target { return 0; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
pInclude, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_ARE_EQUAL_WSTR(L"." SLASH_W L"helper.h;",
pInclude->GetAllFileNames().c_str());
}
TEST_F(CompilerTest, CompileWhenIncludeThenLoadUsed) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"helper.h\"\r\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("#define ZERO 0");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
pInclude, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_ARE_EQUAL_WSTR(L"." SLASH_W L"helper.h;",
pInclude->GetAllFileNames().c_str());
}
static std::wstring NormalizeForPlatform(const std::wstring &s) {
#ifdef _WIN32
wchar_t From = L'/';
wchar_t To = L'\\';
#else
wchar_t From = L'\\';
wchar_t To = L'/';
#endif
std::wstring ret = s;
for (wchar_t &c : ret) {
if (c == From)
c = To;
}
return ret;
};
class SimpleIncludeHanlder : public IDxcIncludeHandler {
DXC_MICROCOM_REF_FIELD(m_dwRef)
public:
DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
dxc::DxcDllSupport &m_dllSupport;
HRESULT m_defaultErrorCode = E_FAIL;
SimpleIncludeHanlder(dxc::DxcDllSupport &dllSupport)
: m_dwRef(0), m_dllSupport(dllSupport) {}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject);
}
std::wstring Path;
std::string Content;
HRESULT STDMETHODCALLTYPE LoadSource(
LPCWSTR pFilename, // Filename as written in #include statement
IDxcBlob **ppIncludeSource // Resultant source object for included file
) override {
if (pFilename == Path) {
MultiByteStringToBlob(m_dllSupport, Content, CP_UTF8, ppIncludeSource);
return S_OK;
}
return E_FAIL;
}
};
TEST_F(CompilerTest, CompileWithIncludeThenTestNoLexicalBlockFile) {
std::string includeFile = R"x(
[RootSignature("")]
float main(uint x : X) : SV_Target {
float ret = 0;
if (x) {
float other_ret = 1;
ret = other_ret;
}
return ret;
}
)x";
std::string mainFile = R"(
#include "include.h"
)";
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<SimpleIncludeHanlder> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(mainFile.c_str(), &pSource);
pInclude = new SimpleIncludeHanlder(m_dllSupport);
pInclude->Content = includeFile;
pInclude->Path = L"." SLASH_W "include.h";
std::vector<const WCHAR *> args = {L"/Zi", L"/Od"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"MyShader.hlsl", L"main",
L"ps_6_0", args.data(), args.size(),
nullptr, 0, pInclude, &pResult));
CComPtr<IDxcResult> pRealResult;
VERIFY_SUCCEEDED(pResult.QueryInterface(&pRealResult));
CComPtr<IDxcBlob> pDxil;
VERIFY_SUCCEEDED(
pRealResult->GetOutput(DXC_OUT_OBJECT, IID_PPV_ARGS(&pDxil), nullptr));
CComPtr<IDxcBlobEncoding> pDisasm;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pDxil, &pDisasm));
CComPtr<IDxcBlobUtf8> pDisasmUtf8;
VERIFY_SUCCEEDED(pDisasm.QueryInterface(&pDisasmUtf8));
std::string disasm(pDisasmUtf8->GetStringPointer(),
pDisasmUtf8->GetStringLength());
VERIFY_IS_TRUE(disasm.find("!DILexicalBlock") != std::string::npos);
VERIFY_IS_TRUE(disasm.find("!DILexicalBlockFile") == std::string::npos);
}
TEST_F(CompilerTest, TestPdbUtilsPathNormalizations) {
#include "TestHeaders/TestPdbUtilsPathNormalizations.h"
struct TestCase {
std::string MainName;
std::string IncludeName;
};
TestCase tests[] = {
{R"(main.hlsl)", R"(include.h)"},
{R"(.\5Cmain.hlsl)", R"(.\5Cinclude.h)"},
{R"(/path/main.hlsl)", R"(/path/include.h)"},
{R"(\5Cpath/main.hlsl)", R"(\5Cpath\5Cinclude.h)"},
{R"(..\5Cmain.hlsl)", R"(..\5Cinclude.h)"},
{R"(..\5Cdir\5Cmain.hlsl)", R"(..\5Cdir\5Cinclude.h)"},
{R"(F:\5C\5Cdir\5Cmain.hlsl)", R"(F:\5C\5Cdir\5Cinclude.h)"},
{R"(\5C\5Cdir\5Cmain.hlsl)", R"(\5C\5Cdir\5Cinclude.h)"},
{R"(\5C\5C\5Cdir\5Cmain.hlsl)", R"(\5C\5C\5Cdir\5Cinclude.h)"},
{R"(//dir\5Cmain.hlsl)", R"(//dir/include.h)"},
{R"(///dir/main.hlsl)", R"(///dir\5Cinclude.h)"},
};
for (TestCase &test : tests) {
std::string oldPdb = kTestPdbUtilsPathNormalizationsIR;
size_t findPos = std::string::npos;
std::string mainPattern = "<MAIN_FILE>";
std::string includePattern = "<INCLUDE_FILE>";
while ((findPos = oldPdb.find(mainPattern)) != std::string::npos) {
oldPdb.replace(oldPdb.begin() + findPos,
oldPdb.begin() + findPos + mainPattern.size(),
test.MainName);
}
while ((findPos = oldPdb.find(includePattern)) != std::string::npos) {
oldPdb.replace(oldPdb.begin() + findPos,
oldPdb.begin() + findPos + includePattern.size(),
test.IncludeName);
}
CComPtr<IDxcAssembler> pAssembler;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcBlobEncoding> pBlobEncoding;
VERIFY_SUCCEEDED(pUtils->CreateBlobFromPinned(oldPdb.data(), oldPdb.size(),
CP_UTF8, &pBlobEncoding));
CComPtr<IDxcOperationResult> pOpResult;
VERIFY_SUCCEEDED(
pAssembler->AssembleToContainer(pBlobEncoding, &pOpResult));
VerifyOperationSucceeded(pOpResult);
CComPtr<IDxcBlob> pDxil;
VERIFY_SUCCEEDED(pOpResult->GetResult(&pDxil));
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
VERIFY_SUCCEEDED(pPdbUtils->Load(pDxil));
CComBSTR pMainName;
CComBSTR pIncludeName;
CComBSTR pMainName2;
CComPtr<IDxcBlobEncoding> pIncludeContent;
CComPtr<IDxcBlobEncoding> pMainContent;
VERIFY_SUCCEEDED(pPdbUtils->GetSourceName(0, &pMainName));
VERIFY_SUCCEEDED(pPdbUtils->GetSourceName(1, &pIncludeName));
VERIFY_SUCCEEDED(pPdbUtils->GetMainFileName(&pMainName2));
VERIFY_SUCCEEDED(pPdbUtils->GetSource(0, &pMainContent));
VERIFY_SUCCEEDED(pPdbUtils->GetSource(1, &pIncludeContent));
VERIFY_ARE_EQUAL(0, wcscmp(pMainName.m_str, pMainName2.m_str));
CComPtr<IDxcBlobUtf8> pMainContentUtf8;
CComPtr<IDxcBlobUtf8> pIncludeContentUtf8;
VERIFY_SUCCEEDED(pMainContent.QueryInterface(&pMainContentUtf8));
VERIFY_SUCCEEDED(pIncludeContent.QueryInterface(&pIncludeContentUtf8));
CComPtr<SimpleIncludeHanlder> pRecompileInclude =
new SimpleIncludeHanlder(m_dllSupport);
pRecompileInclude->Content =
std::string(pIncludeContentUtf8->GetStringPointer(),
pIncludeContentUtf8->GetStringLength());
pRecompileInclude->Path = pIncludeName;
CComPtr<IDxcOperationResult> pRecompileOpResult;
const WCHAR *args[] = {L"-Zi"};
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
VERIFY_SUCCEEDED(pCompiler->Compile(
pMainContentUtf8, pMainName, L"main", L"ps_6_0", args, _countof(args),
nullptr, 0, pRecompileInclude, &pRecompileOpResult));
VerifyOperationSucceeded(pRecompileOpResult);
}
}
TEST_F(CompilerTest, CompileWhenAllIncludeCombinations) {
struct File {
std::wstring name;
std::string content;
};
struct TestCase {
std::wstring mainFileArg;
File mainFile;
File includeFile;
std::vector<const WCHAR *> extraArgs;
};
std::string commonIncludeFile = "float foo() { return 10; }";
TestCase tests[] = {
{L"main.hlsl",
{L".\\main.hlsl",
R"(#include "include.h"
float main() : SV_Target { return foo(); } )"},
{L".\\include.h", commonIncludeFile},
{}},
{L"./main.hlsl",
{L".\\main.hlsl",
R"(#include "include.h"
float main() : SV_Target { return foo(); } )"},
{L".\\include.h", commonIncludeFile},
{}},
{L"../main.hlsl",
{L".\\..\\main.hlsl",
R"(#include "include.h"\n
float main() : SV_Target { return foo(); } )"},
{L".\\..\\include.h", commonIncludeFile},
{}},
{L"../main.hlsl",
{L".\\..\\main.hlsl",
R"(#include "include_dir/include.h"
float main() : SV_Target { return foo(); } )"},
{L".\\..\\include_dir\\include.h", commonIncludeFile},
{}},
{L"../main.hlsl",
{L".\\..\\main.hlsl",
R"(#include "../include.h"
float main() : SV_Target { return foo(); } )"},
{L".\\..\\..\\include.h", commonIncludeFile},
{}},
{L"../main.hlsl",
{L".\\..\\main.hlsl",
R"(#include "second_dir/include.h"
float main() : SV_Target { return foo(); } )"},
{L".\\..\\my_include_dir\\second_dir\\include.h", commonIncludeFile},
{L"-I", L"../my_include_dir"}},
{L"../main.hlsl",
{L".\\..\\main.hlsl",
R"(#include "second_dir/include.h"
float main() : SV_Target { return foo(); } )"},
{L".\\my_include_dir\\second_dir\\include.h", commonIncludeFile},
{L"-I", L"my_include_dir"}},
#ifdef _WIN32
{L"../main.hlsl",
{L".\\..\\main.hlsl",
R"(#include "\\my_include_dir\\second_dir/include.h" // <-- Network path
float main() : SV_Target { return foo(); } )"},
{L"\\\\my_include_dir\\second_dir\\include.h", commonIncludeFile},
{}},
#else
{L"../main.hlsl",
{L".\\..\\main.hlsl",
R"(#include "/my_include_dir\\second_dir/include.h" // <-- Unix absolute path
float main() : SV_Target { return foo(); } )"},
{L"/my_include_dir\\second_dir\\include.h", commonIncludeFile},
{}},
#endif
};
for (TestCase &t : tests) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<SimpleIncludeHanlder> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(t.mainFile.content.c_str(), &pSource);
pInclude = new SimpleIncludeHanlder(m_dllSupport);
pInclude->Content = t.includeFile.content;
pInclude->Path = NormalizeForPlatform(t.includeFile.name);
std::vector<const WCHAR *> args = {L"-Zi", L"-Qembed_debug"};
args.insert(args.end(), t.extraArgs.begin(), t.extraArgs.end());
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, t.mainFileArg.c_str(), L"main",
L"ps_6_0", args.data(), args.size(),
nullptr, 0, pInclude, &pResult));
CComPtr<IDxcBlob> pPdb;
CComPtr<IDxcBlob> pDxil;
CComPtr<IDxcResult> pRealResult;
VERIFY_SUCCEEDED(pResult.QueryInterface(&pRealResult));
VERIFY_SUCCEEDED(
pRealResult->GetOutput(DXC_OUT_PDB, IID_PPV_ARGS(&pPdb), nullptr));
VERIFY_SUCCEEDED(
pRealResult->GetOutput(DXC_OUT_OBJECT, IID_PPV_ARGS(&pDxil), nullptr));
IDxcBlob *debugBlobs[] = {pPdb, pDxil};
for (IDxcBlob *pDbgBlob : debugBlobs) {
CComPtr<IDxcPdbUtils> pPdbUtils;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcPdbUtils, &pPdbUtils));
VERIFY_SUCCEEDED(pPdbUtils->Load(pDbgBlob));
CComBSTR pMainFileName;
VERIFY_SUCCEEDED(pPdbUtils->GetMainFileName(&pMainFileName));
VERIFY_ARE_EQUAL(NormalizeForPlatform(t.mainFile.name),
pMainFileName.m_str);
pMainFileName.Empty();
VERIFY_SUCCEEDED(pPdbUtils->GetSourceName(0, &pMainFileName));
VERIFY_ARE_EQUAL(NormalizeForPlatform(t.mainFile.name),
pMainFileName.m_str);
CComBSTR pIncludeName;
VERIFY_SUCCEEDED(pPdbUtils->GetSourceName(1, &pIncludeName));
VERIFY_ARE_EQUAL(NormalizeForPlatform(t.includeFile.name),
pIncludeName.m_str);
CComPtr<IDxcBlobEncoding> pMainSource;
VERIFY_SUCCEEDED(pPdbUtils->GetSource(0, &pMainSource));
CComPtr<SimpleIncludeHanlder> pRecompileInclude =
new SimpleIncludeHanlder(m_dllSupport);
pRecompileInclude->Content = t.includeFile.content;
pRecompileInclude->Path = pIncludeName;
CComPtr<IDxcOperationResult> pRecompileOpResult;
VERIFY_SUCCEEDED(pCompiler->Compile(
pMainSource, pMainFileName, L"main", L"ps_6_0", args.data(),
args.size(), nullptr, 0, pRecompileInclude, &pRecompileOpResult));
VerifyOperationSucceeded(pRecompileOpResult);
}
}
}
TEST_F(CompilerTest, CompileWhenIncludeAbsoluteThenLoadAbsolute) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
#ifdef _WIN32 // OS-specific root
CreateBlobFromText("#include \"C:\\helper.h\"\r\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
#else
CreateBlobFromText("#include \"/helper.h\"\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
#endif
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("#define ZERO 0");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
pInclude, &pResult));
VerifyOperationSucceeded(pResult);
#ifdef _WIN32 // OS-specific root
VERIFY_ARE_EQUAL_WSTR(L"C:\\helper.h;", pInclude->GetAllFileNames().c_str());
#else
VERIFY_ARE_EQUAL_WSTR(L"/helper.h;", pInclude->GetAllFileNames().c_str());
#endif
}
TEST_F(CompilerTest, CompileWhenIncludeLocalThenLoadRelative) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"..\\helper.h\"\r\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("#define ZERO 0");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
pInclude, &pResult));
VerifyOperationSucceeded(pResult);
#ifdef _WIN32 // OS-specific directory dividers
VERIFY_ARE_EQUAL_WSTR(L".\\..\\helper.h;",
pInclude->GetAllFileNames().c_str());
#else
VERIFY_ARE_EQUAL_WSTR(L"./../helper.h;", pInclude->GetAllFileNames().c_str());
#endif
}
TEST_F(CompilerTest, CompileWhenIncludeSystemThenLoadNotRelative) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"subdir/other/file.h\"\r\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
LPCWSTR args[] = {L"-Ifoo"};
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("#include <helper.h>");
pInclude->CallResults.emplace_back("#define ZERO 0");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude, &pResult));
VerifyOperationSucceeded(pResult);
#ifdef _WIN32 // OS-specific directory dividers
VERIFY_ARE_EQUAL_WSTR(L".\\subdir\\other\\file.h;.\\foo\\helper.h;",
pInclude->GetAllFileNames().c_str());
#else
VERIFY_ARE_EQUAL_WSTR(L"./subdir/other/file.h;./foo/helper.h;",
pInclude->GetAllFileNames().c_str());
#endif
}
TEST_F(CompilerTest, CompileWhenIncludeSystemMissingThenLoadAttempt) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"subdir/other/file.h\"\r\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("#include <helper.h>");
pInclude->CallResults.emplace_back("#define ZERO 0");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
pInclude, &pResult));
std::string failLog(VerifyOperationFailed(pResult));
VERIFY_ARE_NOT_EQUAL(
std::string::npos,
failLog.find("<angled>")); // error message should prompt to use <angled>
// rather than "quotes"
#ifdef _WIN32
VERIFY_ARE_EQUAL_WSTR(L".\\subdir\\other\\file.h;.\\subdir\\other\\helper.h;",
pInclude->GetAllFileNames().c_str());
#else
VERIFY_ARE_EQUAL_WSTR(L"./subdir/other/file.h;./subdir/other/helper.h;",
pInclude->GetAllFileNames().c_str());
#endif
}
TEST_F(CompilerTest, CompileWhenIncludeFlagsThenIncludeUsed) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include <helper.h>\r\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("#define ZERO 0");
#ifdef _WIN32 // OS-specific root
LPCWSTR args[] = {L"-I\\\\server\\share"};
#else
LPCWSTR args[] = {L"-I/server/share"};
#endif
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude, &pResult));
VerifyOperationSucceeded(pResult);
#ifdef _WIN32 // OS-specific root
VERIFY_ARE_EQUAL_WSTR(L"\\\\server\\share\\helper.h;",
pInclude->GetAllFileNames().c_str());
#else
VERIFY_ARE_EQUAL_WSTR(L"/server/share/helper.h;",
pInclude->GetAllFileNames().c_str());
#endif
}
TEST_F(CompilerTest, CompileThenCheckDisplayIncludeProcess) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"inc/helper.h\"\r\n"
"float4 main() : SV_Target { return ZERO; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("#define ZERO 0");
LPCWSTR args[] = {L"-I inc", L"-Vi"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude, &pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcResult> pCompileResult;
CComPtr<IDxcBlob> pRemarkBlob;
pResult->QueryInterface(&pCompileResult);
VERIFY_SUCCEEDED(pCompileResult->GetOutput(
DXC_OUT_REMARKS, IID_PPV_ARGS(&pRemarkBlob), nullptr));
std::string text(BlobToUtf8(pRemarkBlob));
VERIFY_ARE_NOT_EQUAL(
string::npos, text.find("Opening file [./inc/helper.h], stack top [0]"));
}
TEST_F(CompilerTest, CompileThenPrintTimeReport) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0.0; }", &pSource);
LPCWSTR args[] = {L"-ftime-report"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude, &pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcResult> pCompileResult;
CComPtr<IDxcBlob> pReportBlob;
pResult->QueryInterface(&pCompileResult);
VERIFY_SUCCEEDED(pCompileResult->GetOutput(
DXC_OUT_TIME_REPORT, IID_PPV_ARGS(&pReportBlob), nullptr));
std::string text(BlobToUtf8(pReportBlob));
VERIFY_ARE_NOT_EQUAL(string::npos,
text.find("... Pass execution timing report ..."));
}
TEST_F(CompilerTest, CompileThenPrintTimeTrace) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0.0; }", &pSource);
LPCWSTR args[] = {L"-ftime-trace"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args), nullptr,
0, pInclude, &pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcResult> pCompileResult;
CComPtr<IDxcBlob> pReportBlob;
pResult->QueryInterface(&pCompileResult);
VERIFY_SUCCEEDED(pCompileResult->GetOutput(
DXC_OUT_TIME_TRACE, IID_PPV_ARGS(&pReportBlob), nullptr));
std::string text(BlobToUtf8(pReportBlob));
VERIFY_ARE_NOT_EQUAL(string::npos, text.find("{ \"traceEvents\": ["));
}
TEST_F(CompilerTest, CompileWhenIncludeMissingThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"file.h\"\r\n"
"float4 main() : SV_Target { return 0; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
pInclude, &pResult));
HRESULT hr;
VERIFY_SUCCEEDED(pResult->GetStatus(&hr));
VERIFY_FAILED(hr);
}
TEST_F(CompilerTest, CompileWhenIncludeHasPathThenOK) {
CComPtr<IDxcCompiler> pCompiler;
LPCWSTR Source = L"c:\\temp\\OddIncludes\\main.hlsl";
LPCWSTR Args[] = {L"/I", L"c:\\temp"};
LPCWSTR ArgsUp[] = {L"/I", L"c:\\Temp"};
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
bool useUpValues[] = {false, true};
for (bool useUp : useUpValues) {
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
#if TEST_ON_DISK
CComPtr<IDxcLibrary> pLibrary;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
VERIFY_SUCCEEDED(pLibrary->CreateIncludeHandler(&pInclude));
VERIFY_SUCCEEDED(pLibrary->CreateBlobFromFile(Source, nullptr, &pSource));
#else
CComPtr<TestIncludeHandler> pInclude;
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back("// Empty");
CreateBlobFromText("#include \"include.hlsl\"\r\n"
"float4 main() : SV_Target { return 0; }",
&pSource);
#endif
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, Source, L"main", L"ps_6_0",
useUp ? ArgsUp : Args, _countof(Args),
nullptr, 0, pInclude, &pResult));
HRESULT hr;
VERIFY_SUCCEEDED(pResult->GetStatus(&hr));
VERIFY_SUCCEEDED(hr);
}
}
TEST_F(CompilerTest, CompileWhenIncludeEmptyThenOK) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#include \"empty.h\"\r\n"
"float4 main() : SV_Target { return 0; }",
&pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back(
"", CP_ACP); // An empty file would get detected as ACP code page
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
pInclude, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_ARE_EQUAL_WSTR(L"." SLASH_W L"empty.h;",
pInclude->GetAllFileNames().c_str());
}
static const char EmptyCompute[] = "[numthreads(8,8,1)] void main() { }";
TEST_F(CompilerTest, CompileWhenODumpThenCheckNoSink) {
struct Check {
std::vector<const WCHAR *> Args;
std::vector<const WCHAR *> Passes;
};
Check Checks[] = {
{{L"-Odump"},
{L"-instcombine,NoSink=0", L"-dxil-loop-deletion,NoSink=0"}},
{{L"-Odump", L"-opt-disable sink"},
{L"-instcombine,NoSink=1", L"-dxil-loop-deletion,NoSink=1"}},
};
for (Check &C : Checks) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(EmptyCompute, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"cs_6_0", C.Args.data(), C.Args.size(),
nullptr, 0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcBlob> pResultBlob;
VERIFY_SUCCEEDED(pResult->GetResult(&pResultBlob));
wstring passes = BlobToWide(pResultBlob);
for (const WCHAR *pPattern : C.Passes) {
VERIFY_ARE_NOT_EQUAL(wstring::npos, passes.find(pPattern));
}
}
}
TEST_F(CompilerTest, CompileWhenODumpThenPassConfig) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(EmptyCompute, &pSource);
LPCWSTR Args[] = {L"/Odump"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"cs_6_0", Args, _countof(Args), nullptr,
0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcBlob> pResultBlob;
VERIFY_SUCCEEDED(pResult->GetResult(&pResultBlob));
wstring passes = BlobToWide(pResultBlob);
VERIFY_ARE_NOT_EQUAL(wstring::npos, passes.find(L"inline"));
}
TEST_F(CompilerTest, CompileWhenVdThenProducesDxilContainer) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(EmptyCompute, &pSource);
LPCWSTR Args[] = {L"/Vd"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"cs_6_0", Args, _countof(Args), nullptr,
0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcBlob> pResultBlob;
VERIFY_SUCCEEDED(pResult->GetResult(&pResultBlob));
VERIFY_IS_TRUE(
hlsl::IsValidDxilContainer(reinterpret_cast<hlsl::DxilContainerHeader *>(
pResultBlob->GetBufferPointer()),
pResultBlob->GetBufferSize()));
}
void CompilerTest::TestEncodingImpl(const void *sourceData, size_t sourceSize,
UINT32 codePage, const void *includedData,
size_t includedSize,
const WCHAR *encoding) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<TestIncludeHandler> pInclude;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobPinned((const char *)sourceData, sourceSize, codePage, &pSource);
pInclude = new TestIncludeHandler(m_dllSupport);
pInclude->CallResults.emplace_back(includedData, includedSize, CP_ACP);
const WCHAR *pArgs[] = {L"-encoding", encoding};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", pArgs, _countof(pArgs),
nullptr, 0, pInclude, &pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
}
TEST_F(CompilerTest, CompileWithEncodeFlagTestSource) {
std::string sourceUtf8 = "#include \"include.hlsl\"\r\n"
"float4 main() : SV_Target { return 0; }";
std::string includeUtf8 = "// Comment\n";
std::string utf8BOM = "\xEF"
"\xBB"
"\xBF"; // UTF-8 BOM
std::string includeUtf8BOM = utf8BOM + includeUtf8;
std::wstring sourceWide = L"#include \"include.hlsl\"\r\n"
L"float4 main() : SV_Target { return 0; }";
std::wstring includeWide = L"// Comments\n";
std::wstring utf16BOM = L"\xFEFF"; // UTF-16 LE BOM
std::wstring includeUtf16BOM = utf16BOM + includeWide;
// Included files interpreted with encoding option if no BOM
TestEncodingImpl(sourceUtf8.data(), sourceUtf8.size(), DXC_CP_UTF8,
includeUtf8.data(), includeUtf8.size(), L"utf8");
TestEncodingImpl(sourceWide.data(), sourceWide.size() * sizeof(L'A'),
DXC_CP_WIDE, includeWide.data(),
includeWide.size() * sizeof(L'A'), L"wide");
// Encoding option ignored if BOM present
TestEncodingImpl(sourceUtf8.data(), sourceUtf8.size(), DXC_CP_UTF8,
includeUtf8BOM.data(), includeUtf8BOM.size(), L"wide");
TestEncodingImpl(sourceWide.data(), sourceWide.size() * sizeof(L'A'),
DXC_CP_WIDE, includeUtf16BOM.data(),
includeUtf16BOM.size() * sizeof(L'A'), L"utf8");
// Source file interpreted according to DxcBuffer encoding if not CP_ACP
// Included files interpreted with encoding option if no BOM
TestEncodingImpl(sourceUtf8.data(), sourceUtf8.size(), DXC_CP_UTF8,
includeWide.data(), includeWide.size() * sizeof(L'A'),
L"wide");
TestEncodingImpl(sourceWide.data(), sourceWide.size() * sizeof(L'A'),
DXC_CP_WIDE, includeUtf8.data(), includeUtf8.size(),
L"utf8");
// Source file interpreted by encoding option if source DxcBuffer encoding =
// CP_ACP (default)
TestEncodingImpl(sourceUtf8.data(), sourceUtf8.size(), DXC_CP_ACP,
includeUtf8.data(), includeUtf8.size(), L"utf8");
TestEncodingImpl(sourceWide.data(), sourceWide.size() * sizeof(L'A'),
DXC_CP_ACP, includeWide.data(),
includeWide.size() * sizeof(L'A'), L"wide");
}
TEST_F(CompilerTest, CompileWhenODumpThenOptimizerMatch) {
LPCWSTR OptLevels[] = {L"/Od", L"/O1", L"/O2"};
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOptimizer> pOptimizer;
CComPtr<IDxcAssembler> pAssembler;
CComPtr<IDxcValidator> pValidator;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcValidator, &pValidator));
for (LPCWSTR OptLevel : OptLevels) {
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pHighLevelBlob;
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlob> pAssembledBlob;
// Could use EmptyCompute and cs_6_0, but there is an issue where properties
// don't round-trip properly at high-level, so validation fails because
// dimensions are set to zero. Workaround by using pixel shader instead.
LPCWSTR Target = L"ps_6_0";
CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
LPCWSTR Args[2] = {OptLevel, L"/Odump"};
// Get the passes for this optimization level.
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
Target, Args, _countof(Args), nullptr,
0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcBlob> pResultBlob;
VERIFY_SUCCEEDED(pResult->GetResult(&pResultBlob));
wstring passes = BlobToWide(pResultBlob);
// Get wchar_t version and prepend hlsl-hlensure, to do a split
// high-level/opt compilation pass.
std::vector<LPCWSTR> Options;
SplitPassList(const_cast<LPWSTR>(passes.data()), Options);
// Now compile directly.
pResult.Release();
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
Target, Args, 1, nullptr, 0, nullptr,
&pResult));
VerifyOperationSucceeded(pResult);
// Now compile via a high-level compile followed by the optimization passes.
pResult.Release();
Args[_countof(Args) - 1] = L"/fcgl";
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
Target, Args, _countof(Args), nullptr,
0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pHighLevelBlob));
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(pHighLevelBlob, Options.data(),
Options.size(), &pOptimizedModule,
nullptr));
string text = DisassembleProgram(m_dllSupport, pOptimizedModule);
WEX::Logging::Log::Comment(L"Final program:");
WEX::Logging::Log::Comment(CA2W(text.c_str()));
// At the very least, the module should be valid.
pResult.Release();
VERIFY_SUCCEEDED(
pAssembler->AssembleToContainer(pOptimizedModule, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pAssembledBlob));
pResult.Release();
VERIFY_SUCCEEDED(pValidator->Validate(pAssembledBlob,
DxcValidatorFlags_Default, &pResult));
VerifyOperationSucceeded(pResult);
}
}
static const UINT CaptureStacks = 0; // Set to 1 to enable captures
static const UINT StackFrameCount = 12;
struct InstrumentedHeapMalloc : public IMalloc {
private:
HANDLE m_Handle; // Heap handle.
ULONG m_RefCount =
0; // Reference count. Used for reference leaks, not for lifetime.
ULONG m_AllocCount = 0; // Total # of alloc and realloc requests.
ULONG m_AllocSize = 0; // Total # of alloc and realloc bytes.
ULONG m_Size = 0; // Current # of alloc'ed bytes.
ULONG m_FailAlloc = 0; // If nonzero, the alloc/realloc call to fail.
// Each allocation also tracks the following information:
// - allocation callstack
// - deallocation callstack
// - prior/next blocks in a list of allocated blocks
LIST_ENTRY AllocList;
struct PtrData {
LIST_ENTRY Entry;
LPVOID AllocFrames[CaptureStacks ? StackFrameCount * CaptureStacks : 1];
LPVOID FreeFrames[CaptureStacks ? StackFrameCount * CaptureStacks : 1];
UINT64 AllocAtCount;
DWORD AllocFrameCount;
DWORD FreeFrameCount;
SIZE_T Size;
PtrData *Self;
};
PtrData *DataFromPtr(void *p) {
if (p == nullptr)
return nullptr;
PtrData *R = ((PtrData *)p) - 1;
if (R != R->Self) {
VERIFY_FAIL(); // p is invalid or underrun
}
return R;
}
public:
InstrumentedHeapMalloc() : m_Handle(nullptr) { ResetCounts(); }
~InstrumentedHeapMalloc() {
if (m_Handle)
HeapDestroy(m_Handle);
}
void ResetHeap() {
if (m_Handle) {
HeapDestroy(m_Handle);
m_Handle = nullptr;
}
m_Handle = HeapCreate(HEAP_NO_SERIALIZE, 0, 0);
}
ULONG GetRefCount() const { return m_RefCount; }
ULONG GetAllocCount() const { return m_AllocCount; }
ULONG GetAllocSize() const { return m_AllocSize; }
ULONG GetSize() const { return m_Size; }
void ResetCounts() {
m_RefCount = m_AllocCount = m_AllocSize = m_Size = 0;
AllocList.Blink = AllocList.Flink = &AllocList;
}
void SetFailAlloc(ULONG index) { m_FailAlloc = index; }
ULONG STDMETHODCALLTYPE AddRef() override { return ++m_RefCount; }
ULONG STDMETHODCALLTYPE Release() override {
if (m_RefCount == 0)
VERIFY_FAIL();
return --m_RefCount;
}
STDMETHODIMP QueryInterface(REFIID iid, void **ppvObject) override {
return DoBasicQueryInterface<IMalloc>(this, iid, ppvObject);
}
virtual void *STDMETHODCALLTYPE Alloc(SIZE_T cb) override {
++m_AllocCount;
if (m_FailAlloc && m_AllocCount >= m_FailAlloc) {
return nullptr; // breakpoint for i failure - m_FailAlloc == 1+VAL
}
m_AllocSize += cb;
m_Size += cb;
PtrData *P =
(PtrData *)HeapAlloc(m_Handle, HEAP_ZERO_MEMORY, sizeof(PtrData) + cb);
P->Entry.Flink = AllocList.Flink;
P->Entry.Blink = &AllocList;
AllocList.Flink->Blink = &(P->Entry);
AllocList.Flink = &(P->Entry);
// breakpoint for i failure on NN alloc - m_FailAlloc == 1+VAL &&
// m_AllocCount == NN breakpoint for happy path for NN alloc - m_AllocCount
// == NN
P->AllocAtCount = m_AllocCount;
#ifndef __ANDROID__
if (CaptureStacks)
P->AllocFrameCount =
CaptureStackBackTrace(1, StackFrameCount, P->AllocFrames, nullptr);
#endif // __ANDROID__
P->Size = cb;
P->Self = P;
return P + 1;
}
virtual void *STDMETHODCALLTYPE Realloc(void *pv, SIZE_T cb) override {
SIZE_T priorSize = pv == nullptr ? (SIZE_T)0 : GetSize(pv);
void *R = Alloc(cb);
if (!R)
return nullptr;
SIZE_T copySize = std::min(cb, priorSize);
memcpy(R, pv, copySize);
Free(pv);
return R;
}
virtual void STDMETHODCALLTYPE Free(void *pv) override {
if (!pv)
return;
PtrData *P = DataFromPtr(pv);
if (P->FreeFrameCount)
VERIFY_FAIL(); // double-free detected
m_Size -= P->Size;
P->Entry.Flink->Blink = P->Entry.Blink;
P->Entry.Blink->Flink = P->Entry.Flink;
#ifndef __ANDROID__
if (CaptureStacks)
P->FreeFrameCount =
CaptureStackBackTrace(1, StackFrameCount, P->FreeFrames, nullptr);
#endif // __ANDROID__
}
virtual SIZE_T STDMETHODCALLTYPE GetSize(void *pv) override {
if (pv == nullptr)
return 0;
return DataFromPtr(pv)->Size;
}
virtual int STDMETHODCALLTYPE DidAlloc(void *pv) override {
return -1; // don't know
}
virtual void STDMETHODCALLTYPE HeapMinimize(void) override {}
void DumpLeaks() {
PtrData *ptr = (PtrData *)AllocList.Flink;
;
PtrData *end = (PtrData *)AllocList.Blink;
;
WEX::Logging::Log::Comment(
FormatToWString(L"Leaks total size: %d", (signed int)m_Size).data());
while (ptr != end) {
WEX::Logging::Log::Comment(
FormatToWString(L"Memory leak at 0x0%X, size %d, alloc# %d", ptr + 1,
ptr->Size, ptr->AllocAtCount)
.data());
ptr = (PtrData *)ptr->Entry.Flink;
}
}
};
#if _ITERATOR_DEBUG_LEVEL == 0
// CompileWhenNoMemThenOOM can properly detect leaks only when debug iterators
// are disabled
#ifdef _WIN32
TEST_F(CompilerTest, CompileWhenNoMemThenOOM) {
#else
// Disabled it is ignored above
TEST_F(CompilerTest, DISABLED_CompileWhenNoMemThenOOM) {
#endif
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
CComPtr<IDxcBlobEncoding> pSource;
CreateBlobFromText(EmptyCompute, &pSource);
InstrumentedHeapMalloc InstrMalloc;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
ULONG allocCount = 0;
ULONG allocSize = 0;
ULONG initialRefCount;
InstrMalloc.ResetHeap();
VERIFY_IS_TRUE(m_dllSupport.HasCreateWithMalloc());
// Verify a simple object creation.
initialRefCount = InstrMalloc.GetRefCount();
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance2(&InstrMalloc, CLSID_DxcCompiler,
&pCompiler));
pCompiler.Release();
VERIFY_IS_TRUE(0 == InstrMalloc.GetSize());
VERIFY_ARE_EQUAL(initialRefCount, InstrMalloc.GetRefCount());
InstrMalloc.ResetCounts();
InstrMalloc.ResetHeap();
// First time, run to completion and capture stats.
initialRefCount = InstrMalloc.GetRefCount();
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance2(&InstrMalloc, CLSID_DxcCompiler,
&pCompiler));
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"cs_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
allocCount = InstrMalloc.GetAllocCount();
allocSize = InstrMalloc.GetAllocSize();
HRESULT hrWithMemory;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrWithMemory));
VERIFY_SUCCEEDED(hrWithMemory);
pCompiler.Release();
pResult.Release();
VERIFY_IS_TRUE(allocSize > allocCount);
// Ensure that after all resources are released, there are no outstanding
// allocations or references.
//
// First leak is in ((InstrumentedHeapMalloc::PtrData
// *)InstrMalloc.AllocList.Flink)
if (InstrMalloc.GetSize() != 0) {
WEX::Logging::Log::Comment(L"Memory leak(s) detected");
InstrMalloc.DumpLeaks();
VERIFY_IS_TRUE(0 == InstrMalloc.GetSize());
}
VERIFY_ARE_EQUAL(initialRefCount, InstrMalloc.GetRefCount());
// In Debug, without /D_ITERATOR_DEBUG_LEVEL=0, debug iterators will be used;
// this causes a problem where std::string is specified as noexcept, and yet
// a sentinel is allocated that may fail and throw.
if (m_ver.SkipOutOfMemoryTest())
return;
// Now, fail each allocation and make sure we get an error.
for (ULONG i = 0; i <= allocCount; ++i) {
// LogCommentFmt(L"alloc fail %u", i);
bool isLast = i == allocCount;
InstrMalloc.ResetCounts();
InstrMalloc.ResetHeap();
InstrMalloc.SetFailAlloc(i + 1);
HRESULT hrOp = m_dllSupport.CreateInstance2(&InstrMalloc, CLSID_DxcCompiler,
&pCompiler);
if (SUCCEEDED(hrOp)) {
hrOp = pCompiler->Compile(pSource, L"source.hlsl", L"main", L"cs_6_0",
nullptr, 0, nullptr, 0, nullptr, &pResult);
if (SUCCEEDED(hrOp)) {
pResult->GetStatus(&hrOp);
}
}
if (FAILED(hrOp)) {
// This is true in *almost* every case. When the OOM happens during stream
// handling, there is no specific error set; by the time it's detected,
// it propagates as E_FAIL.
// VERIFY_ARE_EQUAL(hrOp, E_OUTOFMEMORY);
VERIFY_IS_TRUE(hrOp == E_OUTOFMEMORY || hrOp == E_FAIL);
}
if (isLast)
VERIFY_SUCCEEDED(hrOp);
else
VERIFY_FAILED(hrOp);
pCompiler.Release();
pResult.Release();
if (InstrMalloc.GetSize() != 0) {
WEX::Logging::Log::Comment(
FormatToWString(L"Memory leak(s) detected, allocCount = %d", i)
.data());
InstrMalloc.DumpLeaks();
VERIFY_IS_TRUE(0 == InstrMalloc.GetSize());
}
VERIFY_ARE_EQUAL(initialRefCount, InstrMalloc.GetRefCount());
}
}
#endif
TEST_F(CompilerTest, CompileWhenShaderModelMismatchAttributeThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(EmptyCompute, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
std::string failLog(VerifyOperationFailed(pResult));
VERIFY_ARE_NOT_EQUAL(string::npos,
failLog.find("attribute numthreads only valid for CS"));
}
TEST_F(CompilerTest, CompileBadHlslThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("bad hlsl", &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_FAILED(status);
}
TEST_F(CompilerTest, CompileLegacyShaderModelThenFail) {
VerifyCompileFailed(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
L"ps_5_1", nullptr);
}
TEST_F(CompilerTest, CompileWhenRecursiveAlbeitStaticTermThenFail) {
// This shader will compile under fxc because if execution is
// simulated statically, it does terminate. dxc changes this behavior
// to avoid imposing the requirement on the compiler.
const char ShaderText[] =
"static int i = 10;\r\n"
"float4 f(); // Forward declaration\r\n"
"float4 g() { if (i > 10) { i--; return f(); } else return 0; } // "
"Recursive call to 'f'\r\n"
"float4 f() { return g(); } // First call to 'g'\r\n"
"float4 VS() : SV_Position{\r\n"
" return f(); // First call to 'f'\r\n"
"}\r\n";
VerifyCompileFailed(ShaderText, L"vs_6_0",
"recursive functions are not allowed: function "
"'VS' calls recursive function 'f'",
L"VS");
}
TEST_F(CompilerTest, CompileWhenRecursiveThenFail) {
const char ShaderTextSimple[] =
"float4 f(); // Forward declaration\r\n"
"float4 g() { return f(); } // Recursive call to 'f'\r\n"
"float4 f() { return g(); } // First call to 'g'\r\n"
"float4 main() : SV_Position{\r\n"
" return f(); // First call to 'f'\r\n"
"}\r\n";
VerifyCompileFailed(ShaderTextSimple, L"vs_6_0",
"recursive functions are not allowed: "
"function 'main' calls recursive function 'f'");
const char ShaderTextIndirect[] =
"float4 f(); // Forward declaration\r\n"
"float4 g() { return f(); } // Recursive call to 'f'\r\n"
"float4 f() { return g(); } // First call to 'g'\r\n"
"float4 main() : SV_Position{\r\n"
" return f(); // First call to 'f'\r\n"
"}\r\n";
VerifyCompileFailed(ShaderTextIndirect, L"vs_6_0",
"recursive functions are not allowed: "
"function 'main' calls recursive function 'f'");
const char ShaderTextSelf[] = "float4 main() : SV_Position{\r\n"
" return main();\r\n"
"}\r\n";
VerifyCompileFailed(ShaderTextSelf, L"vs_6_0",
"recursive functions are not allowed: "
"function 'main' calls recursive function 'main'");
const char ShaderTextMissing[] = "float4 mainz() : SV_Position{\r\n"
" return 1;\r\n"
"}\r\n";
VerifyCompileFailed(ShaderTextMissing, L"vs_6_0",
"missing entry point definition");
}
TEST_F(CompilerTest, CompileHlsl2015ThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2015"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_ARE_EQUAL(status, E_INVALIDARG);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
LPCSTR pErrorMsg =
"HLSL Version 2015 is only supported for language services";
CheckOperationResultMsgs(pResult, &pErrorMsg, 1, false, false);
}
TEST_F(CompilerTest, CompileHlsl2016ThenOK) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2016"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
}
TEST_F(CompilerTest, CompileHlsl2017ThenOK) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2017"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
}
TEST_F(CompilerTest, CompileHlsl2018ThenOK) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2018"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
}
TEST_F(CompilerTest, CompileHlsl2019ThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2019"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_ARE_EQUAL(status, E_INVALIDARG);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
LPCSTR pErrorMsg = "Unknown HLSL version";
CheckOperationResultMsgs(pResult, &pErrorMsg, 1, false, false);
}
TEST_F(CompilerTest, CompileHlsl2020ThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2020"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_ARE_EQUAL(status, E_INVALIDARG);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
LPCSTR pErrorMsg = "Unknown HLSL version";
CheckOperationResultMsgs(pResult, &pErrorMsg, 1, false, false);
}
TEST_F(CompilerTest, CompileHlsl2021ThenOK) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2021"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
}
TEST_F(CompilerTest, CompileHlsl2022ThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"float4 main(float4 pos : SV_Position) : SV_Target { return pos; }",
&pSource);
LPCWSTR args[2] = {L"-HV", L"2022"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, 2, nullptr, 0, nullptr,
&pResult));
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_ARE_EQUAL(status, E_INVALIDARG);
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
LPCSTR pErrorMsg = "Unknown HLSL version";
CheckOperationResultMsgs(pResult, &pErrorMsg, 1, false, false);
}
// this test has issues on ARM64 and clang_cl, disable until we figure out what
// it going on
#if defined(_WIN32) && \
!(defined(_M_ARM64) || defined(_M_ARM64EC) || defined(__clang__))
#pragma fenv_access(on)
#pragma optimize("", off)
#pragma warning(disable : 4723)
// Define test state as something weird that we can verify was restored
static const unsigned int fpTestState =
(_MCW_EM & (~_EM_ZERODIVIDE)) | // throw on div by zero
_DN_FLUSH_OPERANDS_SAVE_RESULTS | // denorm flush operands & save results
_RC_UP; // round up
static const unsigned int fpTestMask = _MCW_EM | _MCW_DN | _MCW_RC;
struct FPTestScope {
// _controlfp_s is non-standard and <cfenv> doesn't have a function to enable
// exceptions
unsigned int fpSavedState;
FPTestScope() {
VERIFY_IS_TRUE(_controlfp_s(&fpSavedState, 0, 0) == 0);
unsigned int newValue;
VERIFY_IS_TRUE(_controlfp_s(&newValue, fpTestState, fpTestMask) == 0);
}
~FPTestScope() {
unsigned int newValue;
errno_t error = _controlfp_s(&newValue, fpSavedState, fpTestMask);
DXASSERT_LOCALVAR(error, error == 0,
"Failed to restore floating-point environment.");
}
};
void VerifyDivByZeroThrows() {
bool bCaughtExpectedException = false;
__try {
float one = 1.0;
float zero = 0.0;
float val = one / zero;
(void)val;
} __except (EXCEPTION_EXECUTE_HANDLER) {
bCaughtExpectedException = true;
}
VERIFY_IS_TRUE(bCaughtExpectedException);
}
TEST_F(CompilerTest, CodeGenFloatingPointEnvironment) {
unsigned int fpOriginal;
VERIFY_IS_TRUE(_controlfp_s(&fpOriginal, 0, 0) == 0);
{
FPTestScope fpTestScope;
// Get state before/after compilation, making sure it's our test state,
// and that it is restored after the compile.
unsigned int fpBeforeCompile;
VERIFY_IS_TRUE(_controlfp_s(&fpBeforeCompile, 0, 0) == 0);
VERIFY_ARE_EQUAL((fpBeforeCompile & fpTestMask), fpTestState);
CodeGenTestCheck(L"fpexcept.hlsl");
// Verify excpetion environment was restored
unsigned int fpAfterCompile;
VERIFY_IS_TRUE(_controlfp_s(&fpAfterCompile, 0, 0) == 0);
VERIFY_ARE_EQUAL((fpBeforeCompile & fpTestMask),
(fpAfterCompile & fpTestMask));
// Make sure round up is set
VERIFY_ARE_EQUAL(rint(12.25), 13);
// Make sure we actually enabled div-by-zero exception
VerifyDivByZeroThrows();
}
// Verify original state has been restored
unsigned int fpLocal;
VERIFY_IS_TRUE(_controlfp_s(&fpLocal, 0, 0) == 0);
VERIFY_ARE_EQUAL(fpLocal, fpOriginal);
}
#pragma optimize("", on)
#else // defined(_WIN32) && !defined(_M_ARM64)
// Only implemented on Win32
TEST_F(CompilerTest, CodeGenFloatingPointEnvironment) { VERIFY_IS_TRUE(true); }
#endif // defined(_WIN32) && !defined(_M_ARM64)
TEST_F(CompilerTest, CodeGenLibCsEntry) {
CodeGenTestCheck(L"lib_cs_entry.hlsl");
}
TEST_F(CompilerTest, CodeGenLibCsEntry2) {
CodeGenTestCheck(L"lib_cs_entry2.hlsl");
}
TEST_F(CompilerTest, CodeGenLibCsEntry3) {
CodeGenTestCheck(L"lib_cs_entry3.hlsl");
}
TEST_F(CompilerTest, CodeGenLibEntries) {
CodeGenTestCheck(L"lib_entries.hlsl");
}
TEST_F(CompilerTest, CodeGenLibEntries2) {
CodeGenTestCheck(L"lib_entries2.hlsl");
}
TEST_F(CompilerTest, CodeGenLibResource) {
CodeGenTestCheck(L"lib_resource.hlsl");
}
TEST_F(CompilerTest, CodeGenLibUnusedFunc) {
CodeGenTestCheck(L"lib_unused_func.hlsl");
}
TEST_F(CompilerTest, CodeGenRootSigProfile) {
if (m_ver.SkipDxilVersion(1, 5))
return;
CodeGenTest(L"rootSigProfile.hlsl");
}
TEST_F(CompilerTest, CodeGenRootSigProfile2) {
if (m_ver.SkipDxilVersion(1, 5))
return;
// TODO: Verify the result when reflect the structures.
CodeGenTest(L"rootSigProfile2.hlsl");
}
TEST_F(CompilerTest, CodeGenRootSigProfile5) {
if (m_ver.SkipDxilVersion(1, 5))
return;
CodeGenTest(L"rootSigProfile5.hlsl");
}
TEST_F(CompilerTest, CodeGenVectorIsnan) {
CodeGenTestCheck(L"isnan_vector_argument.hlsl");
}
TEST_F(CompilerTest, CodeGenVectorAtan2) {
CodeGenTestCheck(L"atan2_vector_argument.hlsl");
}
TEST_F(CompilerTest, LibGVStore) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcContainerReflection> pReflection;
CComPtr<IDxcAssembler> pAssembler;
VERIFY_SUCCEEDED(this->m_dllSupport.CreateInstance(
CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(
this->m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
R"(
struct T {
RWByteAddressBuffer outputBuffer;
RWByteAddressBuffer outputBuffer2;
};
struct D {
float4 a;
int4 b;
};
struct T2 {
RWStructuredBuffer<D> uav;
};
T2 resStruct(T t, uint2 id);
RWByteAddressBuffer outputBuffer;
RWByteAddressBuffer outputBuffer2;
[shader("compute")]
[numthreads(8, 8, 1)]
void main( uint2 id : SV_DispatchThreadID )
{
T t = {outputBuffer,outputBuffer2};
T2 t2 = resStruct(t, id);
uint counter = t2.uav.IncrementCounter();
t2.uav[counter].b.xy = id;
}
)",
&pSource);
const WCHAR *pArgs[] = {
L"/Zi",
};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"file.hlsl", L"", L"lib_6_x",
pArgs, _countof(pArgs), nullptr, 0,
nullptr, &pResult));
CComPtr<IDxcBlob> pShader;
VERIFY_SUCCEEDED(pResult->GetResult(&pShader));
VERIFY_SUCCEEDED(pReflection->Load(pShader));
UINT32 index = 0;
VERIFY_SUCCEEDED(pReflection->FindFirstPartKind(hlsl::DFCC_DXIL, &index));
CComPtr<IDxcBlob> pBitcode;
VERIFY_SUCCEEDED(pReflection->GetPartContent(index, &pBitcode));
const char *bitcode = hlsl::GetDxilBitcodeData(
(hlsl::DxilProgramHeader *)pBitcode->GetBufferPointer());
unsigned bitcode_size = hlsl::GetDxilBitcodeSize(
(hlsl::DxilProgramHeader *)pBitcode->GetBufferPointer());
CComPtr<IDxcBlobEncoding> pBitcodeBlob;
CreateBlobPinned(bitcode, bitcode_size, DXC_CP_ACP, &pBitcodeBlob);
CComPtr<IDxcBlob> pReassembled;
CComPtr<IDxcOperationResult> pReassembleResult;
VERIFY_SUCCEEDED(
pAssembler->AssembleToContainer(pBitcodeBlob, &pReassembleResult));
VERIFY_SUCCEEDED(pReassembleResult->GetResult(&pReassembled));
CComPtr<IDxcBlobEncoding> pTextBlob;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pReassembled, &pTextBlob));
std::wstring Text = BlobToWide(pTextBlob);
VERIFY_ARE_NOT_EQUAL(std::wstring::npos, Text.find(L"store"));
}
TEST_F(CompilerTest, PreprocessWhenValidThenOK) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
DxcDefine defines[2];
defines[0].Name = L"MYDEF";
defines[0].Value = L"int";
defines[1].Name = L"MYOTHERDEF";
defines[1].Value = L"123";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("// First line\r\n"
"MYDEF g_int = MYOTHERDEF;\r\n"
"#define FOO BAR\r\n"
"int FOO;",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Preprocess(pSource, L"file.hlsl", nullptr, 0,
defines, _countof(defines), nullptr,
&pResult));
HRESULT hrOp;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrOp));
VERIFY_SUCCEEDED(hrOp);
CComPtr<IDxcBlob> pOutText;
VERIFY_SUCCEEDED(pResult->GetResult(&pOutText));
std::string text(BlobToUtf8(pOutText));
VERIFY_ARE_EQUAL_STR("#line 1 \"file.hlsl\"\n"
"\n"
"int g_int = 123;\n"
"\n"
"int BAR;\n",
text.c_str());
}
TEST_F(CompilerTest, PreprocessWhenExpandTokenPastingOperandThenAccept) {
// Tests that we can turn on fxc's behavior (pre-expanding operands before
// performing token-pasting) using -flegacy-macro-expansion
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
LPCWSTR expandOption = L"-flegacy-macro-expansion";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(R"(
#define SET_INDEX0 10
#define BINDING_INDEX0 5
#define SET(INDEX) SET_INDEX##INDEX
#define BINDING(INDEX) BINDING_INDEX##INDEX
#define SET_BIND(NAME,SET,BIND) resource_set_##SET##_bind_##BIND##_##NAME
#define RESOURCE(NAME,INDEX) SET_BIND(NAME, SET(INDEX), BINDING(INDEX))
Texture2D<float4> resource_set_10_bind_5_tex;
float4 main() : SV_Target{
return RESOURCE(tex, 0)[uint2(1, 2)];
}
)",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Preprocess(pSource, L"file.hlsl", &expandOption,
1, nullptr, 0, nullptr, &pResult));
HRESULT hrOp;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrOp));
VERIFY_SUCCEEDED(hrOp);
CComPtr<IDxcBlob> pOutText;
VERIFY_SUCCEEDED(pResult->GetResult(&pOutText));
std::string text(BlobToUtf8(pOutText));
VERIFY_ARE_EQUAL_STR("#line 1 \"file.hlsl\"\n"
"#line 12 \"file.hlsl\"\n"
" Texture2D<float4> resource_set_10_bind_5_tex;\n"
"\n"
" float4 main() : SV_Target{\n"
" return resource_set_10_bind_5_tex[uint2(1, 2)];\n"
" }\n",
text.c_str());
}
TEST_F(CompilerTest, PreprocessWithDebugOptsThenOk) {
// Make sure debug options, such as -Zi and -Fd,
// are simply ignored when preprocessing
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
DxcDefine defines[2];
defines[0].Name = L"MYDEF";
defines[0].Value = L"int";
defines[1].Name = L"MYOTHERDEF";
defines[1].Value = L"123";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("// First line\r\n"
"MYDEF g_int = MYOTHERDEF;\r\n"
"#define FOO BAR\r\n"
"int FOO;",
&pSource);
LPCWSTR extraOptions[] = {L"-Zi", L"-Fd", L"file.pdb", L"-Qembed_debug"};
VERIFY_SUCCEEDED(pCompiler->Preprocess(pSource, L"file.hlsl", extraOptions,
_countof(extraOptions), defines,
_countof(defines), nullptr, &pResult));
HRESULT hrOp;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrOp));
VERIFY_SUCCEEDED(hrOp);
CComPtr<IDxcBlob> pOutText;
VERIFY_SUCCEEDED(pResult->GetResult(&pOutText));
std::string text(BlobToUtf8(pOutText));
VERIFY_ARE_EQUAL_STR("#line 1 \"file.hlsl\"\n"
"\n"
"int g_int = 123;\n"
"\n"
"int BAR;\n",
text.c_str());
}
// Make sure that '#line 1 "<built-in>"' won't blow up when preprocessing.
TEST_F(CompilerTest, PreprocessCheckBuiltinIsOk) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#line 1 \"<built-in>\"\r\n"
"int x;",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Preprocess(pSource, L"file.hlsl", nullptr, 0,
nullptr, 0, nullptr, &pResult));
HRESULT hrOp;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrOp));
VERIFY_SUCCEEDED(hrOp);
CComPtr<IDxcBlob> pOutText;
VERIFY_SUCCEEDED(pResult->GetResult(&pOutText));
std::string text(BlobToUtf8(pOutText));
VERIFY_ARE_EQUAL_STR("#line 1 \"file.hlsl\"\n\n", text.c_str());
}
TEST_F(CompilerTest, CompileOtherModesWithDebugOptsThenOk) {
// Make sure debug options, such as -Zi and -Fd,
// are simply ignored when compiling in modes:
// /Odump -ast-dump -fcgl -rootsig_1_0
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("#define RS \"CBV(b0)\"\n"
"[RootSignature(RS)]\n"
"float main(float i : IN) : OUT { return i * 2.0F; }",
&pSource);
auto testWithOpts = [&](LPCWSTR entry, LPCWSTR target,
llvm::ArrayRef<LPCWSTR> mainOpts) -> HRESULT {
std::vector<LPCWSTR> opts(mainOpts);
opts.insert(opts.end(), {L"-Zi", L"-Fd", L"file.pdb"});
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"file.hlsl", entry, target,
opts.data(), opts.size(), nullptr, 0,
nullptr, &pResult));
HRESULT hrOp;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrOp));
return hrOp;
};
VERIFY_SUCCEEDED(testWithOpts(L"main", L"vs_6_0", {L"/Odump"}));
VERIFY_SUCCEEDED(testWithOpts(L"main", L"vs_6_0", {L"-ast-dump"}));
VERIFY_SUCCEEDED(testWithOpts(L"main", L"vs_6_0", {L"-fcgl"}));
VERIFY_SUCCEEDED(testWithOpts(L"RS", L"rootsig_1_0", {}));
}
TEST_F(CompilerTest, WhenSigMismatchPCFunctionThenFail) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(
"struct PSSceneIn \n\
{ \n\
float4 pos : SV_Position; \n\
float2 tex : TEXCOORD0; \n\
float3 norm : NORMAL; \n\
}; \n"
"struct HSPerPatchData { \n\
float edges[ 3 ] : SV_TessFactor; \n\
float inside : SV_InsideTessFactor; \n\
float foo : FOO; \n\
}; \n"
"HSPerPatchData HSPerPatchFunc( InputPatch< PSSceneIn, 3 > points, \n\
OutputPatch<PSSceneIn, 3> outpoints) { \n\
HSPerPatchData d = (HSPerPatchData)0; \n\
d.edges[ 0 ] = points[0].tex.x + outpoints[0].tex.x; \n\
d.edges[ 1 ] = 1; \n\
d.edges[ 2 ] = 1; \n\
d.inside = 1; \n\
return d; \n\
} \n"
"[domain(\"tri\")] \n\
[partitioning(\"fractional_odd\")] \n\
[outputtopology(\"triangle_cw\")] \n\
[patchconstantfunc(\"HSPerPatchFunc\")] \n\
[outputcontrolpoints(3)] \n"
"void main(const uint id : SV_OutputControlPointID, \n\
const InputPatch< PSSceneIn, 3 > points ) { \n\
} \n",
&pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"hs_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
std::string failLog(VerifyOperationFailed(pResult));
VERIFY_ARE_NOT_EQUAL(
string::npos,
failLog.find(
"Signature element SV_Position, referred to by patch constant "
"function, is not found in corresponding hull shader output."));
}
TEST_F(CompilerTest, SubobjectCodeGenErrors) {
struct SubobjectErrorTestCase {
const char *shaderText;
const char *expectedError;
};
SubobjectErrorTestCase testCases[] = {
{"GlobalRootSignature grs;",
"1:1: error: subobject needs to be initialized"},
{"StateObjectConfig soc;",
"1:1: error: subobject needs to be initialized"},
{"LocalRootSignature lrs;",
"1:1: error: subobject needs to be initialized"},
{"SubobjectToExportsAssociation sea;",
"1:1: error: subobject needs to be initialized"},
{"RaytracingShaderConfig rsc;",
"1:1: error: subobject needs to be initialized"},
{"RaytracingPipelineConfig rpc;",
"1:1: error: subobject needs to be initialized"},
{"RaytracingPipelineConfig1 rpc1;",
"1:1: error: subobject needs to be initialized"},
{"TriangleHitGroup hitGt;",
"1:1: error: subobject needs to be initialized"},
{"ProceduralPrimitiveHitGroup hitGt;",
"1:1: error: subobject needs to be initialized"},
{"GlobalRootSignature grs2 = {\"\"};",
"1:29: error: empty string not expected here"},
{"LocalRootSignature lrs2 = {\"\"};",
"1:28: error: empty string not expected here"},
{"SubobjectToExportsAssociation sea2 = { \"\", \"x\" };",
"1:40: error: empty string not expected here"},
{"string s; SubobjectToExportsAssociation sea4 = { \"x\", s };",
"1:55: error: cannot convert to constant string"},
{"extern int v; RaytracingPipelineConfig rpc2 = { v + 16 };",
"1:49: error: cannot convert to constant unsigned int"},
{"string s; TriangleHitGroup trHitGt2_8 = { s, \"foo\" };",
"1:43: error: cannot convert to constant string"},
{"string s; ProceduralPrimitiveHitGroup ppHitGt2_8 = { s, \"\", s };",
"1:54: error: cannot convert to constant string"},
{"ProceduralPrimitiveHitGroup ppHitGt2_9 = { \"a\", \"b\", \"\"};",
"1:54: error: empty string not expected here"}};
for (unsigned i = 0; i < _countof(testCases); i++) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(testCases[i].shaderText, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"",
L"lib_6_4", nullptr, 0, nullptr, 0,
nullptr, &pResult));
std::string failLog(VerifyOperationFailed(pResult));
VERIFY_ARE_NOT_EQUAL(string::npos,
failLog.find(testCases[i].expectedError));
}
}
#ifdef _WIN32
TEST_F(CompilerTest, ManualFileCheckTest) {
#else
TEST_F(CompilerTest, DISABLED_ManualFileCheckTest) {
#endif
using namespace llvm;
using namespace WEX::TestExecution;
WEX::Common::String value;
VERIFY_SUCCEEDED(RuntimeParameters::TryGetValue(L"InputPath", value));
std::wstring path = static_cast<const wchar_t *>(value);
if (!llvm::sys::path::is_absolute(CW2A(path.c_str()).m_psz)) {
path = hlsl_test::GetPathToHlslDataFile(path.c_str());
}
bool isDirectory;
{
// Temporarily setup the filesystem for testing whether the path is a
// directory. If it is, CodeGenTestCheckBatchDir will create its own
// instance.
llvm::sys::fs::MSFileSystem *msfPtr;
VERIFY_SUCCEEDED(CreateMSFileSystemForDisk(&msfPtr));
std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr);
llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
IFTLLVM(pts.error_code());
isDirectory = llvm::sys::fs::is_directory(CW2A(path.c_str()).m_psz);
}
if (isDirectory) {
CodeGenTestCheckBatchDir(path, /*implicitDir*/ false);
} else {
CodeGenTestCheck(path.c_str(), /*implicitDir*/ false);
}
}
TEST_F(CompilerTest, CodeGenHashStabilityD3DReflect) {
CodeGenTestCheckBatchHash(L"d3dreflect");
}
TEST_F(CompilerTest, CodeGenHashStabilityDisassembler) {
CodeGenTestCheckBatchHash(L"disassembler");
}
TEST_F(CompilerTest, CodeGenHashStabilityDXIL) {
CodeGenTestCheckBatchHash(L"dxil");
}
TEST_F(CompilerTest, CodeGenHashStabilityHLSL) {
CodeGenTestCheckBatchHash(L"hlsl");
}
TEST_F(CompilerTest, CodeGenHashStabilityInfra) {
CodeGenTestCheckBatchHash(L"infra");
}
TEST_F(CompilerTest, CodeGenHashStabilityPIX) {
CodeGenTestCheckBatchHash(L"pix");
}
TEST_F(CompilerTest, CodeGenHashStabilityRewriter) {
CodeGenTestCheckBatchHash(L"rewriter");
}
TEST_F(CompilerTest, CodeGenHashStabilitySamples) {
CodeGenTestCheckBatchHash(L"samples");
}
TEST_F(CompilerTest, CodeGenHashStabilityShaderTargets) {
CodeGenTestCheckBatchHash(L"shader_targets");
}
TEST_F(CompilerTest, CodeGenHashStabilityValidation) {
CodeGenTestCheckBatchHash(L"validation");
}
TEST_F(CompilerTest, BatchD3DReflect) {
CodeGenTestCheckBatchDir(L"d3dreflect");
}
TEST_F(CompilerTest, BatchDxil) { CodeGenTestCheckBatchDir(L"dxil"); }
TEST_F(CompilerTest, BatchHLSL) { CodeGenTestCheckBatchDir(L"hlsl"); }
TEST_F(CompilerTest, BatchInfra) { CodeGenTestCheckBatchDir(L"infra"); }
TEST_F(CompilerTest, BatchPasses) { CodeGenTestCheckBatchDir(L"passes"); }
TEST_F(CompilerTest, BatchShaderTargets) {
CodeGenTestCheckBatchDir(L"shader_targets");
}
TEST_F(CompilerTest, BatchValidation) {
CodeGenTestCheckBatchDir(L"validation");
}
TEST_F(CompilerTest, BatchPIX) { CodeGenTestCheckBatchDir(L"pix"); }
TEST_F(CompilerTest, BatchSamples) { CodeGenTestCheckBatchDir(L"samples"); }
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/DxilContainerTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// DxilContainerTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for container formatting and validation. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef UNICODE
#define UNICODE
#endif
#ifdef __APPLE__
// Workaround for ambiguous wcsstr on Mac
#define _WCHAR_H_CPLUSPLUS_98_CONFORMANCE_
#endif
// clang-format off
// Includes on Windows are highly order dependent.
#include <memory>
#include <vector>
#include <string>
#include <tuple>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <unordered_set>
#include "dxc/Support/WinIncludes.h"
#include "dxc/Support/D3DReflection.h"
#include "dxc/dxcapi.h"
#ifdef _WIN32
#include <atlfile.h>
#include <d3dcompiler.h>
#pragma comment(lib, "d3dcompiler.lib")
#if _MSC_VER >= 1920
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include <experimental/filesystem>
#else
#include <filesystem>
#endif
#endif
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include "dxc/Test/HLSLTestData.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/Support/HLSLOptions.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/DxilContainer/DxilRuntimeReflection.h"
#include <assert.h> // Needed for DxilPipelineStateValidation.h
#include "dxc/DxilContainer/DxilPipelineStateValidation.h"
#include "dxc/DXIL/DxilShaderFlags.h"
#include "dxc/DXIL/DxilUtil.h"
#include <fstream>
#include <chrono>
#include <codecvt>
// clang-format on
using namespace std;
using namespace hlsl_test;
#ifdef _WIN32
using namespace std::experimental::filesystem;
static uint8_t MaskCount(uint8_t V) {
DXASSERT_NOMSG(0 <= V && V <= 0xF);
static const uint8_t Count[16] = {0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4};
return Count[V];
}
#endif
#ifdef _WIN32
class DxilContainerTest {
#else
class DxilContainerTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(DxilContainerTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
TEST_METHOD(CompileWhenDebugSourceThenSourceMatters)
TEST_METHOD(CompileAS_CheckPSV0)
TEST_METHOD(CompileGS_CheckPSV0_ViewID)
TEST_METHOD(Compile_CheckPSV0_EntryFunctionName)
TEST_METHOD(CompileCSWaveSize_CheckPSV0)
TEST_METHOD(CompileCSWaveSizeRange_CheckPSV0)
TEST_METHOD(CompileWhenOkThenCheckRDAT)
TEST_METHOD(CompileWhenOkThenCheckRDAT2)
TEST_METHOD(CompileWhenOkThenCheckReflection1)
TEST_METHOD(DxcUtils_CreateReflection)
TEST_METHOD(CheckReflectionQueryInterface)
TEST_METHOD(CompileWhenOKThenIncludesFeatureInfo)
TEST_METHOD(CompileWhenOKThenIncludesSignatures)
TEST_METHOD(CompileWhenSigSquareThenIncludeSplit)
TEST_METHOD(DisassemblyWhenMissingThenFails)
TEST_METHOD(DisassemblyWhenBCInvalidThenFails)
TEST_METHOD(DisassemblyWhenInvalidThenFails)
TEST_METHOD(DisassemblyWhenValidThenOK)
TEST_METHOD(ValidateFromLL_Abs2)
TEST_METHOD(DxilContainerUnitTest)
TEST_METHOD(DxilContainerCompilerVersionTest)
TEST_METHOD(ContainerBuilder_AddPrivateForceLast)
TEST_METHOD(ReflectionMatchesDXBC_CheckIn)
BEGIN_TEST_METHOD(ReflectionMatchesDXBC_Full)
TEST_METHOD_PROPERTY(L"Priority", L"1")
END_TEST_METHOD()
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
void CreateBlobPinned(LPCVOID data, SIZE_T size, UINT32 codePage,
IDxcBlobEncoding **ppBlob) {
CComPtr<IDxcLibrary> library;
IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
IFT(library->CreateBlobWithEncodingFromPinned(data, size, codePage,
ppBlob));
}
void CreateBlobFromText(const char *pText, IDxcBlobEncoding **ppBlob) {
CreateBlobPinned(pText, strlen(pText), CP_UTF8, ppBlob);
}
HRESULT CreateCompiler(IDxcCompiler **ppResult) {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
}
return m_dllSupport.CreateInstance(CLSID_DxcCompiler, ppResult);
}
#ifdef _WIN32 // DXBC Unsupported
void CompareShaderInputBindDesc(D3D12_SHADER_INPUT_BIND_DESC *pTestDesc,
D3D12_SHADER_INPUT_BIND_DESC *pBaseDesc) {
VERIFY_ARE_EQUAL(pTestDesc->BindCount, pBaseDesc->BindCount);
VERIFY_ARE_EQUAL(pTestDesc->BindPoint, pBaseDesc->BindPoint);
VERIFY_ARE_EQUAL(pTestDesc->Dimension, pBaseDesc->Dimension);
VERIFY_ARE_EQUAL_STR(pTestDesc->Name, pBaseDesc->Name);
VERIFY_ARE_EQUAL(pTestDesc->NumSamples, pBaseDesc->NumSamples);
VERIFY_ARE_EQUAL(pTestDesc->ReturnType, pBaseDesc->ReturnType);
VERIFY_ARE_EQUAL(pTestDesc->Space, pBaseDesc->Space);
if (pBaseDesc->Type == D3D_SIT_UAV_APPEND_STRUCTURED ||
pBaseDesc->Type == D3D_SIT_UAV_CONSUME_STRUCTURED) {
// dxil only have rw with counter.
VERIFY_ARE_EQUAL(pTestDesc->Type, D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER);
} else if (pTestDesc->Type == D3D_SIT_STRUCTURED &&
pBaseDesc->Type != D3D_SIT_STRUCTURED) {
VERIFY_ARE_EQUAL(pBaseDesc->Type, D3D_SIT_TEXTURE);
} else
VERIFY_ARE_EQUAL(pTestDesc->Type, pBaseDesc->Type);
// D3D_SIF_USERPACKED is not set consistently in fxc (new-style
// ConstantBuffer).
UINT unusedFlag = D3D_SIF_USERPACKED;
VERIFY_ARE_EQUAL(pTestDesc->uFlags & ~unusedFlag,
pBaseDesc->uFlags & ~unusedFlag);
// VERIFY_ARE_EQUAL(pTestDesc->uID, pBaseDesc->uID); // Like register, this
// can vary.
}
void CompareParameterDesc(D3D12_SIGNATURE_PARAMETER_DESC *pTestDesc,
D3D12_SIGNATURE_PARAMETER_DESC *pBaseDesc,
bool isInput) {
VERIFY_ARE_EQUAL(
0, _stricmp(pTestDesc->SemanticName, pBaseDesc->SemanticName));
if (pTestDesc->SystemValueType == D3D_NAME_CLIP_DISTANCE)
return; // currently generating multiple clip distance params, one per
// component
VERIFY_ARE_EQUAL(pTestDesc->ComponentType, pBaseDesc->ComponentType);
VERIFY_ARE_EQUAL(MaskCount(pTestDesc->Mask), MaskCount(pBaseDesc->Mask));
VERIFY_ARE_EQUAL(pTestDesc->MinPrecision, pBaseDesc->MinPrecision);
if (!isInput) {
if (hlsl::DXIL::CompareVersions(m_ver.m_ValMajor, m_ver.m_ValMinor, 1,
5) < 0)
VERIFY_ARE_EQUAL(pTestDesc->ReadWriteMask != 0,
pBaseDesc->ReadWriteMask != 0);
else
VERIFY_ARE_EQUAL(MaskCount(pTestDesc->ReadWriteMask),
MaskCount(pBaseDesc->ReadWriteMask));
}
// VERIFY_ARE_EQUAL(pTestDesc->Register, pBaseDesc->Register);
// VERIFY_ARE_EQUAL(pTestDesc->SemanticIndex, pBaseDesc->SemanticIndex);
VERIFY_ARE_EQUAL(pTestDesc->Stream, pBaseDesc->Stream);
VERIFY_ARE_EQUAL(pTestDesc->SystemValueType, pBaseDesc->SystemValueType);
}
void CompareType(ID3D12ShaderReflectionType *pTest,
ID3D12ShaderReflectionType *pBase) {
D3D12_SHADER_TYPE_DESC testDesc, baseDesc;
VERIFY_SUCCEEDED(pTest->GetDesc(&testDesc));
VERIFY_SUCCEEDED(pBase->GetDesc(&baseDesc));
VERIFY_ARE_EQUAL(testDesc.Class, baseDesc.Class);
VERIFY_ARE_EQUAL(testDesc.Type, baseDesc.Type);
VERIFY_ARE_EQUAL(testDesc.Rows, baseDesc.Rows);
VERIFY_ARE_EQUAL(testDesc.Columns, baseDesc.Columns);
VERIFY_ARE_EQUAL(testDesc.Elements, baseDesc.Elements);
VERIFY_ARE_EQUAL(testDesc.Members, baseDesc.Members);
VERIFY_ARE_EQUAL(testDesc.Offset, baseDesc.Offset);
// DXIL Reflection doesn't expose half type name,
// and that shouldn't matter because this is only
// in the case where half maps to float.
std::string baseName(baseDesc.Name);
if (baseName.compare(0, 4, "half", 4) == 0)
baseName = baseName.replace(0, 4, "float", 5);
// For anonymous structures, fxc uses "scope::<unnamed>",
// dxc uses "anon", and may have additional ".#" for name disambiguation.
// Just skip name check if struct is unnamed according to fxc.
if (baseName.find("<unnamed>") == std::string::npos) {
VERIFY_ARE_EQUAL_STR(testDesc.Name, baseName.c_str());
}
for (UINT i = 0; i < baseDesc.Members; ++i) {
ID3D12ShaderReflectionType *testMemberType =
pTest->GetMemberTypeByIndex(i);
ID3D12ShaderReflectionType *baseMemberType =
pBase->GetMemberTypeByIndex(i);
VERIFY_IS_NOT_NULL(testMemberType);
VERIFY_IS_NOT_NULL(baseMemberType);
CompareType(testMemberType, baseMemberType);
LPCSTR testMemberName = pTest->GetMemberTypeName(i);
LPCSTR baseMemberName = pBase->GetMemberTypeName(i);
VERIFY_ARE_EQUAL(0, strcmp(testMemberName, baseMemberName));
}
}
typedef HRESULT (__stdcall ID3D12ShaderReflection::*GetParameterDescFn)(
UINT, D3D12_SIGNATURE_PARAMETER_DESC *);
void SortNameIdxVector(std::vector<std::tuple<LPCSTR, UINT, UINT>> &value) {
struct FirstPredT {
bool operator()(std::tuple<LPCSTR, UINT, UINT> &l,
std::tuple<LPCSTR, UINT, UINT> &r) {
int strResult = strcmp(std::get<0>(l), std::get<0>(r));
return (strResult < 0) ||
(strResult == 0 && std::get<1>(l) < std::get<1>(r));
}
} FirstPred;
std::sort(value.begin(), value.end(), FirstPred);
}
void CompareParameterDescs(UINT count, ID3D12ShaderReflection *pTest,
ID3D12ShaderReflection *pBase,
GetParameterDescFn Fn, bool isInput) {
std::vector<std::tuple<LPCSTR, UINT, UINT>> testParams, baseParams;
testParams.reserve(count);
baseParams.reserve(count);
for (UINT i = 0; i < count; ++i) {
D3D12_SIGNATURE_PARAMETER_DESC D;
VERIFY_SUCCEEDED((pTest->*Fn)(i, &D));
testParams.push_back(std::make_tuple(D.SemanticName, D.SemanticIndex, i));
VERIFY_SUCCEEDED((pBase->*Fn)(i, &D));
baseParams.push_back(std::make_tuple(D.SemanticName, D.SemanticIndex, i));
}
SortNameIdxVector(testParams);
SortNameIdxVector(baseParams);
for (UINT i = 0; i < count; ++i) {
D3D12_SIGNATURE_PARAMETER_DESC testParamDesc, baseParamDesc;
VERIFY_SUCCEEDED(
(pTest->*Fn)(std::get<2>(testParams[i]), &testParamDesc));
VERIFY_SUCCEEDED(
(pBase->*Fn)(std::get<2>(baseParams[i]), &baseParamDesc));
CompareParameterDesc(&testParamDesc, &baseParamDesc, isInput);
}
}
void CompareReflection(ID3D12ShaderReflection *pTest,
ID3D12ShaderReflection *pBase) {
D3D12_SHADER_DESC testDesc, baseDesc;
VERIFY_SUCCEEDED(pTest->GetDesc(&testDesc));
VERIFY_SUCCEEDED(pBase->GetDesc(&baseDesc));
VERIFY_ARE_EQUAL(D3D12_SHVER_GET_TYPE(testDesc.Version),
D3D12_SHVER_GET_TYPE(baseDesc.Version));
VERIFY_ARE_EQUAL(testDesc.ConstantBuffers, baseDesc.ConstantBuffers);
VERIFY_ARE_EQUAL(testDesc.BoundResources, baseDesc.BoundResources);
VERIFY_ARE_EQUAL(testDesc.InputParameters, baseDesc.InputParameters);
VERIFY_ARE_EQUAL(testDesc.OutputParameters, baseDesc.OutputParameters);
VERIFY_ARE_EQUAL(testDesc.PatchConstantParameters,
baseDesc.PatchConstantParameters);
{
for (UINT i = 0; i < testDesc.ConstantBuffers; ++i) {
ID3D12ShaderReflectionConstantBuffer *pTestCB, *pBaseCB;
D3D12_SHADER_BUFFER_DESC testCB, baseCB;
pTestCB = pTest->GetConstantBufferByIndex(i);
VERIFY_SUCCEEDED(pTestCB->GetDesc(&testCB));
pBaseCB = pBase->GetConstantBufferByName(testCB.Name);
VERIFY_SUCCEEDED(pBaseCB->GetDesc(&baseCB));
VERIFY_ARE_EQUAL_STR(testCB.Name, baseCB.Name);
VERIFY_ARE_EQUAL(testCB.Type, baseCB.Type);
VERIFY_ARE_EQUAL(testCB.Variables, baseCB.Variables);
VERIFY_ARE_EQUAL(testCB.Size, baseCB.Size);
VERIFY_ARE_EQUAL(testCB.uFlags, baseCB.uFlags);
llvm::StringMap<D3D12_SHADER_VARIABLE_DESC> variableMap;
llvm::StringMap<ID3D12ShaderReflectionType *> variableTypeMap;
for (UINT vi = 0; vi < testCB.Variables; ++vi) {
ID3D12ShaderReflectionVariable *pBaseConst;
D3D12_SHADER_VARIABLE_DESC baseConst;
pBaseConst = pBaseCB->GetVariableByIndex(vi);
VERIFY_SUCCEEDED(pBaseConst->GetDesc(&baseConst));
variableMap[baseConst.Name] = baseConst;
ID3D12ShaderReflectionType *pBaseType = pBaseConst->GetType();
VERIFY_IS_NOT_NULL(pBaseType);
variableTypeMap[baseConst.Name] = pBaseType;
}
for (UINT vi = 0; vi < testCB.Variables; ++vi) {
ID3D12ShaderReflectionVariable *pTestConst;
D3D12_SHADER_VARIABLE_DESC testConst;
pTestConst = pTestCB->GetVariableByIndex(vi);
VERIFY_SUCCEEDED(pTestConst->GetDesc(&testConst));
VERIFY_ARE_EQUAL(variableMap.count(testConst.Name), 1u);
D3D12_SHADER_VARIABLE_DESC baseConst = variableMap[testConst.Name];
VERIFY_ARE_EQUAL(testConst.uFlags, baseConst.uFlags);
VERIFY_ARE_EQUAL(testConst.StartOffset, baseConst.StartOffset);
VERIFY_ARE_EQUAL(testConst.Size, baseConst.Size);
ID3D12ShaderReflectionType *pTestType = pTestConst->GetType();
VERIFY_IS_NOT_NULL(pTestType);
VERIFY_ARE_EQUAL(variableTypeMap.count(testConst.Name), 1u);
ID3D12ShaderReflectionType *pBaseType =
variableTypeMap[testConst.Name];
CompareType(pTestType, pBaseType);
}
}
}
for (UINT i = 0; i < testDesc.BoundResources; ++i) {
D3D12_SHADER_INPUT_BIND_DESC testParamDesc, baseParamDesc;
VERIFY_SUCCEEDED(pTest->GetResourceBindingDesc(i, &testParamDesc),
WStrFmt(L"i=%u", i));
VERIFY_SUCCEEDED(pBase->GetResourceBindingDescByName(testParamDesc.Name,
&baseParamDesc));
CompareShaderInputBindDesc(&testParamDesc, &baseParamDesc);
}
CompareParameterDescs(testDesc.InputParameters, pTest, pBase,
&ID3D12ShaderReflection::GetInputParameterDesc, true);
CompareParameterDescs(testDesc.OutputParameters, pTest, pBase,
&ID3D12ShaderReflection::GetOutputParameterDesc,
false);
bool isHs =
testDesc.HSPartitioning !=
D3D_TESSELLATOR_PARTITIONING::D3D11_TESSELLATOR_PARTITIONING_UNDEFINED;
CompareParameterDescs(
testDesc.PatchConstantParameters, pTest, pBase,
&ID3D12ShaderReflection::GetPatchConstantParameterDesc, !isHs);
{
UINT32 testTotal, testX, testY, testZ;
UINT32 baseTotal, baseX, baseY, baseZ;
testTotal = pTest->GetThreadGroupSize(&testX, &testY, &testZ);
baseTotal = pBase->GetThreadGroupSize(&baseX, &baseY, &baseZ);
VERIFY_ARE_EQUAL(testTotal, baseTotal);
VERIFY_ARE_EQUAL(testX, baseX);
VERIFY_ARE_EQUAL(testY, baseY);
VERIFY_ARE_EQUAL(testZ, baseZ);
}
}
HRESULT CompileFromFile(LPCWSTR path, bool useDXBC, UINT fxcFlags,
IDxcBlob **ppBlob) {
std::vector<FileRunCommandPart> parts;
ParseCommandPartsFromFile(path, parts);
VERIFY_IS_TRUE(parts.size() > 0);
unsigned partIdx = 0;
if (parts[0].Command.compare("%dxilver") == 0) {
partIdx = 1;
}
FileRunCommandPart &dxc = parts[partIdx];
VERIFY_ARE_EQUAL_STR(dxc.Command.c_str(), "%dxc");
m_dllSupport.Initialize();
hlsl::options::MainArgs args;
hlsl::options::DxcOpts opts;
dxc.ReadOptsForDxc(args, opts);
if (opts.CodeGenHighLevel)
return E_FAIL; // skip for now
if (useDXBC) {
// Consider supporting defines and flags if/when needed.
std::string TargetProfile(opts.TargetProfile.str());
TargetProfile[3] = '5';
// Some shaders may need flags, and /Gec is incompatible with SM 5.1
TargetProfile[5] =
(fxcFlags & D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY) ? '0' : '1';
CComPtr<ID3DBlob> pDxbcBlob;
CComPtr<ID3DBlob> pDxbcErrors;
HRESULT hr = D3DCompileFromFile(
path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
opts.EntryPoint.str().c_str(), TargetProfile.c_str(), fxcFlags, 0,
&pDxbcBlob, &pDxbcErrors);
LPCSTR errors =
pDxbcErrors ? (const char *)pDxbcErrors->GetBufferPointer() : "";
(void)errors;
IFR(hr);
IFR(pDxbcBlob.QueryInterface(ppBlob));
} else {
FileRunCommandResult result = dxc.Run(m_dllSupport, nullptr);
IFRBOOL(result.ExitCode == 0, E_FAIL);
IFR(result.OpResult->GetResult(ppBlob));
}
return S_OK;
}
void CreateReflectionFromBlob(IDxcBlob *pBlob,
ID3D12ShaderReflection **ppReflection) {
CComPtr<IDxcContainerReflection> pReflection;
UINT32 shaderIdx;
m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection);
VERIFY_SUCCEEDED(pReflection->Load(pBlob));
VERIFY_SUCCEEDED(
pReflection->FindFirstPartKind(hlsl::DFCC_DXIL, &shaderIdx));
VERIFY_SUCCEEDED(pReflection->GetPartReflection(
shaderIdx, __uuidof(ID3D12ShaderReflection), (void **)ppReflection));
}
void CreateReflectionFromDXBC(IDxcBlob *pBlob,
ID3D12ShaderReflection **ppReflection) {
VERIFY_SUCCEEDED(
D3DReflect(pBlob->GetBufferPointer(), pBlob->GetBufferSize(),
__uuidof(ID3D12ShaderReflection), (void **)ppReflection));
}
#endif // _WIN32 - DXBC Unsupported
void CheckResult(LPCWSTR operation, IDxcOperationResult *pResult) {
HRESULT hrStatus = S_OK;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrStatus));
if (FAILED(hrStatus)) {
CComPtr<IDxcBlobEncoding> pErrorBuffer;
if (SUCCEEDED(pResult->GetErrorBuffer(&pErrorBuffer)) &&
pErrorBuffer->GetBufferSize()) {
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcBlobWide> pErrorBufferW;
VERIFY_SUCCEEDED(pUtils->GetBlobAsWide(pErrorBuffer, &pErrorBufferW));
LogErrorFmt(L"%s failed with hr %d. Error Buffer:\n%s", operation,
hrStatus, pErrorBufferW->GetStringPointer());
} else {
LogErrorFmt(L"%s failed with hr %d.", operation, hrStatus);
}
}
VERIFY_SUCCEEDED(hrStatus);
}
void CompileToProgram(LPCSTR program, LPCWSTR entryPoint, LPCWSTR target,
LPCWSTR *pArguments, UINT32 argCount,
IDxcBlob **ppProgram,
IDxcOperationResult **ppResult = nullptr) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(program, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", entryPoint,
target, pArguments, argCount, nullptr,
0, nullptr, &pResult));
CheckResult(L"compilation", pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
*ppProgram = pProgram.Detach();
if (ppResult)
*ppResult = pResult.Detach();
}
void AssembleToProgram(LPCSTR program, IDxcBlob **ppProgram) {
// Assemble program
CComPtr<IDxcAssembler> pAssembler;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
CComPtr<IDxcBlobEncoding> pSource;
CreateBlobFromText(program, &pSource);
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pAssembler->AssembleToContainer(pSource, &pResult));
CheckResult(L"assembly", pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
pResult.Release(); // Release pResult for re-use
CComPtr<IDxcValidator> pValidator;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcValidator, &pValidator));
VERIFY_SUCCEEDED(pValidator->Validate(
pProgram, DxcValidatorFlags_InPlaceEdit, &pResult));
CheckResult(L"assembly validation", pResult);
*ppProgram = pProgram.Detach();
}
bool DoesValidatorSupportDebugName() {
CComPtr<IDxcVersionInfo> pVersionInfo;
UINT Major, Minor;
HRESULT hrVer =
m_dllSupport.CreateInstance(CLSID_DxcValidator, &pVersionInfo);
if (hrVer == E_NOINTERFACE)
return false;
VERIFY_SUCCEEDED(hrVer);
VERIFY_SUCCEEDED(pVersionInfo->GetVersion(&Major, &Minor));
return !(Major == 1 && Minor < 1);
}
bool DoesValidatorSupportShaderHash() {
CComPtr<IDxcVersionInfo> pVersionInfo;
UINT Major, Minor;
HRESULT hrVer =
m_dllSupport.CreateInstance(CLSID_DxcValidator, &pVersionInfo);
if (hrVer == E_NOINTERFACE)
return false;
VERIFY_SUCCEEDED(hrVer);
VERIFY_SUCCEEDED(pVersionInfo->GetVersion(&Major, &Minor));
return !(Major == 1 && Minor < 5);
}
std::string CompileToDebugName(LPCSTR program, LPCWSTR entryPoint,
LPCWSTR target, LPCWSTR *pArguments,
UINT32 argCount) {
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlob> pNameBlob;
CComPtr<IDxcContainerReflection> pContainer;
UINT32 index;
CompileToProgram(program, entryPoint, target, pArguments, argCount,
&pProgram);
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pContainer));
VERIFY_SUCCEEDED(pContainer->Load(pProgram));
if (FAILED(pContainer->FindFirstPartKind(hlsl::DFCC_ShaderDebugName,
&index))) {
return std::string();
}
VERIFY_SUCCEEDED(pContainer->GetPartContent(index, &pNameBlob));
const hlsl::DxilShaderDebugName *pDebugName =
(hlsl::DxilShaderDebugName *)pNameBlob->GetBufferPointer();
return std::string((const char *)(pDebugName + 1));
}
std::string RetrieveHashFromBlob(IDxcBlob *pHashBlob) {
VERIFY_ARE_NOT_EQUAL(pHashBlob, nullptr);
VERIFY_ARE_EQUAL(pHashBlob->GetBufferSize(), sizeof(DxcShaderHash));
const hlsl::DxilShaderHash *pShaderHash =
(hlsl::DxilShaderHash *)pHashBlob->GetBufferPointer();
std::string result;
llvm::raw_string_ostream os(result);
for (int i = 0; i < 16; ++i)
os << llvm::format("%.2x", pShaderHash->Digest[i]);
return os.str();
}
std::string CompileToShaderHash(LPCSTR program, LPCWSTR entryPoint,
LPCWSTR target, LPCWSTR *pArguments,
UINT32 argCount) {
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlob> pHashBlob;
CComPtr<IDxcContainerReflection> pContainer;
UINT32 index;
CompileToProgram(program, entryPoint, target, pArguments, argCount,
&pProgram, &pResult);
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pContainer));
VERIFY_SUCCEEDED(pContainer->Load(pProgram));
if (FAILED(pContainer->FindFirstPartKind(hlsl::DFCC_ShaderHash, &index))) {
return std::string();
}
VERIFY_SUCCEEDED(pContainer->GetPartContent(index, &pHashBlob));
std::string hashFromPart = RetrieveHashFromBlob(pHashBlob);
CComPtr<IDxcResult> pDxcResult;
if (SUCCEEDED(pResult->QueryInterface(&pDxcResult))) {
// Make sure shader hash was returned in result
VERIFY_IS_TRUE(pDxcResult->HasOutput(DXC_OUT_SHADER_HASH));
pHashBlob.Release();
VERIFY_SUCCEEDED(pDxcResult->GetOutput(
DXC_OUT_SHADER_HASH, IID_PPV_ARGS(&pHashBlob), nullptr));
std::string hashFromResult = RetrieveHashFromBlob(pHashBlob);
VERIFY_ARE_EQUAL(hashFromPart, hashFromPart);
}
return hashFromPart;
}
std::string DisassembleProgram(LPCSTR program, LPCWSTR entryPoint,
LPCWSTR target) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CompileToProgram(program, entryPoint, target, nullptr, 0, &pProgram);
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembly));
return BlobToUtf8(pDisassembly);
}
void SetupBasicHeader(hlsl::DxilContainerHeader *pHeader,
uint32_t partCount = 0) {
ZeroMemory(pHeader, sizeof(*pHeader));
pHeader->HeaderFourCC = hlsl::DFCC_Container;
pHeader->Version.Major = 1;
pHeader->Version.Minor = 0;
pHeader->PartCount = partCount;
pHeader->ContainerSizeInBytes = sizeof(hlsl::DxilContainerHeader) +
sizeof(uint32_t) * partCount +
sizeof(hlsl::DxilPartHeader) * partCount;
}
void CodeGenTestCheck(LPCWSTR name) {
std::wstring fullPath = hlsl_test::GetPathToHlslDataFile(name);
FileRunTestResult t =
FileRunTestResult::RunFromFileCommands(fullPath.c_str());
if (t.RunResult != 0) {
CA2W commentWide(t.ErrorMessage.c_str());
WEX::Logging::Log::Comment(commentWide);
WEX::Logging::Log::Error(L"Run result is not zero");
}
}
#ifdef _WIN32 // DXBC Unsupported
WEX::Common::String WStrFmt(const wchar_t *msg, ...) {
va_list args;
va_start(args, msg);
WEX::Common::String result = WEX::Common::String().FormatV(msg, args);
va_end(args);
return result;
}
void ReflectionTest(
LPCWSTR name, bool ignoreIfDXBCFails,
UINT fxcFlags = D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES) {
WEX::Logging::Log::Comment(
WEX::Common::String().Format(L"Reflection comparison for %s", name));
// Skip if unsupported.
std::vector<FileRunCommandPart> parts;
ParseCommandPartsFromFile(name, parts);
VERIFY_IS_TRUE(parts.size() > 0);
if (parts[0].Command.compare("%dxilver") == 0) {
VERIFY_IS_TRUE(parts.size() > 1);
auto result = parts[0].Run(m_dllSupport, nullptr);
if (result.ExitCode != 0)
return;
}
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlob> pProgramDXBC;
HRESULT hrDXBC = CompileFromFile(name, true, fxcFlags, &pProgramDXBC);
if (FAILED(hrDXBC)) {
WEX::Logging::Log::Comment(L"Failed to compile DXBC blob.");
if (ignoreIfDXBCFails)
return;
VERIFY_FAIL();
}
if (FAILED(CompileFromFile(name, false, 0, &pProgram))) {
WEX::Logging::Log::Comment(L"Failed to compile DXIL blob.");
VERIFY_FAIL();
}
CComPtr<ID3D12ShaderReflection> pProgramReflection;
CComPtr<ID3D12ShaderReflection> pProgramReflectionDXBC;
CreateReflectionFromBlob(pProgram, &pProgramReflection);
CreateReflectionFromDXBC(pProgramDXBC, &pProgramReflectionDXBC);
CompareReflection(pProgramReflection, pProgramReflectionDXBC);
}
#endif // _WIN32 - DXBC Unsupported
};
bool DxilContainerTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
TEST_F(DxilContainerTest, CompileWhenDebugSourceThenSourceMatters) {
char program1[] = "float4 main() : SV_Target { return 0; }";
char program2[] = " float4 main() : SV_Target { return 0; } ";
LPCWSTR Zi[] = {L"/Zi", L"/Qembed_debug"};
LPCWSTR ZiZss[] = {L"/Zi", L"/Qembed_debug", L"/Zss"};
LPCWSTR ZiZsb[] = {L"/Zi", L"/Qembed_debug", L"/Zsb"};
LPCWSTR Zsb[] = {L"/Zsb"};
// No debug info, no debug name...
std::string noName =
CompileToDebugName(program1, L"main", L"ps_6_0", nullptr, 0);
VERIFY_IS_TRUE(noName.empty());
if (!DoesValidatorSupportDebugName())
return;
// Debug info, default to source name.
std::string sourceName1 =
CompileToDebugName(program1, L"main", L"ps_6_0", Zi, _countof(Zi));
VERIFY_IS_FALSE(sourceName1.empty());
// Deterministic naming.
std::string sourceName1Again =
CompileToDebugName(program1, L"main", L"ps_6_0", Zi, _countof(Zi));
VERIFY_ARE_EQUAL_STR(sourceName1.c_str(), sourceName1Again.c_str());
// Use program binary by default, so name should be the same.
std::string sourceName2 =
CompileToDebugName(program2, L"main", L"ps_6_0", Zi, _countof(Zi));
VERIFY_IS_TRUE(0 == strcmp(sourceName2.c_str(), sourceName1.c_str()));
// Source again, different because different switches are specified.
std::string sourceName1Zss =
CompileToDebugName(program1, L"main", L"ps_6_0", ZiZss, _countof(ZiZss));
VERIFY_IS_FALSE(0 == strcmp(sourceName1Zss.c_str(), sourceName1.c_str()));
// Binary program 1 and 2 should be different from source and equal to each
// other.
std::string binName1 =
CompileToDebugName(program1, L"main", L"ps_6_0", ZiZsb, _countof(ZiZsb));
std::string binName2 =
CompileToDebugName(program2, L"main", L"ps_6_0", ZiZsb, _countof(ZiZsb));
VERIFY_ARE_EQUAL_STR(binName1.c_str(), binName2.c_str());
VERIFY_IS_FALSE(0 == strcmp(sourceName1Zss.c_str(), binName1.c_str()));
if (!DoesValidatorSupportShaderHash())
return;
// Verify source hash
std::string binHash1Zss =
CompileToShaderHash(program1, L"main", L"ps_6_0", ZiZss, _countof(ZiZss));
VERIFY_IS_FALSE(binHash1Zss.empty());
// bin hash when compiling with /Zi
std::string binHash1 =
CompileToShaderHash(program1, L"main", L"ps_6_0", ZiZsb, _countof(ZiZsb));
VERIFY_IS_FALSE(binHash1.empty());
// Without /Zi hash for /Zsb should be the same
std::string binHash2 =
CompileToShaderHash(program2, L"main", L"ps_6_0", Zsb, _countof(Zsb));
VERIFY_IS_FALSE(binHash2.empty());
VERIFY_ARE_EQUAL_STR(binHash1.c_str(), binHash2.c_str());
// Source hash and bin hash should be different
VERIFY_IS_FALSE(0 == strcmp(binHash1Zss.c_str(), binHash1.c_str()));
}
TEST_F(DxilContainerTest, ContainerBuilder_AddPrivateForceLast) {
if (m_ver.SkipDxilVersion(1, 7))
return;
CComPtr<IDxcUtils> pUtils;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pDebugPart;
CComPtr<IDxcBlobEncoding> pPrivateData;
std::string data("Here is some private data.");
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
VERIFY_SUCCEEDED(
pUtils->CreateBlob(data.data(), data.size(), DXC_CP_ACP, &pPrivateData));
const char *shader =
"SamplerState Sampler : register(s0); RWBuffer<float> Uav : "
"register(u0); Texture2D<float> ThreeTextures[3] : register(t0); "
"float function1();"
"[shader(\"raygeneration\")] void RayGenMain() { Uav[0] = "
"ThreeTextures[0].SampleLevel(Sampler, float2(0, 0), 0) + "
"ThreeTextures[2].SampleLevel(Sampler, float2(0, 0), 0) + function1(); }";
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(shader, &pSource);
std::vector<LPCWSTR> arguments;
arguments.emplace_back(L"-Zi");
arguments.emplace_back(L"-Qembed_debug");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"", L"lib_6_3",
arguments.data(), arguments.size(),
nullptr, 0, nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
auto GetPart = [](IDxcBlob *pContainerBlob,
uint32_t fourCC) -> hlsl::DxilPartIterator {
const hlsl::DxilContainerHeader *pHeader =
(const hlsl::DxilContainerHeader *)pContainerBlob->GetBufferPointer();
hlsl::DxilPartIterator partIter = std::find_if(
hlsl::begin(pHeader), hlsl::end(pHeader), hlsl::DxilPartIsType(fourCC));
VERIFY_ARE_NOT_EQUAL(hlsl::end(pHeader), partIter);
return partIter;
};
auto VerifyPrivateLast = [](IDxcBlob *pContainerBlob) {
const hlsl::DxilContainerHeader *pHeader =
(const hlsl::DxilContainerHeader *)pContainerBlob->GetBufferPointer();
bool bFoundPrivate = false;
for (auto partIter = hlsl::begin(pHeader), end = hlsl::end(pHeader);
partIter != end; partIter++) {
VERIFY_IS_FALSE(bFoundPrivate && "otherwise, private data is not last");
if ((*partIter)->PartFourCC == hlsl::DFCC_PrivateData) {
bFoundPrivate = true;
}
}
VERIFY_IS_TRUE(bFoundPrivate);
};
auto debugPart = *GetPart(pProgram, hlsl::DFCC_ShaderDebugInfoDXIL);
VERIFY_SUCCEEDED(pUtils->CreateBlob(debugPart + 1, debugPart->PartSize,
DXC_CP_ACP, &pDebugPart));
// release for re-use
pResult.Release();
CComPtr<IDxcContainerBuilder> pBuilder;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerBuilder, &pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pProgram));
// remove debug info, add private, add debug back, and build container.
VERIFY_SUCCEEDED(pBuilder->RemovePart(hlsl::DFCC_ShaderDebugInfoDXIL));
VERIFY_SUCCEEDED(pBuilder->AddPart(hlsl::DFCC_PrivateData, pPrivateData));
VERIFY_SUCCEEDED(
pBuilder->AddPart(hlsl::DFCC_ShaderDebugInfoDXIL, pDebugPart));
CComPtr<IDxcBlob> pNewContainer;
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pNewContainer));
// GetPart verifies we have debug info, but don't need result.
GetPart(pNewContainer, hlsl::DFCC_ShaderDebugInfoDXIL);
VerifyPrivateLast(pNewContainer);
// release for re-use
pResult.Release();
pBuilder.Release();
// Now verify that we can remove and re-add private without error
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerBuilder, &pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pNewContainer));
VERIFY_SUCCEEDED(pBuilder->RemovePart(hlsl::DFCC_ShaderDebugInfoDXIL));
VERIFY_SUCCEEDED(pBuilder->RemovePart(hlsl::DFCC_PrivateData));
VERIFY_SUCCEEDED(pBuilder->AddPart(hlsl::DFCC_PrivateData, pPrivateData));
VERIFY_SUCCEEDED(
pBuilder->AddPart(hlsl::DFCC_ShaderDebugInfoDXIL, pDebugPart));
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
pNewContainer.Release();
VERIFY_SUCCEEDED(pResult->GetResult(&pNewContainer));
// verify private data found after debug info again
GetPart(pNewContainer, hlsl::DFCC_ShaderDebugInfoDXIL);
VerifyPrivateLast(pNewContainer);
}
TEST_F(DxilContainerTest, CompileWhenOKThenIncludesSignatures) {
char program[] =
"struct PSInput {\r\n"
" float4 position : SV_POSITION;\r\n"
" float4 color : COLOR;\r\n"
"};\r\n"
"PSInput VSMain(float4 position : POSITION, float4 color : COLOR) {\r\n"
" PSInput result;\r\n"
" result.position = position;\r\n"
" result.color = color;\r\n"
" return result;\r\n"
"}\r\n"
"float4 PSMain(PSInput input) : SV_TARGET {\r\n"
" return input.color;\r\n"
"}";
{
std::string s = DisassembleProgram(program, L"VSMain", L"vs_6_0");
// NOTE: this will change when proper packing is done, and when
// 'always-reads' is accurately implemented.
const char
expected_1_4[] = ";\n"
"; Input signature:\n"
";\n"
"; Name Index Mask Register "
"SysValue Format Used\n"
"; -------------------- ----- ------ -------- "
"-------- ------- ------\n"
"; POSITION 0 xyzw 0 "
"NONE float \n" // should read 'xyzw' in Used
"; COLOR 0 xyzw 1 "
"NONE float \n" // should read '1' in register
";\n"
";\n"
"; Output signature:\n"
";\n"
"; Name Index Mask Register "
"SysValue Format Used\n"
"; -------------------- ----- ------ -------- "
"-------- ------- ------\n"
"; SV_Position 0 xyzw 0 "
"POS float xyzw\n" // could read SV_POSITION
"; COLOR 0 xyzw 1 "
"NONE float xyzw\n"; // should read '1' in register
const char
expected[] = ";\n"
"; Input signature:\n"
";\n"
"; Name Index Mask Register SysValue "
"Format Used\n"
"; -------------------- ----- ------ -------- -------- "
"------- ------\n"
"; POSITION 0 xyzw 0 NONE "
"float xyzw\n" // should read 'xyzw' in Used
"; COLOR 0 xyzw 1 NONE "
"float xyzw\n" // should read '1' in register
";\n"
";\n"
"; Output signature:\n"
";\n"
"; Name Index Mask Register SysValue "
"Format Used\n"
"; -------------------- ----- ------ -------- -------- "
"------- ------\n"
"; SV_Position 0 xyzw 0 POS "
"float xyzw\n" // could read SV_POSITION
"; COLOR 0 xyzw 1 NONE "
"float xyzw\n"; // should read '1' in register
if (hlsl::DXIL::CompareVersions(m_ver.m_ValMajor, m_ver.m_ValMinor, 1, 5) <
0) {
std::string start(s.c_str(), strlen(expected_1_4));
VERIFY_ARE_EQUAL_STR(expected_1_4, start.c_str());
} else {
std::string start(s.c_str(), strlen(expected));
VERIFY_ARE_EQUAL_STR(expected, start.c_str());
}
}
{
std::string s = DisassembleProgram(program, L"PSMain", L"ps_6_0");
// NOTE: this will change when proper packing is done, and when
// 'always-reads' is accurately implemented.
const char
expected_1_4[] =
";\n"
"; Input signature:\n"
";\n"
"; Name Index Mask Register SysValue Format "
"Used\n"
"; -------------------- ----- ------ -------- -------- ------- "
"------\n"
"; SV_Position 0 xyzw 0 POS float "
" \n" // could read SV_POSITION
"; COLOR 0 xyzw 1 NONE float "
" \n" // should read '1' in register, xyzw in Used
";\n"
";\n"
"; Output signature:\n"
";\n"
"; Name Index Mask Register SysValue Format "
"Used\n"
"; -------------------- ----- ------ -------- -------- ------- "
"------\n"
"; SV_Target 0 xyzw 0 TARGET float "
"xyzw\n"; // could read SV_TARGET
const char
expected[] =
";\n"
"; Input signature:\n"
";\n"
"; Name Index Mask Register SysValue Format "
"Used\n"
"; -------------------- ----- ------ -------- -------- ------- "
"------\n"
"; SV_Position 0 xyzw 0 POS float "
" \n" // could read SV_POSITION
"; COLOR 0 xyzw 1 NONE float "
"xyzw\n" // should read '1' in register, xyzw in Used
";\n"
";\n"
"; Output signature:\n"
";\n"
"; Name Index Mask Register SysValue Format "
"Used\n"
"; -------------------- ----- ------ -------- -------- ------- "
"------\n"
"; SV_Target 0 xyzw 0 TARGET float "
"xyzw\n"; // could read SV_TARGET
if (hlsl::DXIL::CompareVersions(m_ver.m_ValMajor, m_ver.m_ValMinor, 1, 5) <
0) {
std::string start(s.c_str(), strlen(expected_1_4));
VERIFY_ARE_EQUAL_STR(expected_1_4, start.c_str());
} else {
std::string start(s.c_str(), strlen(expected));
VERIFY_ARE_EQUAL_STR(expected, start.c_str());
}
}
}
TEST_F(DxilContainerTest, CompileWhenSigSquareThenIncludeSplit) {
#if 0 // TODO: reenable test when multiple rows are supported.
const char program[] =
"float main(float4x4 a : A, int4 b : B) : SV_Target {\n"
" return a[b.x][b.y];\n"
"}";
std::string s = DisassembleProgram(program, L"main", L"ps_6_0");
const char expected[] =
"// Input signature:\n"
"//\n"
"// Name Index Mask Register SysValue Format Used\n"
"// -------------------- ----- ------ -------- -------- ------- ------\n"
"// A 0 xyzw 0 NONE float xyzw\n"
"// A 1 xyzw 1 NONE float xyzw\n"
"// A 2 xyzw 2 NONE float xyzw\n"
"// A 3 xyzw 3 NONE float xyzw\n"
"// B 0 xyzw 4 NONE int xy\n"
"//\n"
"//\n"
"// Output signature:\n"
"//\n"
"// Name Index Mask Register SysValue Format Used\n"
"// -------------------- ----- ------ -------- -------- ------- ------\n"
"// SV_Target 0 x 0 TARGET float x\n";
std::string start(s.c_str(), strlen(expected));
VERIFY_ARE_EQUAL_STR(expected, start.c_str());
#endif
}
TEST_F(DxilContainerTest, CompileAS_CheckPSV0) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char asSource[] = "struct PayloadType { uint a, b, c; };\n"
"[shader(\"amplification\")]\n"
"[numthreads(1,1,1)]\n"
"void main(uint idx : SV_GroupIndex) {\n"
" PayloadType p = { idx, 2, 3 };\n"
" DispatchMesh(1,1,1, p);\n"
"}";
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(asSource, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"as_6_5",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
HRESULT hrStatus;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrStatus));
VERIFY_SUCCEEDED(hrStatus);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
CComPtr<IDxcContainerReflection> containerReflection;
uint32_t partCount;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
IFT(containerReflection->Load(pProgram));
IFT(containerReflection->GetPartCount(&partCount));
bool blobFound = false;
for (uint32_t i = 0; i < partCount; ++i) {
uint32_t kind;
VERIFY_SUCCEEDED(containerReflection->GetPartKind(i, &kind));
if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_PipelineStateValidation) {
blobFound = true;
CComPtr<IDxcBlob> pBlob;
VERIFY_SUCCEEDED(containerReflection->GetPartContent(i, &pBlob));
DxilPipelineStateValidation PSV;
PSV.InitFromPSV0(pBlob->GetBufferPointer(), pBlob->GetBufferSize());
PSVShaderKind kind = PSV.GetShaderKind();
VERIFY_ARE_EQUAL(PSVShaderKind::Amplification, kind);
PSVRuntimeInfo0 *pInfo = PSV.GetPSVRuntimeInfo0();
VERIFY_IS_NOT_NULL(pInfo);
VERIFY_ARE_EQUAL(12U, pInfo->AS.PayloadSizeInBytes);
break;
}
}
VERIFY_IS_TRUE(blobFound);
}
TEST_F(DxilContainerTest, CompileGS_CheckPSV0_ViewID) {
if (m_ver.SkipDxilVersion(1, 7))
return;
// Verify that ViewID and Input to Output masks are correct for
// geometry shader with multiple stream outputs.
// This acts as a regression test for issue #5199, where a single pointer was
// used for the ViewID dependency mask and a single pointer for input to
// output dependencies, when each of these needed a separate pointer per
// stream. The effect was an overlapping and clobbering of data for earlier
// streams.
// Skip validator versions < 1.7 since they lack the fix.
const unsigned ARRAY_SIZE = 8;
const char gsSource[] = "#define ARRAY_SIZE 8\n"
"struct GSOut0 { float4 pos : SV_Position; };\n"
"struct GSOut1 { float4 arr[ARRAY_SIZE] : Array; };\n"
"[shader(\"geometry\")]\n"
"[maxvertexcount(1)]\n"
"void main(point float4 input[1] : COORD,\n"
" inout PointStream<GSOut0> out0,\n"
" inout PointStream<GSOut1> out1,\n"
" uint vid : SV_ViewID) {\n"
" GSOut0 o0 = (GSOut0)0;\n"
" GSOut1 o1 = (GSOut1)0;\n"
" o0.pos = input[0];\n"
" out0.Append(o0);\n"
" out0.RestartStrip();\n"
" [unroll]\n"
" for (uint i = 0; i < ARRAY_SIZE; i++)\n"
" o1.arr[i] = input[0][i%4] + vid;\n"
" out1.Append(o1);\n"
" out1.RestartStrip();\n"
"}";
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcOperationResult> pResult;
// Compile the shader
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(gsSource, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"gs_6_3",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
HRESULT hrStatus;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrStatus));
VERIFY_SUCCEEDED(hrStatus);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Get PSV0 part
CComPtr<IDxcContainerReflection> containerReflection;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
VERIFY_SUCCEEDED(containerReflection->Load(pProgram));
uint32_t partIdx = 0;
VERIFY_SUCCEEDED(containerReflection->FindFirstPartKind(
(uint32_t)hlsl::DxilFourCC::DFCC_PipelineStateValidation, &partIdx));
CComPtr<IDxcBlob> pBlob;
VERIFY_SUCCEEDED(containerReflection->GetPartContent(partIdx, &pBlob));
// Init PSV and verify ViewID masks and Input to Output Masks
DxilPipelineStateValidation PSV;
PSV.InitFromPSV0(pBlob->GetBufferPointer(), pBlob->GetBufferSize());
PSVShaderKind kind = PSV.GetShaderKind();
VERIFY_ARE_EQUAL(PSVShaderKind::Geometry, kind);
PSVRuntimeInfo0 *pInfo = PSV.GetPSVRuntimeInfo0();
VERIFY_IS_NOT_NULL(pInfo);
// Stream 0 should have no direct ViewID dependency:
PSVComponentMask viewIDMask0 = PSV.GetViewIDOutputMask(0);
VERIFY_IS_TRUE(viewIDMask0.IsValid());
VERIFY_ARE_EQUAL(1U, viewIDMask0.NumVectors);
for (unsigned i = 0; i < 4; i++) {
VERIFY_IS_FALSE(viewIDMask0.Get(i));
}
// Everything in stream 1 should be dependent on ViewID:
PSVComponentMask viewIDMask1 = PSV.GetViewIDOutputMask(1);
VERIFY_IS_TRUE(viewIDMask1.IsValid());
VERIFY_ARE_EQUAL(ARRAY_SIZE, viewIDMask1.NumVectors);
for (unsigned i = 0; i < ARRAY_SIZE * 4; i++) {
VERIFY_IS_TRUE(viewIDMask1.Get(i));
}
// Stream 0 is simple assignment of input vector:
PSVDependencyTable ioTable0 = PSV.GetInputToOutputTable(0);
VERIFY_IS_TRUE(ioTable0.IsValid());
VERIFY_ARE_EQUAL(1U, ioTable0.OutputVectors);
for (unsigned i = 0; i < 4; i++) {
PSVComponentMask ioMask0_i = ioTable0.GetMaskForInput(i);
// input 0123 -> output 0123
for (unsigned j = 0; j < 4; j++) {
VERIFY_ARE_EQUAL(i == j, ioMask0_i.Get(j));
}
}
// Each vector in Stream 1 combines one component of input with ViewID:
PSVDependencyTable ioTable1 = PSV.GetInputToOutputTable(1);
VERIFY_IS_TRUE(ioTable1.IsValid());
VERIFY_ARE_EQUAL(ARRAY_SIZE, ioTable1.OutputVectors);
for (unsigned i = 0; i < 4; i++) {
PSVComponentMask ioMask1_i = ioTable1.GetMaskForInput(i);
for (unsigned j = 0; j < ARRAY_SIZE * 4; j++) {
// Vector output vector/component dependency by input component:
// 0000, 1111, 2222, 3333, 0000, 1111, 2222, 3333, ...
VERIFY_ARE_EQUAL(i == (j / 4) % 4, ioMask1_i.Get(j));
}
}
}
TEST_F(DxilContainerTest, Compile_CheckPSV0_EntryFunctionName) {
if (m_ver.SkipDxilVersion(1, 8))
return;
auto CheckEntryFunctionNameForProgram = [&](const char *EntryPointName,
CComPtr<IDxcBlob> pProgram) {
// Get PSV0 part
CComPtr<IDxcContainerReflection> containerReflection;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
VERIFY_SUCCEEDED(containerReflection->Load(pProgram));
uint32_t partIdx = 0;
VERIFY_SUCCEEDED(containerReflection->FindFirstPartKind(
(uint32_t)hlsl::DxilFourCC::DFCC_PipelineStateValidation, &partIdx));
CComPtr<IDxcBlob> pBlob;
VERIFY_SUCCEEDED(containerReflection->GetPartContent(partIdx, &pBlob));
// Look up EntryFunctionName in PSV0
DxilPipelineStateValidation PSV;
PSV.InitFromPSV0(pBlob->GetBufferPointer(), pBlob->GetBufferSize());
// We should have a valid PSVRuntimeInfo3 structure
PSVRuntimeInfo3 *pInfo3 = PSV.GetPSVRuntimeInfo3();
VERIFY_IS_NOT_NULL(pInfo3);
// Finally, verify that the entry function name in PSV0 matches
VERIFY_ARE_EQUAL_STR(EntryPointName, PSV.GetEntryFunctionName());
};
auto CheckEntryFunctionNameForHLSL = [&](const char *EntryPointName,
const char *Source,
const char *Profile) {
CComPtr<IDxcBlob> pProgram;
CA2W wEntryPointName(EntryPointName);
CA2W wProfile(Profile);
CompileToProgram(Source, wEntryPointName, wProfile, nullptr, 0, &pProgram);
CheckEntryFunctionNameForProgram(EntryPointName, pProgram);
};
auto CheckEntryFunctionNameForLL = [&](const char *EntryPointName,
const char *Source) {
CComPtr<IDxcBlob> pProgram;
AssembleToProgram(Source, &pProgram);
CheckEntryFunctionNameForProgram(EntryPointName, pProgram);
};
const char src_PSMain[] = "float MyPSMain() : SV_Target { return 0; }";
const char src_VSMain[] = "float4 MyVSMain() : SV_Position { return 0; }";
const char src_CSMain[] = "[numthreads(1,1,1)] void MyCSMain() {}";
CheckEntryFunctionNameForHLSL("MyPSMain", src_PSMain, "ps_6_0");
CheckEntryFunctionNameForHLSL("MyVSMain", src_VSMain, "vs_6_0");
CheckEntryFunctionNameForHLSL("MyCSMain", src_CSMain, "cs_6_0");
// HS is interesting because of the passthrough case, where the main control
// point function body can be eliminated.
const char src_HSMain[] = R"(
struct HSInputOutput { float4 pos : POSITION; };
struct HSPerPatchData {
float edges[3] : SV_TessFactor;
float inside : SV_InsideTessFactor;
};
[domain("tri")] [partitioning("integer")] [outputtopology("triangle_cw")]
[outputcontrolpoints(3)] [patchconstantfunc("MyPatchConstantFunc")]
HSInputOutput MyHSMain(InputPatch<HSInputOutput, 3> input,
uint id : SV_OutputControlPointID) {
HSInputOutput output;
output.pos = input[id].pos * id;
return output;
}
[domain("tri")] [partitioning("integer")] [outputtopology("triangle_cw")]
[outputcontrolpoints(3)] [patchconstantfunc("MyPatchConstantFunc")]
HSInputOutput MyHSMainPassthrough(InputPatch<HSInputOutput, 3> input,
uint id : SV_OutputControlPointID) {
return input[id];
}
void MyPatchConstantFunc(out HSPerPatchData output) {
output.edges[0] = 1;
output.edges[1] = 2;
output.edges[2] = 3;
output.inside = 4;
}
)";
CheckEntryFunctionNameForHLSL("MyHSMain", src_HSMain, "hs_6_0");
CheckEntryFunctionNameForHLSL("MyHSMainPassthrough", src_HSMain, "hs_6_0");
// Because DXC currently won't eliminate the main HS function body for the
// passthrough case, we must construct the IR manually to test that.
// TODO: There are problems blocking the real pass-through control point
// function case.
// See: https://github.com/microsoft/DirectXShaderCompiler/issues/6001
// Update this code once this case is fixed.
const char ll_HSPassthrough[] = R"!!!(
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
define void @MyHSMainPassthrough() {
ret void
}
define void @"\01?MyPatchConstantFunc@@YAXUHSPerPatchData@@@Z"() {
entry:
call void @dx.op.storePatchConstant.f32(i32 106, i32 0, i32 0, i8 0, float 1.000000e+00)
call void @dx.op.storePatchConstant.f32(i32 106, i32 0, i32 1, i8 0, float 2.000000e+00)
call void @dx.op.storePatchConstant.f32(i32 106, i32 0, i32 2, i8 0, float 3.000000e+00)
call void @dx.op.storePatchConstant.f32(i32 106, i32 1, i32 0, i8 0, float 4.000000e+00)
ret void
}
; Function Attrs: nounwind
declare void @dx.op.storePatchConstant.f32(i32, i32, i32, i8, float) #1
attributes #0 = { nounwind readnone }
attributes #1 = { nounwind }
!llvm.ident = !{!0}
!dx.version = !{!1}
!dx.valver = !{!2}
!dx.shaderModel = !{!3}
!dx.typeAnnotations = !{!4}
!dx.viewIdState = !{!8}
!dx.entryPoints = !{!9}
!0 = !{!"dxc(private) 1.7.0.4190 (psv0-add-entryname, f73dd2937)"}
!1 = !{i32 1, i32 0}
!2 = !{i32 1, i32 8}
!3 = !{!"hs", i32 6, i32 0}
!4 = !{i32 1, void ()* @"\01?MyPatchConstantFunc@@YAXUHSPerPatchData@@@Z", !5, void ()* @MyHSMainPassthrough, !5}
!5 = !{!6}
!6 = !{i32 0, !7, !7}
!7 = !{}
!8 = !{[11 x i32] [i32 4, i32 4, i32 1, i32 2, i32 4, i32 8, i32 13, i32 0, i32 0, i32 0, i32 0]}
!9 = !{void ()* @MyHSMainPassthrough, !"MyHSMainPassthrough", !10, null, !20}
!10 = !{!11, !11, !15}
!11 = !{!12}
!12 = !{i32 0, !"POSITION", i8 9, i8 0, !13, i8 2, i32 1, i8 4, i32 0, i8 0, !14}
!13 = !{i32 0}
!14 = !{i32 3, i32 15}
!15 = !{!16, !19}
!16 = !{i32 0, !"SV_TessFactor", i8 9, i8 25, !17, i8 0, i32 3, i8 1, i32 0, i8 3, !18}
!17 = !{i32 0, i32 1, i32 2}
!18 = !{i32 3, i32 1}
!19 = !{i32 1, !"SV_InsideTessFactor", i8 9, i8 26, !13, i8 0, i32 1, i8 1, i32 3, i8 0, !18}
!20 = !{i32 3, !21}
!21 = !{void ()* @"\01?MyPatchConstantFunc@@YAXUHSPerPatchData@@@Z", i32 3, i32 3, i32 2, i32 1, i32 3, float 6.400000e+01}
)!!!";
CheckEntryFunctionNameForLL("MyHSMainPassthrough", ll_HSPassthrough);
}
TEST_F(DxilContainerTest, CompileCSWaveSize_CheckPSV0) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char csSource[] = R"(
RWByteAddressBuffer B;
[numthreads(1,1,1)]
[wavesize(16)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x == 0)
B.Store(0, WaveGetLaneCount());
}
)";
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcOperationResult> pResult;
CompileToProgram(csSource, L"main", L"cs_6_6", nullptr, 0, &pProgram,
&pResult);
CComPtr<IDxcContainerReflection> containerReflection;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
IFT(containerReflection->Load(pProgram));
UINT32 partIdx = 0;
IFT(containerReflection->FindFirstPartKind(
(uint32_t)hlsl::DxilFourCC::DFCC_PipelineStateValidation, &partIdx))
CComPtr<IDxcBlob> pBlob;
VERIFY_SUCCEEDED(containerReflection->GetPartContent(partIdx, &pBlob));
DxilPipelineStateValidation PSV;
PSV.InitFromPSV0(pBlob->GetBufferPointer(), pBlob->GetBufferSize());
PSVShaderKind kind = PSV.GetShaderKind();
VERIFY_ARE_EQUAL(PSVShaderKind::Compute, kind);
PSVRuntimeInfo0 *pInfo = PSV.GetPSVRuntimeInfo0();
VERIFY_IS_NOT_NULL(pInfo);
VERIFY_ARE_EQUAL(16U, pInfo->MaximumExpectedWaveLaneCount);
VERIFY_ARE_EQUAL(16U, pInfo->MinimumExpectedWaveLaneCount);
}
TEST_F(DxilContainerTest, CompileCSWaveSizeRange_CheckPSV0) {
if (m_ver.SkipDxilVersion(1, 8))
return;
const char csSource[] = R"(
RWByteAddressBuffer B;
[numthreads(1,1,1)]
[wavesize(16, 64 PREFERRED)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x == 0)
B.Store(0, WaveGetLaneCount());
}
)";
auto TestCompile = [&](LPCWSTR defPreferred) {
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcOperationResult> pResult;
LPCWSTR args[] = {defPreferred};
CompileToProgram(csSource, L"main", L"cs_6_8", args, 1, &pProgram,
&pResult);
CComPtr<IDxcContainerReflection> containerReflection;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
IFT(containerReflection->Load(pProgram));
UINT32 partIdx = 0;
IFT(containerReflection->FindFirstPartKind(
(uint32_t)hlsl::DxilFourCC::DFCC_PipelineStateValidation, &partIdx))
CComPtr<IDxcBlob> pBlob;
VERIFY_SUCCEEDED(containerReflection->GetPartContent(partIdx, &pBlob));
DxilPipelineStateValidation PSV;
PSV.InitFromPSV0(pBlob->GetBufferPointer(), pBlob->GetBufferSize());
PSVShaderKind kind = PSV.GetShaderKind();
VERIFY_ARE_EQUAL(PSVShaderKind::Compute, kind);
PSVRuntimeInfo0 *pInfo = PSV.GetPSVRuntimeInfo0();
VERIFY_IS_NOT_NULL(pInfo);
VERIFY_ARE_EQUAL(16U, pInfo->MinimumExpectedWaveLaneCount);
VERIFY_ARE_EQUAL(64U, pInfo->MaximumExpectedWaveLaneCount);
};
// Same range, whether preferred is set or not.
TestCompile(L"-DPREFERRED=");
TestCompile(L"-DPREFERRED=,32");
}
TEST_F(DxilContainerTest, CompileWhenOkThenCheckRDAT) {
if (m_ver.SkipDxilVersion(1, 3))
return;
const char *shader =
"float c_buf;"
"RWTexture1D<int4> tex : register(u5);"
"Texture1D<float4> tex2 : register(t0);"
"RWByteAddressBuffer b_buf;"
"struct Foo { float2 f2; int2 i2; };"
"AppendStructuredBuffer<Foo> append_buf;"
"ConsumeStructuredBuffer<Foo> consume_buf;"
"RasterizerOrderedByteAddressBuffer rov_buf;"
"globallycoherent RWByteAddressBuffer gc_buf;"
"float function_import(float x);"
"export float function0(min16float x) { "
" return x + 1 + tex[0].x; }"
"export float function1(float x, min12int i) {"
" return x + c_buf + b_buf.Load(x) + tex2[i].x; }"
"export float function2(float x) { return x + function_import(x); }"
"export void function3(int i) {"
" Foo f = consume_buf.Consume();"
" f.f2 += 0.5; append_buf.Append(f);"
" rov_buf.Store(i, f.i2.x);"
" gc_buf.Store(i, f.i2.y);"
" b_buf.Store(i, f.i2.x + f.i2.y); }";
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
struct CheckResFlagInfo {
std::string name;
hlsl::DXIL::ResourceKind kind;
hlsl::RDAT::DxilResourceFlag flag;
};
const unsigned numResFlagCheck = 5;
CheckResFlagInfo resFlags[numResFlagCheck] = {
{"b_buf", hlsl::DXIL::ResourceKind::RawBuffer,
hlsl::RDAT::DxilResourceFlag::None},
{"append_buf", hlsl::DXIL::ResourceKind::StructuredBuffer,
hlsl::RDAT::DxilResourceFlag::UAVCounter},
{"consume_buf", hlsl::DXIL::ResourceKind::StructuredBuffer,
hlsl::RDAT::DxilResourceFlag::UAVCounter},
{"gc_buf", hlsl::DXIL::ResourceKind::RawBuffer,
hlsl::RDAT::DxilResourceFlag::UAVGloballyCoherent},
{"rov_buf", hlsl::DXIL::ResourceKind::RawBuffer,
hlsl::RDAT::DxilResourceFlag::UAVRasterizerOrderedView}};
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(shader, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
L"lib_6_3", nullptr, 0, nullptr, 0,
nullptr, &pResult));
HRESULT hrStatus;
VERIFY_SUCCEEDED(pResult->GetStatus(&hrStatus));
VERIFY_SUCCEEDED(hrStatus);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
CComPtr<IDxcContainerReflection> containerReflection;
uint32_t partCount;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
IFT(containerReflection->Load(pProgram));
IFT(containerReflection->GetPartCount(&partCount));
bool blobFound = false;
for (uint32_t i = 0; i < partCount; ++i) {
uint32_t kind;
IFT(containerReflection->GetPartKind(i, &kind));
if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_RuntimeData) {
blobFound = true;
using namespace hlsl::RDAT;
CComPtr<IDxcBlob> pBlob;
IFT(containerReflection->GetPartContent(i, &pBlob));
// Validate using DxilRuntimeData
DxilRuntimeData context;
context.InitFromRDAT((char *)pBlob->GetBufferPointer(),
pBlob->GetBufferSize());
auto funcTable = context.GetFunctionTable();
auto resTable = context.GetResourceTable();
VERIFY_ARE_EQUAL(funcTable.Count(), 4U);
std::string str("function");
for (uint32_t j = 0; j < funcTable.Count(); ++j) {
auto funcReader = funcTable[j];
std::string funcName(funcReader.getUnmangledName());
VERIFY_IS_TRUE(str.compare(funcName.substr(0, 8)) == 0);
std::string cur_str = str;
cur_str.push_back('0' + j);
if (cur_str.compare("function0") == 0) {
VERIFY_ARE_EQUAL(funcReader.getResources().Count(), 1U);
hlsl::ShaderFlags flag;
flag.SetUAVLoadAdditionalFormats(true);
flag.SetLowPrecisionPresent(true);
uint64_t rawFlag = flag.GetFeatureInfo();
VERIFY_ARE_EQUAL(funcReader.GetFeatureFlags(), rawFlag);
auto resReader = funcReader.getResources()[0];
VERIFY_ARE_EQUAL(resReader.getClass(),
hlsl::DXIL::ResourceClass::UAV);
VERIFY_ARE_EQUAL(resReader.getKind(),
hlsl::DXIL::ResourceKind::Texture1D);
} else if (cur_str.compare("function1") == 0) {
hlsl::ShaderFlags flag;
flag.SetLowPrecisionPresent(true);
uint64_t rawFlag = flag.GetFeatureInfo();
VERIFY_ARE_EQUAL(funcReader.GetFeatureFlags(), rawFlag);
VERIFY_ARE_EQUAL(funcReader.getResources().Count(), 3U);
} else if (cur_str.compare("function2") == 0) {
VERIFY_ARE_EQUAL(funcReader.GetFeatureFlags() & 0xffffffffffffffff,
0U);
VERIFY_ARE_EQUAL(funcReader.getResources().Count(), 0U);
std::string dependency = funcReader.getFunctionDependencies()[0];
VERIFY_IS_TRUE(dependency.find("function_import") !=
std::string::npos);
} else if (cur_str.compare("function3") == 0) {
VERIFY_ARE_EQUAL(funcReader.GetFeatureFlags() & 0xffffffffffffffff,
0U);
VERIFY_ARE_EQUAL(funcReader.getResources().Count(), numResFlagCheck);
for (unsigned i = 0; i < funcReader.getResources().Count(); ++i) {
auto resReader = funcReader.getResources()[0];
VERIFY_ARE_EQUAL(resReader.getClass(),
hlsl::DXIL::ResourceClass::UAV);
unsigned j = 0;
for (; j < numResFlagCheck; ++j) {
if (resFlags[j].name.compare(resReader.getName()) == 0)
break;
}
VERIFY_IS_LESS_THAN(j, numResFlagCheck);
VERIFY_ARE_EQUAL(resReader.getKind(), resFlags[j].kind);
VERIFY_ARE_EQUAL(resReader.getFlags(),
static_cast<uint32_t>(resFlags[j].flag));
}
} else {
IFTBOOLMSG(false, E_FAIL, "unknown function name");
}
}
VERIFY_ARE_EQUAL(resTable.Count(), 8U);
}
}
IFTBOOLMSG(blobFound, E_FAIL, "failed to find RDAT blob after compiling");
}
TEST_F(DxilContainerTest, CompileWhenOkThenCheckRDAT2) {
if (m_ver.SkipDxilVersion(1, 3))
return;
// This is a case when the user of resource is a constant, not instruction.
// Compiler generates the following load instruction for texture.
// load %class.Texture2D, %class.Texture2D* getelementptr inbounds ([3 x
// %class.Texture2D], [3 x %class.Texture2D]*
// @"\01?ThreeTextures@@3PAV?$Texture2D@M@@A", i32 0, i32 0), align 4
const char *shader =
"SamplerState Sampler : register(s0); RWBuffer<float> Uav : "
"register(u0); Texture2D<float> ThreeTextures[3] : register(t0); "
"float function1();"
"[shader(\"raygeneration\")] void RayGenMain() { Uav[0] = "
"ThreeTextures[0].SampleLevel(Sampler, float2(0, 0), 0) + "
"ThreeTextures[2].SampleLevel(Sampler, float2(0, 0), 0) + function1(); }";
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
HRESULT status;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(shader, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
L"lib_6_3", nullptr, 0, nullptr, 0,
nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_SUCCEEDED(status);
CComPtr<IDxcContainerReflection> pReflection;
uint32_t partCount;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
IFT(pReflection->Load(pProgram));
IFT(pReflection->GetPartCount(&partCount));
bool blobFound = false;
for (uint32_t i = 0; i < partCount; ++i) {
uint32_t kind;
IFT(pReflection->GetPartKind(i, &kind));
if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_RuntimeData) {
blobFound = true;
using namespace hlsl::RDAT;
CComPtr<IDxcBlob> pBlob;
IFT(pReflection->GetPartContent(i, &pBlob));
DxilRuntimeData context;
context.InitFromRDAT((char *)pBlob->GetBufferPointer(),
pBlob->GetBufferSize());
auto funcTable = context.GetFunctionTable();
auto resTable = context.GetResourceTable();
VERIFY_IS_TRUE(funcTable.Count() == 1);
VERIFY_IS_TRUE(resTable.Count() == 3);
auto funcReader = funcTable[0];
llvm::StringRef name(funcReader.getUnmangledName());
VERIFY_IS_TRUE(name.compare("RayGenMain") == 0);
VERIFY_IS_TRUE(funcReader.getShaderKind() ==
hlsl::DXIL::ShaderKind::RayGeneration);
VERIFY_IS_TRUE(funcReader.getResources().Count() == 3);
VERIFY_IS_TRUE(funcReader.getFunctionDependencies().Count() == 1);
llvm::StringRef dependencyName = hlsl::dxilutil::DemangleFunctionName(
funcReader.getFunctionDependencies()[0]);
VERIFY_IS_TRUE(dependencyName.compare("function1") == 0);
}
}
IFTBOOLMSG(blobFound, E_FAIL, "failed to find RDAT blob after compiling");
}
static uint32_t EncodedVersion_lib_6_3 =
hlsl::EncodeVersion(hlsl::DXIL::ShaderKind::Library, 6, 3);
static uint32_t EncodedVersion_vs_6_3 =
hlsl::EncodeVersion(hlsl::DXIL::ShaderKind::Vertex, 6, 3);
static void
Ref1_CheckCBuffer_Globals(ID3D12ShaderReflectionConstantBuffer *pCBReflection,
D3D12_SHADER_BUFFER_DESC &cbDesc) {
std::string cbName = cbDesc.Name;
VERIFY_IS_TRUE(cbName.compare("$Globals") == 0);
VERIFY_ARE_EQUAL(cbDesc.Size, 16U);
VERIFY_ARE_EQUAL(cbDesc.Type, D3D_CT_CBUFFER);
VERIFY_ARE_EQUAL(cbDesc.Variables, 1U);
// cbval1
ID3D12ShaderReflectionVariable *pVar = pCBReflection->GetVariableByIndex(0);
D3D12_SHADER_VARIABLE_DESC varDesc;
VERIFY_SUCCEEDED(pVar->GetDesc(&varDesc));
VERIFY_ARE_EQUAL_STR(varDesc.Name, "cbval1");
VERIFY_ARE_EQUAL(varDesc.StartOffset, 0U);
VERIFY_ARE_EQUAL(varDesc.Size, 4U);
// TODO: verify rest of variable
ID3D12ShaderReflectionType *pType = pVar->GetType();
D3D12_SHADER_TYPE_DESC tyDesc;
VERIFY_SUCCEEDED(pType->GetDesc(&tyDesc));
VERIFY_ARE_EQUAL(tyDesc.Class, D3D_SVC_SCALAR);
VERIFY_ARE_EQUAL(tyDesc.Type, D3D_SVT_FLOAT);
// TODO: verify rest of type
}
static void
Ref1_CheckCBuffer_MyCB(ID3D12ShaderReflectionConstantBuffer *pCBReflection,
D3D12_SHADER_BUFFER_DESC &cbDesc) {
std::string cbName = cbDesc.Name;
VERIFY_IS_TRUE(cbName.compare("MyCB") == 0);
VERIFY_ARE_EQUAL(cbDesc.Size, 32U);
VERIFY_ARE_EQUAL(cbDesc.Type, D3D_CT_CBUFFER);
VERIFY_ARE_EQUAL(cbDesc.Variables, 2U);
// cbval2
{
ID3D12ShaderReflectionVariable *pVar = pCBReflection->GetVariableByIndex(0);
D3D12_SHADER_VARIABLE_DESC varDesc;
VERIFY_SUCCEEDED(pVar->GetDesc(&varDesc));
VERIFY_ARE_EQUAL_STR(varDesc.Name, "cbval2");
VERIFY_ARE_EQUAL(varDesc.StartOffset, 0U);
VERIFY_ARE_EQUAL(varDesc.Size, 16U);
// TODO: verify rest of variable
ID3D12ShaderReflectionType *pType = pVar->GetType();
D3D12_SHADER_TYPE_DESC tyDesc;
VERIFY_SUCCEEDED(pType->GetDesc(&tyDesc));
VERIFY_ARE_EQUAL(tyDesc.Class, D3D_SVC_VECTOR);
VERIFY_ARE_EQUAL(tyDesc.Type, D3D_SVT_INT);
// TODO: verify rest of type
}
// cbval3
{
ID3D12ShaderReflectionVariable *pVar = pCBReflection->GetVariableByIndex(1);
D3D12_SHADER_VARIABLE_DESC varDesc;
VERIFY_SUCCEEDED(pVar->GetDesc(&varDesc));
VERIFY_ARE_EQUAL_STR(varDesc.Name, "cbval3");
VERIFY_ARE_EQUAL(varDesc.StartOffset, 16U);
VERIFY_ARE_EQUAL(varDesc.Size, 16U);
// TODO: verify rest of variable
ID3D12ShaderReflectionType *pType = pVar->GetType();
D3D12_SHADER_TYPE_DESC tyDesc;
VERIFY_SUCCEEDED(pType->GetDesc(&tyDesc));
VERIFY_ARE_EQUAL(tyDesc.Class, D3D_SVC_VECTOR);
VERIFY_ARE_EQUAL(tyDesc.Type, D3D_SVT_INT);
// TODO: verify rest of type
}
}
static void Ref1_CheckBinding_Globals(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
std::string resName = resDesc.Name;
VERIFY_IS_TRUE(resName.compare("$Globals") == 0);
VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_CBUFFER);
// not explicitly bound:
VERIFY_ARE_EQUAL(resDesc.BindPoint, 4294967295U);
VERIFY_ARE_EQUAL(resDesc.Space, 0U);
VERIFY_ARE_EQUAL(resDesc.BindCount, 1U);
}
static void Ref1_CheckBinding_MyCB(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
std::string resName = resDesc.Name;
VERIFY_IS_TRUE(resName.compare("MyCB") == 0);
VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_CBUFFER);
VERIFY_ARE_EQUAL(resDesc.BindPoint, 11U);
VERIFY_ARE_EQUAL(resDesc.Space, 2U);
VERIFY_ARE_EQUAL(resDesc.BindCount, 1U);
}
static void Ref1_CheckBinding_tex(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
std::string resName = resDesc.Name;
VERIFY_IS_TRUE(resName.compare("tex") == 0);
VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_UAV_RWTYPED);
VERIFY_ARE_EQUAL(resDesc.BindPoint, 5U);
VERIFY_ARE_EQUAL(resDesc.Space, 0U);
VERIFY_ARE_EQUAL(resDesc.BindCount, 1U);
}
static void Ref1_CheckBinding_tex2(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
std::string resName = resDesc.Name;
VERIFY_IS_TRUE(resName.compare("tex2") == 0);
VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_TEXTURE);
VERIFY_ARE_EQUAL(resDesc.BindPoint, 0U);
VERIFY_ARE_EQUAL(resDesc.Space, 0U);
VERIFY_ARE_EQUAL(resDesc.BindCount, 1U);
}
static void Ref1_CheckBinding_samp(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
std::string resName = resDesc.Name;
VERIFY_IS_TRUE(resName.compare("samp") == 0);
VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_SAMPLER);
VERIFY_ARE_EQUAL(resDesc.BindPoint, 7U);
VERIFY_ARE_EQUAL(resDesc.Space, 0U);
VERIFY_ARE_EQUAL(resDesc.BindCount, 1U);
}
static void Ref1_CheckBinding_b_buf(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
std::string resName = resDesc.Name;
VERIFY_IS_TRUE(resName.compare("b_buf") == 0);
VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_UAV_RWBYTEADDRESS);
// not explicitly bound:
VERIFY_ARE_EQUAL(resDesc.BindPoint, 4294967295U);
VERIFY_ARE_EQUAL(resDesc.Space, 4294967295U);
VERIFY_ARE_EQUAL(resDesc.BindCount, 1U);
}
const char *Ref1_Shader =
"float cbval1;"
"cbuffer MyCB : register(b11, space2) { int4 cbval2, cbval3; }"
"RWTexture1D<int4> tex : register(u5);"
"Texture1D<float4> tex2 : register(t0);"
"SamplerState samp : register(s7);"
"RWByteAddressBuffer b_buf;"
"export float function0(min16float x) { "
" return x + cbval2.x + tex[0].x; }"
"export float function1(float x, min12int i) {"
" return x + cbval1 + b_buf.Load(x) + tex2.Sample(samp, x).x; }"
"[shader(\"vertex\")]"
"float4 function2(float4 x : POSITION) : SV_Position { return x + cbval1 + "
"cbval3.x; }";
TEST_F(DxilContainerTest, CompileWhenOkThenCheckReflection1) {
if (m_ver.SkipDxilVersion(1, 3))
return;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText(Ref1_Shader, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"", L"lib_6_3",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
CComPtr<IDxcContainerReflection> containerReflection;
uint32_t partCount;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
VERIFY_SUCCEEDED(containerReflection->Load(pProgram));
VERIFY_SUCCEEDED(containerReflection->GetPartCount(&partCount));
bool blobFound = false;
for (uint32_t i = 0; i < partCount; ++i) {
uint32_t kind;
VERIFY_SUCCEEDED(containerReflection->GetPartKind(i, &kind));
if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_DXIL) {
blobFound = true;
VERIFY_SUCCEEDED(containerReflection->GetPartReflection(
i, IID_PPV_ARGS(&pLibraryReflection)));
D3D12_LIBRARY_DESC LibDesc;
VERIFY_SUCCEEDED(pLibraryReflection->GetDesc(&LibDesc));
VERIFY_ARE_EQUAL(LibDesc.FunctionCount, 3U);
for (INT iFn = 0; iFn < (INT)LibDesc.FunctionCount; iFn++) {
ID3D12FunctionReflection *pFunctionReflection =
pLibraryReflection->GetFunctionByIndex(iFn);
D3D12_FUNCTION_DESC FnDesc;
pFunctionReflection->GetDesc(&FnDesc);
std::string Name = FnDesc.Name;
if (Name.compare("\01?function0@@YAM$min16f@@Z") == 0) {
VERIFY_ARE_EQUAL(FnDesc.Version, EncodedVersion_lib_6_3);
VERIFY_ARE_EQUAL(FnDesc.ConstantBuffers, 1U);
VERIFY_ARE_EQUAL(FnDesc.BoundResources, 2U);
D3D12_SHADER_BUFFER_DESC cbDesc;
ID3D12ShaderReflectionConstantBuffer *pCBReflection =
pFunctionReflection->GetConstantBufferByIndex(0);
VERIFY_SUCCEEDED(pCBReflection->GetDesc(&cbDesc));
std::string cbName = cbDesc.Name;
(void)(cbName);
Ref1_CheckCBuffer_MyCB(pCBReflection, cbDesc);
for (INT iRes = 0; iRes < (INT)FnDesc.BoundResources; iRes++) {
D3D12_SHADER_INPUT_BIND_DESC resDesc;
pFunctionReflection->GetResourceBindingDesc(iRes, &resDesc);
std::string resName = resDesc.Name;
if (resName.compare("$Globals") == 0) {
Ref1_CheckBinding_Globals(resDesc);
} else if (resName.compare("MyCB") == 0) {
Ref1_CheckBinding_MyCB(resDesc);
} else if (resName.compare("samp") == 0) {
Ref1_CheckBinding_samp(resDesc);
} else if (resName.compare("tex") == 0) {
Ref1_CheckBinding_tex(resDesc);
} else if (resName.compare("tex2") == 0) {
Ref1_CheckBinding_tex2(resDesc);
} else if (resName.compare("b_buf") == 0) {
Ref1_CheckBinding_b_buf(resDesc);
} else {
VERIFY_FAIL(L"Unexpected resource used");
}
}
} else if (Name.compare("\01?function1@@YAMM$min12i@@Z") == 0) {
VERIFY_ARE_EQUAL(FnDesc.Version, EncodedVersion_lib_6_3);
VERIFY_ARE_EQUAL(FnDesc.ConstantBuffers, 1U);
VERIFY_ARE_EQUAL(FnDesc.BoundResources, 4U);
D3D12_SHADER_BUFFER_DESC cbDesc;
ID3D12ShaderReflectionConstantBuffer *pCBReflection =
pFunctionReflection->GetConstantBufferByIndex(0);
VERIFY_SUCCEEDED(pCBReflection->GetDesc(&cbDesc));
std::string cbName = cbDesc.Name;
(void)(cbName);
Ref1_CheckCBuffer_Globals(pCBReflection, cbDesc);
for (INT iRes = 0; iRes < (INT)FnDesc.BoundResources; iRes++) {
D3D12_SHADER_INPUT_BIND_DESC resDesc;
pFunctionReflection->GetResourceBindingDesc(iRes, &resDesc);
std::string resName = resDesc.Name;
if (resName.compare("$Globals") == 0) {
Ref1_CheckBinding_Globals(resDesc);
} else if (resName.compare("MyCB") == 0) {
Ref1_CheckBinding_MyCB(resDesc);
} else if (resName.compare("samp") == 0) {
Ref1_CheckBinding_samp(resDesc);
} else if (resName.compare("tex") == 0) {
Ref1_CheckBinding_tex(resDesc);
} else if (resName.compare("tex2") == 0) {
Ref1_CheckBinding_tex2(resDesc);
} else if (resName.compare("b_buf") == 0) {
Ref1_CheckBinding_b_buf(resDesc);
} else {
VERIFY_FAIL(L"Unexpected resource used");
}
}
} else if (Name.compare("function2") == 0) {
// shader function with unmangled name
VERIFY_ARE_EQUAL(FnDesc.Version, EncodedVersion_vs_6_3);
VERIFY_ARE_EQUAL(FnDesc.ConstantBuffers, 2U);
VERIFY_ARE_EQUAL(FnDesc.BoundResources, 2U);
for (INT iCB = 0; iCB < (INT)FnDesc.BoundResources; iCB++) {
D3D12_SHADER_BUFFER_DESC cbDesc;
ID3D12ShaderReflectionConstantBuffer *pCBReflection =
pFunctionReflection->GetConstantBufferByIndex(0);
VERIFY_SUCCEEDED(pCBReflection->GetDesc(&cbDesc));
std::string cbName = cbDesc.Name;
if (cbName.compare("$Globals") == 0) {
Ref1_CheckCBuffer_Globals(pCBReflection, cbDesc);
} else if (cbName.compare("MyCB") == 0) {
Ref1_CheckCBuffer_MyCB(pCBReflection, cbDesc);
}
}
for (INT iRes = 0; iRes < (INT)FnDesc.BoundResources; iRes++) {
D3D12_SHADER_INPUT_BIND_DESC resDesc;
pFunctionReflection->GetResourceBindingDesc(iRes, &resDesc);
std::string resName = resDesc.Name;
if (resName.compare("$Globals") == 0) {
Ref1_CheckBinding_Globals(resDesc);
} else if (resName.compare("MyCB") == 0) {
Ref1_CheckBinding_MyCB(resDesc);
} else {
VERIFY_FAIL(L"Unexpected resource used");
}
}
} else {
VERIFY_FAIL(L"Unexpected function");
}
}
// TODO: FINISH THIS
}
}
IFTBOOLMSG(blobFound, E_FAIL, "failed to find RDAT blob after compiling");
}
TEST_F(DxilContainerTest, DxcUtils_CreateReflection) {
// Reflection stripping fails on DXIL.dll ver. < 1.5
if (m_ver.SkipDxilVersion(1, 5))
return;
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CComPtr<IDxcBlobEncoding> pSource;
CreateBlobFromText(Ref1_Shader, &pSource);
LPCWSTR options[] = {L"-Qstrip_reflect_from_dxil", L"-Qstrip_reflect"};
const UINT32 kStripFromDxilOnly =
1; // just strip reflection from DXIL, not container
const UINT32 kStripFromContainer =
2; // strip reflection from DXIL and container
auto VerifyStripReflection = [&](IDxcBlob *pBlob, bool bShouldSucceed) {
CComPtr<IDxcContainerReflection> pReflection;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&pReflection));
VERIFY_SUCCEEDED(pReflection->Load(pBlob));
UINT32 idxPart = (UINT32)-1;
if (bShouldSucceed)
VERIFY_SUCCEEDED(
pReflection->FindFirstPartKind(DXC_PART_REFLECTION_DATA, &idxPart));
else
VERIFY_FAILED(
pReflection->FindFirstPartKind(DXC_PART_REFLECTION_DATA, &idxPart));
CComPtr<IDxcContainerBuilder> pBuilder;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerBuilder, &pBuilder));
VERIFY_SUCCEEDED(pBuilder->Load(pBlob));
if (bShouldSucceed) {
VERIFY_SUCCEEDED(pBuilder->RemovePart(DXC_PART_REFLECTION_DATA));
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pBuilder->SerializeContainer(&pResult));
HRESULT hr = E_FAIL;
VERIFY_SUCCEEDED(pResult->GetStatus(&hr));
VERIFY_SUCCEEDED(hr);
CComPtr<IDxcBlob> pStrippedBlob;
pResult->GetResult(&pStrippedBlob);
CComPtr<IDxcContainerReflection> pReflection2;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&pReflection2));
VERIFY_SUCCEEDED(pReflection2->Load(pStrippedBlob));
idxPart = (UINT32)-1;
VERIFY_FAILED(
pReflection2->FindFirstPartKind(DXC_PART_REFLECTION_DATA, &idxPart));
} else {
VERIFY_FAILED(pBuilder->RemovePart(DXC_PART_REFLECTION_DATA));
}
};
{
// Test Shader path
auto VerifyCreateReflectionShader = [&](IDxcBlob *pBlob, bool bValid) {
DxcBuffer buffer = {pBlob->GetBufferPointer(), pBlob->GetBufferSize(), 0};
CComPtr<ID3D12ShaderReflection> pShaderReflection;
VERIFY_SUCCEEDED(
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pShaderReflection)));
D3D12_SHADER_DESC desc;
VERIFY_SUCCEEDED(pShaderReflection->GetDesc(&desc));
VERIFY_ARE_EQUAL(desc.Version, EncodedVersion_vs_6_3);
if (bValid) {
VERIFY_ARE_EQUAL(desc.ConstantBuffers, 2U);
VERIFY_ARE_EQUAL(desc.BoundResources, 2U);
// That should be good enough to check that IDxcUtils::CreateReflection
// worked
}
};
{
// Test Full container path
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, L"hlsl.hlsl", L"function2", L"vs_6_3", options,
kStripFromDxilOnly, nullptr, 0, nullptr, &pResult));
HRESULT hr;
VERIFY_SUCCEEDED(pResult->GetStatus(&hr));
VERIFY_SUCCEEDED(hr);
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
VerifyCreateReflectionShader(pProgram, true);
// Verify reflection stripping
VerifyStripReflection(pProgram, true);
}
{
// From New IDxcResult API
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, L"hlsl.hlsl", L"function2", L"vs_6_3", options,
kStripFromContainer, nullptr, 0, nullptr, &pResult));
HRESULT hr;
VERIFY_SUCCEEDED(pResult->GetStatus(&hr));
VERIFY_SUCCEEDED(hr);
// Test separate reflection result path
CComPtr<IDxcResult> pResultV2;
CComPtr<IDxcBlob> pReflectionPart;
VERIFY_SUCCEEDED(pResult->QueryInterface(&pResultV2));
VERIFY_SUCCEEDED(pResultV2->GetOutput(
DXC_OUT_REFLECTION, IID_PPV_ARGS(&pReflectionPart), nullptr));
VerifyCreateReflectionShader(pReflectionPart, true);
// Container should have limited reflection, and no reflection part
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
VerifyCreateReflectionShader(pProgram, false);
VerifyStripReflection(pProgram, false);
}
}
{
// Test Library path
auto VerifyCreateReflectionLibrary = [&](IDxcBlob *pBlob, bool bValid) {
DxcBuffer buffer = {pBlob->GetBufferPointer(), pBlob->GetBufferSize(), 0};
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_SUCCEEDED(
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pLibraryReflection)));
D3D12_LIBRARY_DESC desc;
VERIFY_SUCCEEDED(pLibraryReflection->GetDesc(&desc));
if (bValid) {
VERIFY_ARE_EQUAL(desc.FunctionCount, 3U);
// That should be good enough to check that IDxcUtils::CreateReflection
// worked
}
};
{
// Test Full container path
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, L"hlsl.hlsl", L"", L"lib_6_3", options, kStripFromDxilOnly,
nullptr, 0, nullptr, &pResult));
HRESULT hr;
VERIFY_SUCCEEDED(pResult->GetStatus(&hr));
VERIFY_SUCCEEDED(hr);
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
VerifyCreateReflectionLibrary(pProgram, true);
// Verify reflection stripping
VerifyStripReflection(pProgram, true);
}
{
// From New IDxcResult API
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, L"hlsl.hlsl", L"", L"lib_6_3", options, kStripFromContainer,
nullptr, 0, nullptr, &pResult));
HRESULT hr;
VERIFY_SUCCEEDED(pResult->GetStatus(&hr));
VERIFY_SUCCEEDED(hr);
// Test separate reflection result path
CComPtr<IDxcResult> pResultV2;
CComPtr<IDxcBlob> pReflectionPart;
VERIFY_SUCCEEDED(pResult->QueryInterface(&pResultV2));
VERIFY_SUCCEEDED(pResultV2->GetOutput(
DXC_OUT_REFLECTION, IID_PPV_ARGS(&pReflectionPart), nullptr));
// Test Reflection part path
VerifyCreateReflectionLibrary(pReflectionPart, true);
// Container should have limited reflection, and no reflection part
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
VerifyCreateReflectionLibrary(pProgram, false);
VerifyStripReflection(pProgram, false);
}
}
}
TEST_F(DxilContainerTest, CheckReflectionQueryInterface) {
// Minimum version 1.3 required for library support.
if (m_ver.SkipDxilVersion(1, 3))
return;
// Check that QueryInterface for shader and library reflection accepts/rejects
// interfaces properly
// Also check that DxilShaderReflection::Get*ParameterDesc methods do not
// write out-of-bounds for earlier interface version.
// Use domain shader to test DxilShaderReflection::Get*ParameterDesc because
// it can use all three signatures.
const char *shaderSource = R"(
struct PSInput {
noperspective float4 pos : SV_POSITION;
};
// Patch constant signature
struct HS_CONSTANT_DATA_OUTPUT {
float edges[3] : SV_TessFactor;
float inside : SV_InsideTessFactor;
};
// Patch input signature
struct HS_CONTROL_POINT {
float3 pos : POSITION;
};
// Domain shader
[domain("tri")]
void main(
OutputPatch<HS_CONTROL_POINT, 3> TrianglePatch,
HS_CONSTANT_DATA_OUTPUT pcIn,
float3 bary : SV_DomainLocation,
out PSInput output) {
output.pos = float4((bary.x * TrianglePatch[0].pos +
bary.y * TrianglePatch[1].pos +
bary.z * TrianglePatch[2].pos), 1);
}
)";
CComPtr<IDxcUtils> pUtils;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcUtils, &pUtils));
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
struct TestDescStruct {
D3D12_SIGNATURE_PARAMETER_DESC paramDesc;
// `pad` is used to ensure Get*ParameterDesc does not write out-of-bounds.
// It should still have the 0xFE byte pattern.
uint32_t pad;
TestDescStruct() { Clear(); }
void Clear() {
// fill this structure with 0xFE bytes
memset(this, 0xFE, sizeof(TestDescStruct));
}
bool CheckRemainingBytes(size_t offset) {
// Check that bytes in this struct after offset are still 0xFE
uint8_t *pBytes = (uint8_t *)this;
for (size_t i = offset; i < sizeof(TestDescStruct); i++) {
if (pBytes[i] != 0xFE)
return false;
}
return true;
}
bool CheckBytesAfterStream() {
// Check that bytes in this struct after Stream are still 0xFE
return CheckRemainingBytes(offsetof(TestDescStruct, paramDesc.Stream) +
sizeof(paramDesc.Stream));
}
bool CheckBytesAfterParamDesc() {
// Check that bytes in this struct after paramDesc are still 0xFE
return CheckRemainingBytes(offsetof(TestDescStruct, paramDesc) +
sizeof(paramDesc));
}
};
// ID3D12LibraryReflection
{
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcResult> pResultV2;
CComPtr<IDxcBlob> pReflectionPart;
CComPtr<IDxcBlobEncoding> pSource;
CreateBlobFromText(Ref1_Shader, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"", L"lib_6_3",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VERIFY_SUCCEEDED(pResult->QueryInterface(&pResultV2));
VERIFY_SUCCEEDED(pResultV2->GetOutput(
DXC_OUT_REFLECTION, IID_PPV_ARGS(&pReflectionPart), nullptr));
DxcBuffer buffer = {pReflectionPart->GetBufferPointer(),
pReflectionPart->GetBufferSize(), 0};
{
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_SUCCEEDED(
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pLibraryReflection)));
CComPtr<ID3D12LibraryReflection> pLibraryReflection2;
VERIFY_SUCCEEDED(pLibraryReflection->QueryInterface(
IID_PPV_ARGS(&pLibraryReflection2)));
CComPtr<IUnknown> pUnknown;
VERIFY_SUCCEEDED(
pLibraryReflection->QueryInterface(IID_PPV_ARGS(&pUnknown)));
CComPtr<ID3D12ShaderReflection> pShaderReflection;
VERIFY_FAILED(
pLibraryReflection->QueryInterface(IID_PPV_ARGS(&pShaderReflection)));
}
{ // Allow IUnknown
CComPtr<IUnknown> pUnknown;
VERIFY_SUCCEEDED(
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pUnknown)));
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_SUCCEEDED(
pUnknown->QueryInterface(IID_PPV_ARGS(&pLibraryReflection)));
}
{ // Fail to create with incorrect interface
CComPtr<ID3D12ShaderReflection> pShaderReflection;
VERIFY_ARE_EQUAL(
E_NOINTERFACE,
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pShaderReflection)));
}
}
// Supported shader reflection interfaces defined by legacy APIs
const GUID IID_ID3D11ShaderReflection_43 = {
0x0a233719,
0x3960,
0x4578,
{0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1}};
const GUID IID_ID3D11ShaderReflection_47 = {
0x8d536ca1,
0x0cca,
0x4956,
{0xa8, 0x37, 0x78, 0x69, 0x63, 0x75, 0x55, 0x84}};
// Check ShaderReflection interface versions
{
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcResult> pResultV2;
CComPtr<IDxcBlob> pReflectionPart;
CComPtr<IDxcBlobEncoding> pSource;
CreateBlobFromText(shaderSource, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
L"ds_6_0", nullptr, 0, nullptr, 0,
nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->QueryInterface(&pResultV2));
VERIFY_SUCCEEDED(pResultV2->GetOutput(
DXC_OUT_REFLECTION, IID_PPV_ARGS(&pReflectionPart), nullptr));
DxcBuffer buffer = {pReflectionPart->GetBufferPointer(),
pReflectionPart->GetBufferSize(), 0};
// The interface version supported for QI should only be the one used for
// creating the original reflection interface.
{ // Verify with initial interface ID3D12ShaderReflection
CComPtr<ID3D12ShaderReflection> pShaderReflection;
VERIFY_SUCCEEDED(
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pShaderReflection)));
// Verify QI for same interface and IUnknown succeeds:
CComPtr<ID3D12ShaderReflection> pShaderReflection2;
VERIFY_SUCCEEDED(
pShaderReflection->QueryInterface(IID_PPV_ARGS(&pShaderReflection2)));
CComPtr<IUnknown> pUnknown;
VERIFY_SUCCEEDED(
pShaderReflection->QueryInterface(IID_PPV_ARGS(&pUnknown)));
// Verify QI for wrong version of interface fails:
CComPtr<ID3D12ShaderReflection> pShaderReflection43;
VERIFY_FAILED(pShaderReflection->QueryInterface(
IID_ID3D11ShaderReflection_43, (void **)&pShaderReflection43));
CComPtr<ID3D12ShaderReflection> pShaderReflection47;
VERIFY_FAILED(pShaderReflection->QueryInterface(
IID_ID3D11ShaderReflection_47, (void **)&pShaderReflection47));
// Verify QI for wrong interface fails:
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_FAILED(
pShaderReflection->QueryInterface(IID_PPV_ARGS(&pLibraryReflection)));
// Verify Get*ParameterDesc methods do not write out-of-bounds
TestDescStruct testParamDesc;
VERIFY_SUCCEEDED(pShaderReflection->GetInputParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterParamDesc());
VERIFY_SUCCEEDED(pShaderReflection->GetOutputParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterParamDesc());
VERIFY_SUCCEEDED(pShaderReflection->GetPatchConstantParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterParamDesc());
}
{ // Verify with initial interface IID_ID3D11ShaderReflection_47
CComPtr<ID3D12ShaderReflection> pShaderReflection;
VERIFY_SUCCEEDED(pUtils->CreateReflection(
&buffer, IID_ID3D11ShaderReflection_47, (void **)&pShaderReflection));
// Verify QI for same interface and IUnknown succeeds:
CComPtr<ID3D12ShaderReflection> pShaderReflection2;
VERIFY_SUCCEEDED(pShaderReflection->QueryInterface(
IID_ID3D11ShaderReflection_47, (void **)&pShaderReflection2));
CComPtr<IUnknown> pUnknown;
VERIFY_SUCCEEDED(
pShaderReflection->QueryInterface(IID_PPV_ARGS(&pUnknown)));
// Verify QI for wrong version of interface fails:
CComPtr<ID3D12ShaderReflection> pShaderReflection43;
VERIFY_FAILED(pShaderReflection->QueryInterface(
IID_ID3D11ShaderReflection_43, (void **)&pShaderReflection43));
CComPtr<ID3D12ShaderReflection> pShaderReflection12;
VERIFY_FAILED(pShaderReflection->QueryInterface(
IID_PPV_ARGS(&pShaderReflection12)));
// Verify QI for wrong interface fails:
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_FAILED(
pShaderReflection->QueryInterface(IID_PPV_ARGS(&pLibraryReflection)));
// Verify Get*ParameterDesc methods do not write out-of-bounds
TestDescStruct testParamDesc;
VERIFY_SUCCEEDED(pShaderReflection->GetInputParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterParamDesc());
VERIFY_SUCCEEDED(pShaderReflection->GetOutputParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterParamDesc());
VERIFY_SUCCEEDED(pShaderReflection->GetPatchConstantParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterParamDesc());
}
{ // Verify with initial interface IID_ID3D11ShaderReflection_43
CComPtr<ID3D12ShaderReflection> pShaderReflection;
VERIFY_SUCCEEDED(pUtils->CreateReflection(
&buffer, IID_ID3D11ShaderReflection_43, (void **)&pShaderReflection));
// Verify QI for same interface and IUnknown succeeds:
CComPtr<ID3D12ShaderReflection> pShaderReflection2;
VERIFY_SUCCEEDED(pShaderReflection->QueryInterface(
IID_ID3D11ShaderReflection_43, (void **)&pShaderReflection2));
CComPtr<IUnknown> pUnknown;
VERIFY_SUCCEEDED(
pShaderReflection->QueryInterface(IID_PPV_ARGS(&pUnknown)));
// Verify QI for wrong version of interface fails:
CComPtr<ID3D12ShaderReflection> pShaderReflection47;
VERIFY_FAILED(pShaderReflection->QueryInterface(
IID_ID3D11ShaderReflection_47, (void **)&pShaderReflection47));
CComPtr<ID3D12ShaderReflection> pShaderReflection12;
VERIFY_FAILED(pShaderReflection->QueryInterface(
IID_PPV_ARGS(&pShaderReflection12)));
// Verify QI for wrong interface fails:
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_FAILED(
pShaderReflection->QueryInterface(IID_PPV_ARGS(&pLibraryReflection)));
// Verify Get*ParameterDesc methods do not write out-of-bounds
// IID_ID3D11ShaderReflection_43 version of the structure does not have
// any feilds after Stream
TestDescStruct testParamDesc;
VERIFY_SUCCEEDED(pShaderReflection->GetInputParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterStream());
VERIFY_SUCCEEDED(pShaderReflection->GetOutputParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterStream());
VERIFY_SUCCEEDED(pShaderReflection->GetPatchConstantParameterDesc(
0, &testParamDesc.paramDesc));
VERIFY_IS_TRUE(testParamDesc.CheckBytesAfterStream());
}
{ // Allow IUnknown for latest interface version
CComPtr<IUnknown> pUnknown;
VERIFY_SUCCEEDED(
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pUnknown)));
CComPtr<ID3D12ShaderReflection> pShaderReflection;
VERIFY_SUCCEEDED(
pUnknown->QueryInterface(IID_PPV_ARGS(&pShaderReflection)));
}
{ // Fail to create with incorrect interface
CComPtr<ID3D12LibraryReflection> pLibraryReflection;
VERIFY_ARE_EQUAL(
E_NOINTERFACE,
pUtils->CreateReflection(&buffer, IID_PPV_ARGS(&pLibraryReflection)));
}
}
}
TEST_F(DxilContainerTest, CompileWhenOKThenIncludesFeatureInfo) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
hlsl::DxilContainerHeader *pHeader;
hlsl::DxilPartIterator pPartIter(nullptr, 0);
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Now mess with the program bitcode.
pHeader = (hlsl::DxilContainerHeader *)pProgram->GetBufferPointer();
pPartIter = std::find_if(hlsl::begin(pHeader), hlsl::end(pHeader),
hlsl::DxilPartIsType(hlsl::DFCC_FeatureInfo));
VERIFY_ARE_NOT_EQUAL(hlsl::end(pHeader), pPartIter);
VERIFY_ARE_EQUAL(sizeof(uint64_t), (*pPartIter)->PartSize);
VERIFY_ARE_EQUAL(0U, *(const uint64_t *)hlsl::GetDxilPartData(*pPartIter));
}
TEST_F(DxilContainerTest, DisassemblyWhenBCInvalidThenFails) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
hlsl::DxilContainerHeader *pHeader;
hlsl::DxilPartHeader *pPart;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Now mess with the program bitcode.
pHeader = (hlsl::DxilContainerHeader *)pProgram->GetBufferPointer();
pPart = const_cast<hlsl::DxilPartHeader *>(
*std::find_if(hlsl::begin(pHeader), hlsl::end(pHeader),
hlsl::DxilPartIsType(hlsl::DFCC_DXIL)));
strcpy_s(hlsl::GetDxilPartData(pPart), pPart->PartSize, "corruption");
VERIFY_FAILED(pCompiler->Disassemble(pProgram, &pDisassembly));
}
TEST_F(DxilContainerTest, DisassemblyWhenMissingThenFails) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlobEncoding> pDisassembly;
hlsl::DxilContainerHeader header;
SetupBasicHeader(&header);
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobPinned(&header, header.ContainerSizeInBytes, 0, &pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
TEST_F(DxilContainerTest, DisassemblyWhenInvalidThenFails) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pDisassembly;
uint8_t scratch[1024];
hlsl::DxilContainerHeader *pHeader = (hlsl::DxilContainerHeader *)scratch;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
// Too small to contain header.
{
CComPtr<IDxcBlobEncoding> pSource;
SetupBasicHeader(pHeader);
CreateBlobPinned(pHeader, sizeof(hlsl::DxilContainerHeader) - 4, 0,
&pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
// Wrong major version.
{
CComPtr<IDxcBlobEncoding> pSource;
SetupBasicHeader(pHeader);
pHeader->Version.Major = 100;
CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, 0, &pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
// Size out of bounds.
{
CComPtr<IDxcBlobEncoding> pSource;
SetupBasicHeader(pHeader);
pHeader->ContainerSizeInBytes = 1024;
CreateBlobPinned(pHeader, sizeof(hlsl::DxilContainerHeader), 0, &pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
// Size too large as per spec limit.
{
CComPtr<IDxcBlobEncoding> pSource;
SetupBasicHeader(pHeader);
pHeader->ContainerSizeInBytes = hlsl::DxilContainerMaxSize + 1;
CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, 0, &pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
// Not large enough to hold offset table.
{
CComPtr<IDxcBlobEncoding> pSource;
SetupBasicHeader(pHeader);
pHeader->PartCount = 1;
CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, 0, &pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
// Part offset out of bounds.
{
CComPtr<IDxcBlobEncoding> pSource;
SetupBasicHeader(pHeader);
pHeader->PartCount = 1;
*((uint32_t *)(pHeader + 1)) = 1024;
pHeader->ContainerSizeInBytes += sizeof(uint32_t);
CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, 0, &pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
// Part size out of bounds.
{
CComPtr<IDxcBlobEncoding> pSource;
SetupBasicHeader(pHeader);
pHeader->PartCount = 1;
*((uint32_t *)(pHeader + 1)) = sizeof(*pHeader) + sizeof(uint32_t);
pHeader->ContainerSizeInBytes += sizeof(uint32_t);
hlsl::GetDxilContainerPart(pHeader, 0)->PartSize = 1024;
pHeader->ContainerSizeInBytes += sizeof(hlsl::DxilPartHeader);
CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, 0, &pSource);
VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
}
}
TEST_F(DxilContainerTest, DisassemblyWhenValidThenOK) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
hlsl::DxilContainerHeader header;
SetupBasicHeader(&header);
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembly));
std::string disassembleString(BlobToUtf8(pDisassembly));
VERIFY_ARE_NOT_EQUAL(0U, disassembleString.size());
}
class HlslFileVariables {
private:
std::wstring m_Entry;
std::wstring m_Mode;
std::wstring m_Target;
std::vector<std::wstring> m_Arguments;
std::vector<LPCWSTR> m_ArgumentPtrs;
public:
HlslFileVariables(HlslFileVariables &other) = delete;
const LPCWSTR *GetArguments() const { return m_ArgumentPtrs.data(); }
UINT32 GetArgumentCount() const { return m_ArgumentPtrs.size(); }
LPCWSTR GetEntry() const { return m_Entry.c_str(); }
LPCWSTR GetMode() const { return m_Mode.c_str(); }
LPCWSTR GetTarget() const { return m_Target.c_str(); }
void Reset();
HRESULT SetFromText(const char *pText, size_t len);
};
void HlslFileVariables::Reset() {
m_Entry.resize(0);
m_Mode.resize(0);
m_Target.resize(0);
m_Arguments.resize(0);
m_ArgumentPtrs.resize(0);
}
#include <codecvt>
static bool wcsneq(const wchar_t *pValue, const wchar_t *pCheck) {
return 0 == wcsncmp(pValue, pCheck, wcslen(pCheck));
}
HRESULT HlslFileVariables::SetFromText(const char *pText, size_t len) {
// Look for the line of interest.
const char *pEnd = pText + len;
const char *pLineEnd = pText;
while (pLineEnd < pEnd && *pLineEnd != '\n')
pLineEnd++;
// Create a wide char backing store.
auto state = std::mbstate_t();
size_t size = std::mbsrtowcs(nullptr, &pText, 0, &state);
if (size == static_cast<size_t>(-1))
return E_INVALIDARG;
std::unique_ptr<wchar_t[]> pWText(new wchar_t[size + 1]);
std::mbsrtowcs(pWText.get(), &pText, size + 1, &state);
// Find starting and ending '-*-' delimiters.
const wchar_t *pVarStart = wcsstr(pWText.get(), L"-*-");
if (!pVarStart)
return E_INVALIDARG;
pVarStart += 3;
const wchar_t *pVarEnd = wcsstr(pVarStart, L"-*-");
if (!pVarEnd)
return E_INVALIDARG;
for (;;) {
// Find 'name' ':' 'value' ';'
const wchar_t *pVarNameStart = pVarStart;
while (pVarNameStart < pVarEnd && L' ' == *pVarNameStart)
++pVarNameStart;
if (pVarNameStart == pVarEnd)
break;
const wchar_t *pVarValDelim = pVarNameStart;
while (pVarValDelim < pVarEnd && L':' != *pVarValDelim)
++pVarValDelim;
if (pVarValDelim == pVarEnd)
break;
const wchar_t *pVarValStart = pVarValDelim + 1;
while (pVarValStart < pVarEnd && L' ' == *pVarValStart)
++pVarValStart;
if (pVarValStart == pVarEnd)
break;
const wchar_t *pVarValEnd = pVarValStart;
while (pVarValEnd < pVarEnd && L';' != *pVarValEnd)
++pVarValEnd;
if (wcsneq(pVarNameStart, L"mode")) {
m_Mode.assign(pVarValStart, pVarValEnd - pVarValStart - 1);
} else if (wcsneq(pVarNameStart, L"hlsl-entry")) {
m_Entry.assign(pVarValStart, pVarValEnd - pVarValStart - 1);
} else if (wcsneq(pVarNameStart, L"hlsl-target")) {
m_Target.assign(pVarValStart, pVarValEnd - pVarValStart - 1);
} else if (wcsneq(pVarNameStart, L"hlsl-args")) {
// skip for now
}
}
return S_OK;
}
#ifdef _WIN32 // DXBC unsupported
TEST_F(DxilContainerTest, ReflectionMatchesDXBC_CheckIn) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
ReflectionTest(hlsl_test::GetPathToHlslDataFile(
L"..\\CodeGenHLSL\\container\\SimpleBezier11DS.hlsl")
.c_str(),
false);
ReflectionTest(hlsl_test::GetPathToHlslDataFile(
L"..\\CodeGenHLSL\\container\\SubD11_SmoothPS.hlsl")
.c_str(),
false);
ReflectionTest(
hlsl_test::GetPathToHlslDataFile(
L"..\\HLSLFileCheck\\d3dreflect\\structured_buffer_layout.hlsl")
.c_str(),
false);
ReflectionTest(hlsl_test::GetPathToHlslDataFile(
L"..\\HLSLFileCheck\\d3dreflect\\cb_sizes.hlsl")
.c_str(),
false);
ReflectionTest(hlsl_test::GetPathToHlslDataFile(
L"..\\HLSLFileCheck\\d3dreflect\\tbuffer.hlsl")
.c_str(),
false, D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY);
ReflectionTest(hlsl_test::GetPathToHlslDataFile(
L"..\\HLSLFileCheck\\d3dreflect\\texture2dms.hlsl")
.c_str(),
false);
ReflectionTest(
hlsl_test::GetPathToHlslDataFile(
L"..\\HLSLFileCheck\\hlsl\\objects\\StructuredBuffer\\layout.hlsl")
.c_str(),
false);
}
TEST_F(DxilContainerTest, ReflectionMatchesDXBC_Full) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
std::wstring codeGenPath =
hlsl_test::GetPathToHlslDataFile(L"..\\CodeGenHLSL\\Samples");
// This test was running at about three minutes; that can be enabled with
// TestAll=True, otherwise the much shorter list is used.
const bool TestAll = false;
LPCWSTR PreApprovedPaths[] = {
L"2DQuadShaders_VS.hlsl", L"BC6HEncode_TryModeLE10CS.hlsl",
L"DepthViewerVS.hlsl", L"DetailTessellation11_DS.hlsl",
L"GenerateHistogramCS.hlsl", L"OIT_PS.hlsl",
L"PNTriangles11_DS.hlsl", L"PerfGraphPS.hlsl",
L"PerfGraphVS.hlsl", L"ScreenQuadVS.hlsl",
L"SimpleBezier11HS.hlsl"};
// These tests should always be skipped
LPCWSTR SkipPaths[] = {L".hlsli", L"TessellatorCS40_defines.h",
L"SubD11_SubDToBezierHS",
L"ParticleTileCullingCS_fail_unroll.hlsl"};
for (auto &p : recursive_directory_iterator(path(codeGenPath))) {
if (is_regular_file(p)) {
LPCWSTR fullPath = p.path().c_str();
auto Matches = [&](LPCWSTR candidate) {
LPCWSTR match = wcsstr(fullPath, candidate);
return nullptr != match;
};
// Skip failed tests.
LPCWSTR *SkipEnd = SkipPaths + _countof(SkipPaths);
if (SkipEnd != std::find_if(SkipPaths, SkipEnd, Matches))
continue;
if (!TestAll) {
bool shouldTest = false;
LPCWSTR *PreApprovedEnd = PreApprovedPaths + _countof(PreApprovedPaths);
shouldTest = PreApprovedEnd !=
std::find_if(PreApprovedPaths, PreApprovedEnd, Matches);
if (!shouldTest) {
continue;
}
}
auto start = std::chrono::system_clock::now();
ReflectionTest(fullPath, true);
if (TestAll) {
// If testing all cases, print out their timing.
auto end = std::chrono::system_clock::now();
auto dur =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
LogCommentFmt(L"%s,%u", fullPath, (unsigned)dur.count());
}
}
}
}
#endif // _WIN32 - DXBC unsupported
TEST_F(DxilContainerTest, ValidateFromLL_Abs2) {
CodeGenTestCheck(L"..\\CodeGenHLSL\\container\\abs2_m.ll");
}
// Test to see if the Compiler Version (VERS) part gets added to library shaders
// with validator version >= 1.8
TEST_F(DxilContainerTest, DxilContainerCompilerVersionTest) {
if (m_ver.SkipDxilVersion(1, 8))
return;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("export float4 main() : SV_Target { return 0; }",
&pSource);
// Test DxilContainer with ShaderDebugInfoDXIL
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
L"lib_6_3", nullptr, 0, nullptr, 0,
nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
const hlsl::DxilContainerHeader *pHeader = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_IS_TRUE(
hlsl::IsValidDxilContainer(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::IsDxilContainerLike(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_CompilerVersion));
pResult.Release();
pProgram.Release();
// Test DxilContainer without ShaderDebugInfoDXIL
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
L"lib_6_8", nullptr, 0, nullptr, 0,
nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
pHeader = hlsl::IsDxilContainerLike(pProgram->GetBufferPointer(),
pProgram->GetBufferSize());
VERIFY_IS_TRUE(
hlsl::IsValidDxilContainer(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::IsDxilContainerLike(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_CompilerVersion));
const hlsl::DxilPartHeader *pVersionHeader =
hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_CompilerVersion);
// ensure the version info has the expected contents by
// querying IDxcVersion interface from pCompiler and comparing
// against the contents inside of pProgram
// Gather "true" information
CComPtr<IDxcVersionInfo> pVersionInfo;
CComPtr<IDxcVersionInfo2> pVersionInfo2;
CComPtr<IDxcVersionInfo3> pVersionInfo3;
pCompiler.QueryInterface(&pVersionInfo);
UINT major;
UINT minor;
UINT flags;
UINT commit_count;
CComHeapPtr<char> pCommitHashRef;
CComHeapPtr<char> pCustomVersionStrRef;
VERIFY_SUCCEEDED(pVersionInfo->GetVersion(&major, &minor));
VERIFY_SUCCEEDED(pVersionInfo->GetFlags(&flags));
VERIFY_SUCCEEDED(pCompiler.QueryInterface(&pVersionInfo2));
VERIFY_SUCCEEDED(
pVersionInfo2->GetCommitInfo(&commit_count, &pCommitHashRef));
VERIFY_SUCCEEDED(pCompiler.QueryInterface(&pVersionInfo3));
VERIFY_SUCCEEDED(
pVersionInfo3->GetCustomVersionString(&pCustomVersionStrRef));
// test the "true" information against what's in the blob
VERIFY_IS_TRUE(pVersionHeader->PartFourCC ==
hlsl::DxilFourCC::DFCC_CompilerVersion);
// test the rest of the contents (major, minor, etc.)
CComPtr<IDxcContainerReflection> containerReflection;
uint32_t partCount;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
IFT(containerReflection->Load(pProgram));
IFT(containerReflection->GetPartCount(&partCount));
UINT part_index;
VERIFY_SUCCEEDED(containerReflection->FindFirstPartKind(
hlsl::DFCC_CompilerVersion, &part_index));
CComPtr<IDxcBlob> pBlob;
IFT(containerReflection->GetPartContent(part_index, &pBlob));
void *pBlobPtr = pBlob->GetBufferPointer();
hlsl::DxilCompilerVersion *pDCV = (hlsl::DxilCompilerVersion *)pBlobPtr;
VERIFY_ARE_EQUAL(major, pDCV->Major);
VERIFY_ARE_EQUAL(minor, pDCV->Minor);
VERIFY_ARE_EQUAL(flags, pDCV->VersionFlags);
VERIFY_ARE_EQUAL(commit_count, pDCV->CommitCount);
if (pDCV->VersionStringListSizeInBytes != 0) {
LPCSTR pCommitHashStr = (LPCSTR)pDCV + sizeof(hlsl::DxilCompilerVersion);
uint32_t uCommitHashLen = (uint32_t)strlen(pCommitHashStr);
VERIFY_ARE_EQUAL_STR(pCommitHashStr, pCommitHashRef);
// + 2 for the two null terminators that are included in this size:
if (pDCV->VersionStringListSizeInBytes > uCommitHashLen + 2) {
LPCSTR pCustomVersionString = pCommitHashStr + uCommitHashLen + 1;
VERIFY_ARE_EQUAL_STR(pCustomVersionString, pCustomVersionStrRef)
}
}
}
TEST_F(DxilContainerTest, DxilContainerUnitTest) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlobEncoding> pDisassembly;
CComPtr<IDxcOperationResult> pResult;
std::vector<LPCWSTR> arguments;
arguments.emplace_back(L"/Zi");
arguments.emplace_back(L"/Qembed_debug");
VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
// Test DxilContainer with ShaderDebugInfoDXIL
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
arguments.data(), arguments.size(),
nullptr, 0, nullptr, &pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
const hlsl::DxilContainerHeader *pHeader = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_IS_TRUE(
hlsl::IsValidDxilContainer(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::IsDxilContainerLike(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::GetDxilProgramHeader(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
VERIFY_IS_NOT_NULL(hlsl::GetDxilProgramHeader(
pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
VERIFY_IS_NOT_NULL(
hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
VERIFY_IS_NOT_NULL(hlsl::GetDxilPartByType(
pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
pResult.Release();
pProgram.Release();
// Test DxilContainer without ShaderDebugInfoDXIL
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
pHeader = hlsl::IsDxilContainerLike(pProgram->GetBufferPointer(),
pProgram->GetBufferSize());
VERIFY_IS_TRUE(
hlsl::IsValidDxilContainer(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::IsDxilContainerLike(pHeader, pProgram->GetBufferSize()));
VERIFY_IS_NOT_NULL(
hlsl::GetDxilProgramHeader(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
VERIFY_IS_NULL(hlsl::GetDxilProgramHeader(
pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
VERIFY_IS_NOT_NULL(
hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
VERIFY_IS_NULL(hlsl::GetDxilPartByType(
pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
// Test Empty DxilContainer
hlsl::DxilContainerHeader header;
SetupBasicHeader(&header);
VERIFY_IS_TRUE(
hlsl::IsValidDxilContainer(&header, header.ContainerSizeInBytes));
VERIFY_IS_NOT_NULL(
hlsl::IsDxilContainerLike(&header, header.ContainerSizeInBytes));
VERIFY_IS_NULL(
hlsl::GetDxilProgramHeader(&header, hlsl::DxilFourCC::DFCC_DXIL));
VERIFY_IS_NULL(hlsl::GetDxilPartByType(&header, hlsl::DxilFourCC::DFCC_DXIL));
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/TestMain.cpp
|
//===--- utils/unittest/HLSL/TestMain.cpp - unittest driver --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "llvm/Support/Signals.h"
#include "HLSLTestOptions.h"
#include "dxc/Test/WEXAdapter.h"
#if defined(_WIN32)
#include <windows.h>
#if defined(_MSC_VER)
#include <crtdbg.h>
#endif
#endif
namespace {
using namespace ::testing;
/// A GoogleTest event printer that only prints test failures.
class FailurePrinter : public TestEventListener {
public:
explicit FailurePrinter(TestEventListener *listener)
: defaultListener(listener) {}
~FailurePrinter() override { delete defaultListener; }
void OnTestProgramStart(const UnitTest &ut) override {
defaultListener->OnTestProgramStart(ut);
}
void OnTestIterationStart(const UnitTest &ut, int iteration) override {
defaultListener->OnTestIterationStart(ut, iteration);
}
void OnEnvironmentsSetUpStart(const UnitTest &ut) override {
defaultListener->OnEnvironmentsSetUpStart(ut);
}
void OnEnvironmentsSetUpEnd(const UnitTest &ut) override {
defaultListener->OnEnvironmentsSetUpEnd(ut);
}
void OnTestCaseStart(const TestCase &tc) override {
defaultListener->OnTestCaseStart(tc);
}
void OnTestStart(const TestInfo &ti) override {
// Do not output on test start
// defaultListener->OnTestStart(ti);
}
void OnTestPartResult(const TestPartResult &result) override {
defaultListener->OnTestPartResult(result);
}
void OnTestEnd(const TestInfo &ti) override {
// Only output if failure on test end
if (ti.result()->Failed())
defaultListener->OnTestEnd(ti);
}
void OnTestCaseEnd(const TestCase &tc) override {
defaultListener->OnTestCaseEnd(tc);
}
void OnEnvironmentsTearDownStart(const UnitTest &ut) override {
defaultListener->OnEnvironmentsTearDownStart(ut);
}
void OnEnvironmentsTearDownEnd(const UnitTest &ut) override {
defaultListener->OnEnvironmentsTearDownEnd(ut);
}
void OnTestIterationEnd(const UnitTest &ut, int iteration) override {
defaultListener->OnTestIterationEnd(ut, iteration);
}
void OnTestProgramEnd(const UnitTest &ut) override {
defaultListener->OnTestProgramEnd(ut);
}
private:
TestEventListener *defaultListener;
};
} // namespace
const char *TestMainArgv0;
#define SAVE_ARG(argname) \
if (std::string("--" #argname) == argv[i]) { \
if (i + 1 < argc) { \
clang::hlsl::testOptions::argname = argv[++i]; \
} else { \
fprintf(stderr, "Error: --" #argname " requires an argument\n"); \
return 1; \
} \
}
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal(true /* Disable crash reporting */);
for (int i = 1; i < argc; ++i) {
ARG_LIST(SAVE_ARG)
}
// Initialize both gmock and gtest.
testing::InitGoogleMock(&argc, argv);
// Switch event listener to one that only prints failures.
testing::TestEventListeners &listeners =
::testing::UnitTest::GetInstance()->listeners();
auto *defaultPrinter = listeners.Release(listeners.default_result_printer());
// Google Test takes the ownership.
listeners.Append(new FailurePrinter(defaultPrinter));
// Make it easy for a test to re-execute itself by saving argv[0].
TestMainArgv0 = argv[0];
#if defined(_WIN32)
// Disable all of the possible ways Windows conspires to make automated
// testing impossible.
::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#if defined(_MSC_VER)
::_set_error_mode(_OUT_TO_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#endif
#endif
moduleSetup();
int rv = RUN_ALL_TESTS();
moduleTeardown();
return rv;
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/DXIsenseTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// DXIsenseTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for the dxcompiler Intellisense API. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/CompilationResult.h"
#include "dxc/Test/HLSLTestData.h"
#include <stdint.h>
#include "dxc/Support/microcom.h"
#include "dxc/Test/HlslTestUtils.h"
#ifdef _WIN32
class DXIntellisenseTest {
#else
class DXIntellisenseTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(DXIntellisenseTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
protected:
TEST_CLASS_SETUP(DXIntellisenseTestClassSetup)
TEST_CLASS_CLEANUP(DXIntellisenseTestClassCleanup)
void GetLocationAt(IDxcTranslationUnit *TU, unsigned line, unsigned col,
IDxcSourceLocation **pResult) {
CComPtr<IDxcFile> file;
VERIFY_SUCCEEDED(TU->GetFile("filename.hlsl", &file));
VERIFY_SUCCEEDED(TU->GetLocation(file, line, col, pResult));
}
void GetCursorAt(IDxcTranslationUnit *TU, unsigned line, unsigned col,
IDxcCursor **pResult) {
CComPtr<IDxcSourceLocation> location;
GetLocationAt(TU, line, col, &location);
VERIFY_SUCCEEDED(TU->GetCursorForLocation(location, pResult));
}
void ExpectCursorAt(IDxcTranslationUnit *TU, unsigned line, unsigned col,
DxcCursorKind expectedKind,
IDxcCursor **pResult = nullptr) {
CComPtr<IDxcCursor> cursor;
DxcCursorKind actualKind;
GetCursorAt(TU, line, col, &cursor);
VERIFY_SUCCEEDED(cursor->GetKind(&actualKind));
EXPECT_EQ(expectedKind,
actualKind); // << " for cursor at " << line << ":" << col;
if (pResult != nullptr) {
*pResult = cursor.Detach();
}
}
void ExpectQualifiedName(IDxcTranslationUnit *TU, unsigned line, unsigned col,
const wchar_t *expectedName) {
CComPtr<IDxcCursor> cursor;
CComBSTR name;
GetCursorAt(TU, line, col, &cursor);
ASSERT_HRESULT_SUCCEEDED(cursor->GetQualifiedName(FALSE, &name));
EXPECT_STREQW(expectedName,
name); // << "qualified name at " << line << ":" << col;
}
void ExpectDeclarationText(IDxcTranslationUnit *TU, unsigned line,
unsigned col, const wchar_t *expectedDecl) {
CComPtr<IDxcCursor> cursor;
CComBSTR name;
GetCursorAt(TU, line, col, &cursor);
DxcCursorFormatting formatting =
(DxcCursorFormatting)(DxcCursorFormatting_IncludeNamespaceKeyword);
ASSERT_HRESULT_SUCCEEDED(cursor->GetFormattedName(formatting, &name));
EXPECT_STREQW(expectedDecl,
name); // << "declaration text at " << line << ":" << col;
}
TEST_METHOD(CursorWhenCBufferRefThenFound)
TEST_METHOD(CursorWhenPresumedLocationDifferentFromSpellingLocation)
TEST_METHOD(CursorWhenPresumedLocationSameAsSpellingLocation)
TEST_METHOD(CursorWhenFieldRefThenSimpleNames)
TEST_METHOD(CursorWhenFindAtBodyCallThenMatch)
TEST_METHOD(CursorWhenFindAtGlobalThenMatch)
TEST_METHOD(CursorWhenFindBeforeBodyCallThenMatch)
TEST_METHOD(CursorWhenFindBeforeGlobalThenMatch)
TEST_METHOD(CursorWhenFunctionThenParamsAvailable)
TEST_METHOD(CursorWhenFunctionThenReturnTypeAvailable)
TEST_METHOD(CursorWhenFunctionThenSignatureAvailable)
TEST_METHOD(CursorWhenGlobalVariableThenSimpleNames)
TEST_METHOD(CursorWhenOverloadedIncompleteThenInvisible)
TEST_METHOD(CursorWhenOverloadedResolvedThenDirectSymbol)
TEST_METHOD(CursorWhenReferenceThenDefinitionAvailable)
TEST_METHOD(CursorWhenTypeOfVariableDeclThenNamesHaveType)
TEST_METHOD(CursorTypeUsedNamespace)
TEST_METHOD(CursorWhenVariableRefThenSimpleNames)
TEST_METHOD(CursorWhenVariableUsedThenDeclarationAvailable)
TEST_METHOD(FileWhenSameThenEqual)
TEST_METHOD(FileWhenNotSameThenNotEqual)
TEST_METHOD(InclusionWhenMissingThenError)
TEST_METHOD(InclusionWhenValidThenAvailable)
TEST_METHOD(TUWhenGetFileMissingThenFail)
TEST_METHOD(TUWhenGetFilePresentThenOK)
TEST_METHOD(TUWhenEmptyStructThenErrorIfISense)
TEST_METHOD(TUWhenRegionInactiveMissingThenCountIsZero)
TEST_METHOD(TUWhenRegionInactiveThenEndIsBeforeElseHash)
TEST_METHOD(TUWhenRegionInactiveThenEndIsBeforeEndifHash)
TEST_METHOD(TUWhenRegionInactiveThenStartIsAtIfdefEol)
TEST_METHOD(TUWhenUnsaveFileThenOK)
TEST_METHOD(QualifiedNameClass)
TEST_METHOD(QualifiedNameVariable)
TEST_METHOD(TypeWhenICEThenEval)
TEST_METHOD(CompletionWhenResultsAvailable)
};
bool DXIntellisenseTest::DXIntellisenseTestClassSetup() {
std::shared_ptr<HlslIntellisenseSupport> result =
std::make_shared<HlslIntellisenseSupport>();
if (FAILED(result->Initialize()))
return false;
CompilationResult::DefaultHlslSupport = result;
return true;
}
bool DXIntellisenseTest::DXIntellisenseTestClassCleanup() {
CompilationResult::DefaultHlslSupport = nullptr;
return true;
}
TEST_F(DXIntellisenseTest, CursorWhenCBufferRefThenFound) {
char program[] = "cbuffer MyBuffer {\r\n"
" int a; }\r\n"
"int main() { return\r\n"
"a; }";
CComPtr<IDxcCursor> varRefCursor;
CComPtr<IDxcFile> file;
CComInterfaceArray<IDxcCursor> refs;
CComPtr<IDxcSourceLocation> loc;
unsigned line;
CompilationResult c(
CompilationResult::CreateForProgram(program, strlen(program)));
VERIFY_IS_TRUE(c.ParseSucceeded());
ExpectCursorAt(c.TU, 4, 1, DxcCursor_DeclRefExpr, &varRefCursor);
VERIFY_SUCCEEDED(
c.TU->GetFile(CompilationResult::getDefaultFileName(), &file));
VERIFY_SUCCEEDED(varRefCursor->FindReferencesInFile(
file, 0, 4, refs.size_ref(), refs.data_ref()));
VERIFY_ARE_EQUAL(2U, refs.size());
VERIFY_SUCCEEDED(refs.begin()[0]->GetLocation(&loc));
VERIFY_SUCCEEDED(loc->GetSpellingLocation(nullptr, &line, nullptr, nullptr));
VERIFY_ARE_EQUAL(2U, line);
}
TEST_F(DXIntellisenseTest,
CursorWhenPresumedLocationDifferentFromSpellingLocation) {
char program[] = "#line 21 \"something.h\"\r\n"
"struct MyStruct { };";
CComPtr<IDxcCursor> varCursor;
CComPtr<IDxcSourceLocation> loc;
CComPtr<IDxcFile> spellingFile;
unsigned spellingLine, spellingCol, spellingOffset;
CComHeapPtr<char> presumedFilename;
unsigned presumedLine, presumedCol;
CompilationResult c(
CompilationResult::CreateForProgram(program, strlen(program)));
VERIFY_IS_TRUE(c.ParseSucceeded());
ExpectCursorAt(c.TU, 2, 1, DxcCursor_StructDecl, &varCursor);
VERIFY_SUCCEEDED(varCursor->GetLocation(&loc));
VERIFY_SUCCEEDED(loc->GetSpellingLocation(&spellingFile, &spellingLine,
&spellingCol, &spellingOffset));
VERIFY_ARE_EQUAL(2u, spellingLine);
VERIFY_ARE_EQUAL(8u, spellingCol);
VERIFY_ARE_EQUAL(31u, spellingOffset);
VERIFY_SUCCEEDED(
loc->GetPresumedLocation(&presumedFilename, &presumedLine, &presumedCol));
VERIFY_ARE_EQUAL_STR("something.h", presumedFilename);
VERIFY_ARE_EQUAL(21u, presumedLine);
VERIFY_ARE_EQUAL(8u, presumedCol);
}
TEST_F(DXIntellisenseTest, CursorWhenPresumedLocationSameAsSpellingLocation) {
char program[] = "struct MyStruct { };";
CComPtr<IDxcCursor> varCursor;
CComPtr<IDxcSourceLocation> loc;
CComPtr<IDxcFile> spellingFile;
unsigned spellingLine, spellingCol, spellingOffset;
CComHeapPtr<char> presumedFilename;
unsigned presumedLine, presumedCol;
CompilationResult c(
CompilationResult::CreateForProgram(program, strlen(program)));
VERIFY_IS_TRUE(c.ParseSucceeded());
ExpectCursorAt(c.TU, 1, 1, DxcCursor_StructDecl, &varCursor);
VERIFY_SUCCEEDED(varCursor->GetLocation(&loc));
VERIFY_SUCCEEDED(loc->GetSpellingLocation(&spellingFile, &spellingLine,
&spellingCol, &spellingOffset));
VERIFY_ARE_EQUAL(1u, spellingLine);
VERIFY_ARE_EQUAL(8u, spellingCol);
VERIFY_ARE_EQUAL(7u, spellingOffset);
VERIFY_SUCCEEDED(
loc->GetPresumedLocation(&presumedFilename, &presumedLine, &presumedCol));
VERIFY_ARE_EQUAL_STR(CompilationResult::getDefaultFileName(),
presumedFilename);
VERIFY_ARE_EQUAL(1u, presumedLine);
VERIFY_ARE_EQUAL(8u, presumedCol);
}
TEST_F(DXIntellisenseTest, InclusionWhenMissingThenError) {
CComPtr<IDxcIntelliSense> isense;
CComPtr<IDxcIndex> index;
CComPtr<IDxcUnsavedFile> unsaved;
CComPtr<IDxcTranslationUnit> TU;
CComPtr<IDxcDiagnostic> pDiag;
DxcDiagnosticSeverity Severity;
const char main_text[] =
"error\r\n#include \"missing.hlsl\"\r\nfloat3 g_global;";
unsigned diagCount;
VERIFY_SUCCEEDED(
CompilationResult::DefaultHlslSupport->CreateIntellisense(&isense));
VERIFY_SUCCEEDED(isense->CreateIndex(&index));
VERIFY_SUCCEEDED(isense->CreateUnsavedFile("file.hlsl", main_text,
strlen(main_text), &unsaved));
VERIFY_SUCCEEDED(index->ParseTranslationUnit(
"file.hlsl", nullptr, 0, &unsaved.p, 1,
DxcTranslationUnitFlags_UseCallerThread, &TU));
VERIFY_SUCCEEDED(TU->GetNumDiagnostics(&diagCount));
VERIFY_ARE_EQUAL(1U, diagCount);
VERIFY_SUCCEEDED(TU->GetDiagnostic(0, &pDiag));
VERIFY_SUCCEEDED(pDiag->GetSeverity(&Severity));
VERIFY_IS_TRUE(Severity == DxcDiagnosticSeverity::DxcDiagnostic_Error ||
Severity == DxcDiagnosticSeverity::DxcDiagnostic_Fatal);
}
TEST_F(DXIntellisenseTest, InclusionWhenValidThenAvailable) {
CComPtr<IDxcIntelliSense> isense;
CComPtr<IDxcIndex> index;
CComPtr<IDxcUnsavedFile> unsaved[2];
CComPtr<IDxcTranslationUnit> TU;
CComInterfaceArray<IDxcInclusion> inclusions;
const char main_text[] =
"#include \"inc.h\"\r\nfloat4 main() : SV_Target { return FOO; }";
const char unsaved_text[] = "#define FOO 1";
unsigned diagCount;
unsigned expectedIndex = 0;
const char *expectedNames[2] = {"file.hlsl", "./inc.h"};
VERIFY_SUCCEEDED(
CompilationResult::DefaultHlslSupport->CreateIntellisense(&isense));
VERIFY_SUCCEEDED(isense->CreateIndex(&index));
VERIFY_SUCCEEDED(isense->CreateUnsavedFile(
"./inc.h", unsaved_text, strlen(unsaved_text), &unsaved[0]));
VERIFY_SUCCEEDED(isense->CreateUnsavedFile("file.hlsl", main_text,
strlen(main_text), &unsaved[1]));
VERIFY_SUCCEEDED(index->ParseTranslationUnit(
"file.hlsl", nullptr, 0, &unsaved[0].p, 2,
DxcTranslationUnitFlags_UseCallerThread, &TU));
VERIFY_SUCCEEDED(TU->GetNumDiagnostics(&diagCount));
VERIFY_ARE_EQUAL(0U, diagCount);
VERIFY_SUCCEEDED(
TU->GetInclusionList(inclusions.size_ref(), inclusions.data_ref()));
VERIFY_ARE_EQUAL(2U, inclusions.size());
for (IDxcInclusion *i : inclusions) {
CComPtr<IDxcFile> file;
CComHeapPtr<char> fileName;
VERIFY_SUCCEEDED(i->GetIncludedFile(&file));
VERIFY_SUCCEEDED(file->GetName(&fileName));
VERIFY_ARE_EQUAL_STR(expectedNames[expectedIndex], fileName.m_pData);
expectedIndex++;
}
}
TEST_F(DXIntellisenseTest, TUWhenGetFileMissingThenFail) {
const char program[] = "int i;";
CompilationResult result =
CompilationResult::CreateForProgram(program, strlen(program), nullptr);
VERIFY_IS_TRUE(result.ParseSucceeded());
CComPtr<IDxcFile> file;
VERIFY_FAILED(result.TU->GetFile("unknonwn.txt", &file));
}
TEST_F(DXIntellisenseTest, TUWhenGetFilePresentThenOK) {
const char program[] = "int i;";
CompilationResult result =
CompilationResult::CreateForProgram(program, strlen(program), nullptr);
VERIFY_IS_TRUE(result.ParseSucceeded());
CComPtr<IDxcFile> file;
VERIFY_SUCCEEDED(
result.TU->GetFile(CompilationResult::getDefaultFileName(), &file));
VERIFY_IS_NOT_NULL(file.p);
}
TEST_F(DXIntellisenseTest, TUWhenEmptyStructThenErrorIfISense) {
// An declaration of the from 'struct S;' is a forward declaration in HLSL
// 2016, but is invalid in HLSL 2015.
const char program[] = "struct S;";
const char programWithDef[] = "struct S { int i; };";
const char *args2015[] = {"-HV", "2015"};
const char *args2016[] = {"-HV", "2016"};
CompilationResult result15WithDef(CompilationResult::CreateForProgramAndArgs(
programWithDef, _countof(programWithDef), args2015, _countof(args2015),
nullptr));
VERIFY_IS_TRUE(result15WithDef.ParseSucceeded());
CompilationResult result15(CompilationResult::CreateForProgramAndArgs(
program, _countof(program), args2015, _countof(args2015), nullptr));
VERIFY_IS_FALSE(result15.ParseSucceeded());
CompilationResult result16(CompilationResult::CreateForProgramAndArgs(
program, _countof(program), args2016, _countof(args2016), nullptr));
VERIFY_IS_TRUE(result16.ParseSucceeded());
}
TEST_F(DXIntellisenseTest, TUWhenRegionInactiveMissingThenCountIsZero) {
char program[] = "void foo() { }";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcFile> file;
unsigned resultCount;
IDxcSourceRange **results;
VERIFY_SUCCEEDED(result.TU->GetFile("filename.hlsl", &file));
VERIFY_SUCCEEDED(result.TU->GetSkippedRanges(file.p, &resultCount, &results));
VERIFY_ARE_EQUAL(0U, resultCount);
VERIFY_IS_NULL(results);
}
TEST_F(DXIntellisenseTest, TUWhenRegionInactiveThenEndIsBeforeElseHash) {
char program[] = "#ifdef NOT // a comment\r\n"
"int foo() { }\r\n"
"#else // a comment\r\n"
"int bar() { }\r\n"
"#endif // a comment\r\n";
DxcTranslationUnitFlags options =
(DxcTranslationUnitFlags)(DxcTranslationUnitFlags_DetailedPreprocessingRecord |
DxcTranslationUnitFlags_UseCallerThread);
CompilationResult result(CompilationResult::CreateForProgram(
program, _countof(program), &options));
CComPtr<IDxcFile> file;
unsigned resultCount;
IDxcSourceRange **results;
VERIFY_SUCCEEDED(result.TU->GetFile("filename.hlsl", &file));
VERIFY_SUCCEEDED(result.TU->GetSkippedRanges(file.p, &resultCount, &results));
::WEX::TestExecution::DisableVerifyExceptions disable;
VERIFY_ARE_EQUAL(1U, resultCount);
for (unsigned i = 0; i < resultCount; ++i) {
CComPtr<IDxcSourceLocation> endLoc;
VERIFY_SUCCEEDED(results[i]->GetEnd(&endLoc));
unsigned line, col, offset;
VERIFY_SUCCEEDED(
endLoc->GetSpellingLocation(nullptr, &line, &col, &offset));
VERIFY_ARE_EQUAL(3U, line);
VERIFY_ARE_EQUAL(1U, col);
results[i]->Release();
}
CoTaskMemFree(results);
}
TEST_F(DXIntellisenseTest, TUWhenRegionInactiveThenEndIsBeforeEndifHash) {
char program[] = "#ifdef NOT // a comment\r\n"
"int bar() { }\r\n"
"#endif // a comment\r\n";
DxcTranslationUnitFlags options =
(DxcTranslationUnitFlags)(DxcTranslationUnitFlags_DetailedPreprocessingRecord |
DxcTranslationUnitFlags_UseCallerThread);
CompilationResult result(CompilationResult::CreateForProgram(
program, _countof(program), &options));
CComPtr<IDxcFile> file;
unsigned resultCount;
IDxcSourceRange **results;
VERIFY_SUCCEEDED(result.TU->GetFile("filename.hlsl", &file));
VERIFY_SUCCEEDED(result.TU->GetSkippedRanges(file.p, &resultCount, &results));
::WEX::TestExecution::DisableVerifyExceptions disable;
VERIFY_ARE_EQUAL(1U, resultCount);
for (unsigned i = 0; i < resultCount; ++i) {
CComPtr<IDxcSourceLocation> endLoc;
VERIFY_SUCCEEDED(results[i]->GetEnd(&endLoc));
unsigned line, col, offset;
VERIFY_SUCCEEDED(
endLoc->GetSpellingLocation(nullptr, &line, &col, &offset));
VERIFY_ARE_EQUAL(3U, line);
VERIFY_ARE_EQUAL(1U, col);
results[i]->Release();
}
CoTaskMemFree(results);
}
TEST_F(DXIntellisenseTest, TUWhenRegionInactiveThenStartIsAtIfdefEol) {
char program[] = "#ifdef NOT // a comment\r\n"
"int foo() { }\r\n"
"#else // a comment\r\n"
"int bar() { }\r\n"
"#endif // a comment\r\n";
DxcTranslationUnitFlags options =
(DxcTranslationUnitFlags)(DxcTranslationUnitFlags_DetailedPreprocessingRecord |
DxcTranslationUnitFlags_UseCallerThread);
CompilationResult result(CompilationResult::CreateForProgram(
program, _countof(program), &options));
CComPtr<IDxcFile> file;
unsigned resultCount;
IDxcSourceRange **results;
VERIFY_SUCCEEDED(result.TU->GetFile("filename.hlsl", &file));
VERIFY_SUCCEEDED(result.TU->GetSkippedRanges(file.p, &resultCount, &results));
::WEX::TestExecution::DisableVerifyExceptions disable;
VERIFY_ARE_EQUAL(1U, resultCount);
for (unsigned i = 0; i < resultCount; ++i) {
CComPtr<IDxcSourceLocation> startLoc;
VERIFY_SUCCEEDED(results[i]->GetStart(&startLoc));
unsigned line, col, offset;
VERIFY_SUCCEEDED(
startLoc->GetSpellingLocation(nullptr, &line, &col, &offset));
VERIFY_ARE_EQUAL(1U, line);
VERIFY_ARE_EQUAL(24U, col);
results[i]->Release();
}
CoTaskMemFree(results);
}
std::ostream &operator<<(std::ostream &os, CComPtr<IDxcSourceLocation> &loc) {
CComPtr<IDxcFile> locFile;
unsigned locLine, locCol, locOffset;
loc->GetSpellingLocation(&locFile, &locLine, &locCol, &locOffset);
os << locLine << ':' << locCol << '@' << locOffset;
return os;
}
std::wostream &operator<<(std::wostream &os, CComPtr<IDxcSourceLocation> &loc) {
CComPtr<IDxcFile> locFile;
unsigned locLine, locCol, locOffset;
loc->GetSpellingLocation(&locFile, &locLine, &locCol, &locOffset);
os << locLine << L':' << locCol << L'@' << locOffset;
return os;
}
TEST_F(DXIntellisenseTest, TUWhenUnsaveFileThenOK) {
// Verify that an unsaved file using the library-provided implementation still
// works.
const char fileName[] = "filename.hlsl";
char program[] = "[numthreads(1, 1, 1)]\r\n"
"[shader(\"compute\")]\r\n"
"void main( uint3 DTid : SV_DispatchThreadID )\r\n"
"{\r\n"
"}";
bool useBuiltInValues[] = {false, true};
HlslIntellisenseSupport support;
VERIFY_SUCCEEDED(support.Initialize());
for (bool useBuiltIn : useBuiltInValues) {
CComPtr<IDxcIntelliSense> isense;
CComPtr<IDxcIndex> tuIndex;
CComPtr<IDxcTranslationUnit> tu;
CComPtr<IDxcUnsavedFile> unsavedFile;
DxcTranslationUnitFlags localOptions;
const char **commandLineArgs = nullptr;
int commandLineArgsCount = 0;
VERIFY_SUCCEEDED(support.CreateIntellisense(&isense));
VERIFY_SUCCEEDED(isense->CreateIndex(&tuIndex));
VERIFY_SUCCEEDED(isense->GetDefaultEditingTUOptions(&localOptions));
if (useBuiltIn)
VERIFY_SUCCEEDED(isense->CreateUnsavedFile(
fileName, program, strlen(program), &unsavedFile));
else
VERIFY_SUCCEEDED(
TrivialDxcUnsavedFile::Create(fileName, program, &unsavedFile));
VERIFY_SUCCEEDED(tuIndex->ParseTranslationUnit(
fileName, commandLineArgs, commandLineArgsCount, &(unsavedFile.p), 1,
localOptions, &tu));
// No errors expected.
unsigned numDiagnostics;
VERIFY_SUCCEEDED(tu->GetNumDiagnostics(&numDiagnostics));
VERIFY_ARE_EQUAL(0U, numDiagnostics);
CComPtr<IDxcCursor> tuCursor;
CComInterfaceArray<IDxcCursor> cursors;
VERIFY_SUCCEEDED(tu->GetCursor(&tuCursor));
VERIFY_SUCCEEDED(
tuCursor->GetChildren(0, 20, cursors.size_ref(), cursors.data_ref()));
std::wstringstream offsetStream;
for (IDxcCursor *pCursor : cursors) {
CComPtr<IDxcSourceRange> range;
CComPtr<IDxcSourceLocation> location;
CComPtr<IDxcSourceLocation> rangeStart, rangeEnd;
CComBSTR name;
VERIFY_SUCCEEDED(pCursor->GetExtent(&range));
VERIFY_SUCCEEDED(range->GetStart(&rangeStart));
VERIFY_SUCCEEDED(range->GetEnd(&rangeEnd));
VERIFY_SUCCEEDED(pCursor->GetDisplayName(&name));
VERIFY_SUCCEEDED(pCursor->GetLocation(&location));
offsetStream << (LPWSTR)name << " - spelling " << location << " - extent "
<< rangeStart << " .. " << rangeEnd << std::endl;
}
// Format for a location is line:col@offset
VERIFY_ARE_EQUAL_WSTR(
L"main(uint3) - spelling 3:6@49 - extent 3:1@44 .. 5:2@95\n",
offsetStream.str().c_str());
}
}
TEST_F(DXIntellisenseTest, QualifiedNameClass) {
char program[] = "class TheClass {\r\n"
"};\r\n"
"TheClass C;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
ExpectQualifiedName(result.TU, 3, 1, L"TheClass");
}
TEST_F(DXIntellisenseTest, CursorWhenGlobalVariableThenSimpleNames) {
char program[] = "namespace Ns { class TheClass {\r\n"
"}; }\r\n"
"Ns::TheClass C;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
// Qualified name does not include type.
ExpectQualifiedName(result.TU, 3, 14, L"C");
// Decalaration name includes type.
ExpectDeclarationText(result.TU, 3, 14, L"Ns::TheClass C");
// Semicolon is empty.
ExpectQualifiedName(result.TU, 3, 15, L"");
}
TEST_F(DXIntellisenseTest, CursorWhenTypeOfVariableDeclThenNamesHaveType) {
char program[] = "namespace Ns { class TheClass {\r\n"
"}; }\r\n"
"Ns::TheClass C;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
ExpectQualifiedName(result.TU, 3, 1, L"Ns");
ExpectDeclarationText(result.TU, 3, 1, L"namespace Ns");
ExpectQualifiedName(result.TU, 3, 6, L"Ns::TheClass");
ExpectDeclarationText(result.TU, 3, 6, L"class Ns::TheClass");
}
TEST_F(DXIntellisenseTest, CursorTypeUsedNamespace) {
char program[] = "namespace Ns { class TheClass {\n"
"}; }\n"
"using namespace Ns;\n"
"TheClass C;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
ExpectQualifiedName(result.TU, 4, 4, L"Ns::TheClass");
}
TEST_F(DXIntellisenseTest, CursorWhenVariableRefThenSimpleNames) {
char program[] = "namespace Ns { class TheClass {\r\n"
"public: int f;\r\n"
"}; }\r\n"
"void fn() {\r\n"
"Ns::TheClass C;\r\n"
"C.f = 1;\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
ExpectCursorAt(result.TU, 6, 1, DxcCursor_DeclRefExpr);
ExpectQualifiedName(result.TU, 6, 1, L"C");
}
TEST_F(DXIntellisenseTest, CursorWhenFieldRefThenSimpleNames) {
char program[] = "namespace Ns { class TheClass {\r\n"
"public: int f;\r\n"
"}; }\r\n"
"void fn() {\r\n"
"Ns::TheClass C;\r\n"
"C.f = 1;\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
ExpectQualifiedName(result.TU, 6, 3, L"int f");
}
TEST_F(DXIntellisenseTest, QualifiedNameVariable) {
char program[] = "namespace Ns { class TheClass {\r\n"
"}; }\r\n"
"Ns::TheClass C;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
ExpectQualifiedName(result.TU, 3, 14, L"C");
}
TEST_F(DXIntellisenseTest, CursorWhenOverloadedResolvedThenDirectSymbol) {
char program[] = "int abc(int);\r\n"
"float abc(float);\r\n"
"void foo() {\r\n"
"int i = abc(123);\r\n"
"}\r\n";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
GetCursorAt(result.TU, 4, 10, &cursor);
DxcCursorKind kind;
// 'abc' in 'abc(123)' is an expression that refers to a declaration.
ASSERT_HRESULT_SUCCEEDED(cursor->GetKind(&kind));
EXPECT_EQ(DxcCursor_DeclRefExpr, kind);
// The referenced declaration is a function declaration.
CComPtr<IDxcCursor> referenced;
ASSERT_HRESULT_SUCCEEDED(cursor->GetReferencedCursor(&referenced));
ASSERT_HRESULT_SUCCEEDED(referenced->GetKind(&kind));
EXPECT_EQ(DxcCursor_FunctionDecl, kind);
}
TEST_F(DXIntellisenseTest, CursorWhenOverloadedIncompleteThenInvisible) {
char program[] = "int abc(int);\r\n"
"float abc(float);\r\n"
"void foo() {\r\n"
"int i = abc();\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
GetCursorAt(result.TU, 4, 10, &cursor);
DxcCursorKind kind;
// 'abc' in 'abc()' is just part of the declaration - it's not a valid
// standalone entity
ASSERT_HRESULT_SUCCEEDED(cursor->GetKind(&kind));
EXPECT_EQ(DxcCursor_DeclStmt, kind);
// The child of the declaration statement is the declaration.
CComPtr<IDxcCursor> decl;
ASSERT_HRESULT_SUCCEEDED(GetFirstChildFromCursor(cursor, &decl));
ASSERT_HRESULT_SUCCEEDED(decl->GetKind(&kind));
EXPECT_EQ(DxcCursor_VarDecl, kind);
}
TEST_F(DXIntellisenseTest, CursorWhenVariableUsedThenDeclarationAvailable) {
char program[] = "int foo() {\r\n"
"int i = 1;\r\n"
"return i;\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
// 'abc' in 'abc()' is just part of the declaration - it's not a valid
// standalone entity
ExpectCursorAt(result.TU, 3, 8, DxcCursor_DeclRefExpr, &cursor);
// The referenced declaration is a variable declaration.
CComPtr<IDxcCursor> referenced;
DxcCursorKind kind;
ASSERT_HRESULT_SUCCEEDED(cursor->GetReferencedCursor(&referenced));
ASSERT_HRESULT_SUCCEEDED(referenced->GetKind(&kind));
EXPECT_EQ(DxcCursor_VarDecl, kind);
CComBSTR name;
ASSERT_HRESULT_SUCCEEDED(
referenced->GetFormattedName(DxcCursorFormatting_Default, &name));
EXPECT_STREQW(L"i", (LPWSTR)name);
}
// TODO: get a referenced local variable as 'int localVar';
// TODO: get a referenced type as 'class Something';
// TODO: having the caret on a function name in definition, highlights calls to
// it
// TODO: get a class name without the template arguments
// TODO: get a class name with ftemplate arguments
// TODO: code completion for a built-in function
// TODO: code completion for a built-in method
TEST_F(DXIntellisenseTest, CursorWhenFunctionThenSignatureAvailable) {
char program[] = "int myfunc(int a, float b) { return a + b; }\r\n"
"int foo() {\r\n"
"myfunc(1, 2.0f);\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
ExpectCursorAt(result.TU, 3, 1, DxcCursor_DeclRefExpr, &cursor);
// TODO - how to get signature?
}
TEST_F(DXIntellisenseTest, CursorWhenFunctionThenParamsAvailable) {
char program[] = "int myfunc(int a, float b) { return a + b; }\r\n"
"int foo() {\r\n"
"myfunc(1, 2.0f);\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
ExpectCursorAt(result.TU, 3, 1, DxcCursor_DeclRefExpr, &cursor);
int argCount;
VERIFY_SUCCEEDED(cursor->GetNumArguments(&argCount));
VERIFY_ARE_EQUAL(-1, argCount); // The reference doesn't have the argument
// count - we need to resolve to func decl
// TODO - how to get signature?
}
TEST_F(DXIntellisenseTest, CursorWhenFunctionThenReturnTypeAvailable) {
char program[] = "int myfunc(int a, float b) { return a + b; }\r\n"
"int foo() {\r\n"
"myfunc(1, 2.0f);\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
ExpectCursorAt(result.TU, 3, 1, DxcCursor_DeclRefExpr, &cursor);
// TODO - how to get signature?
}
TEST_F(DXIntellisenseTest, CursorWhenReferenceThenDefinitionAvailable) {
char program[] = "int myfunc(int a, float b) { return a + b; }\r\n"
"int foo() {\r\n"
"myfunc(1, 2.0f);\r\n"
"}";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
CComPtr<IDxcCursor> defCursor;
CComPtr<IDxcSourceLocation> defLocation;
CComPtr<IDxcFile> defFile;
unsigned line, col, offset;
ExpectCursorAt(result.TU, 3, 1, DxcCursor_DeclRefExpr, &cursor);
VERIFY_SUCCEEDED(cursor->GetDefinitionCursor(&defCursor));
VERIFY_IS_NOT_NULL(defCursor.p);
DxcCursorKind kind;
VERIFY_SUCCEEDED(defCursor->GetKind(&kind));
VERIFY_ARE_EQUAL(DxcCursor_FunctionDecl, kind);
VERIFY_SUCCEEDED(defCursor->GetLocation(&defLocation));
VERIFY_SUCCEEDED(
defLocation->GetSpellingLocation(&defFile, &line, &col, &offset));
VERIFY_ARE_EQUAL(1U, line);
VERIFY_ARE_EQUAL(5U, col); // Points to 'myfunc'
VERIFY_ARE_EQUAL(4U, offset); // Offset is zero-based
}
TEST_F(DXIntellisenseTest, CursorWhenFindAtBodyCallThenMatch) {
char program[] = "int f();\r\n"
"int main() {\r\n"
" f(); }";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
ExpectCursorAt(result.TU, 3, 3, DxcCursor_DeclRefExpr, &cursor);
}
TEST_F(DXIntellisenseTest, CursorWhenFindAtGlobalThenMatch) {
char program[] = "int a;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
ExpectCursorAt(result.TU, 1, 4, DxcCursor_VarDecl, &cursor);
}
TEST_F(DXIntellisenseTest, CursorWhenFindBeforeBodyCallThenMatch) {
char program[] = "int f();\r\n"
"int main() {\r\n"
" f(); }";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
ExpectCursorAt(result.TU, 3, 1, DxcCursor_CompoundStmt, &cursor);
CComPtr<IDxcCursor> snappedCursor;
CComPtr<IDxcSourceLocation> location;
DxcCursorKind cursorKind;
GetLocationAt(result.TU, 3, 1, &location);
VERIFY_SUCCEEDED(cursor->GetSnappedChild(location, &snappedCursor));
VERIFY_IS_NOT_NULL(snappedCursor.p);
VERIFY_SUCCEEDED(snappedCursor->GetKind(&cursorKind));
VERIFY_ARE_EQUAL(DxcCursor_DeclRefExpr, cursorKind);
}
TEST_F(DXIntellisenseTest, CursorWhenFindBeforeGlobalThenMatch) {
char program[] = " int a;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcCursor> cursor;
ExpectCursorAt(result.TU, 1, 1, DxcCursor_NoDeclFound, &cursor);
cursor.Release();
CComPtr<IDxcCursor> snappedCursor;
CComPtr<IDxcSourceLocation> location;
DxcCursorKind cursorKind;
GetLocationAt(result.TU, 1, 1, &location);
VERIFY_SUCCEEDED(result.TU->GetCursor(&cursor));
VERIFY_SUCCEEDED(cursor->GetSnappedChild(location, &snappedCursor));
VERIFY_IS_NOT_NULL(snappedCursor.p);
VERIFY_SUCCEEDED(snappedCursor->GetKind(&cursorKind));
VERIFY_ARE_EQUAL(DxcCursor_VarDecl, cursorKind);
}
TEST_F(DXIntellisenseTest, FileWhenSameThenEqual) {
char program[] = "int a;\r\nint b;";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcSourceLocation> location0, location1;
CComPtr<IDxcFile> file0, file1;
unsigned line, col, offset;
BOOL isEqual;
GetLocationAt(result.TU, 1, 1, &location0);
GetLocationAt(result.TU, 2, 1, &location1);
VERIFY_SUCCEEDED(
location0->GetSpellingLocation(&file0, &line, &col, &offset));
VERIFY_SUCCEEDED(
location1->GetSpellingLocation(&file1, &line, &col, &offset));
VERIFY_SUCCEEDED(file0->IsEqualTo(file1, &isEqual));
VERIFY_ARE_EQUAL(TRUE, isEqual);
}
TEST_F(DXIntellisenseTest, FileWhenNotSameThenNotEqual) {
char program[] = "int a;\r\nint b;";
CompilationResult result0(
CompilationResult::CreateForProgram(program, _countof(program)));
CompilationResult result1(
CompilationResult::CreateForProgram(program, _countof(program)));
CComPtr<IDxcSourceLocation> location0, location1;
CComPtr<IDxcFile> file0, file1;
unsigned line, col, offset;
BOOL isEqual;
GetLocationAt(result0.TU, 1, 1, &location0);
GetLocationAt(result1.TU, 1, 1, &location1);
VERIFY_SUCCEEDED(
location0->GetSpellingLocation(&file0, &line, &col, &offset));
VERIFY_SUCCEEDED(
location1->GetSpellingLocation(&file1, &line, &col, &offset));
VERIFY_SUCCEEDED(file0->IsEqualTo(file1, &isEqual));
VERIFY_ARE_EQUAL(FALSE, isEqual);
}
TEST_F(DXIntellisenseTest, TypeWhenICEThenEval) {
// When an ICE is present in a declaration, it appears in the name.
char program[] = "float c[(1, 2)];\r\n"
"float main() : SV_Target\r\n"
"{ return c[0]; }";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
VERIFY_IS_TRUE(result.ParseSucceeded());
CComPtr<IDxcCursor> cCursor;
ExpectCursorAt(result.TU, 1, 7, DxcCursor_VarDecl, &cCursor);
CComPtr<IDxcType> typeCursor;
VERIFY_SUCCEEDED(cCursor->GetCursorType(&typeCursor));
CComHeapPtr<char> name;
VERIFY_SUCCEEDED(typeCursor->GetSpelling(&name));
VERIFY_ARE_EQUAL_STR("const float [2]",
name); // global variables converted to const by default
}
TEST_F(DXIntellisenseTest, CompletionWhenResultsAvailable) {
char program[] = "struct MyStruct {};"
"MyStr";
CompilationResult result(
CompilationResult::CreateForProgram(program, _countof(program)));
VERIFY_IS_FALSE(result.ParseSucceeded());
const char *fileName = "filename.hlsl";
CComPtr<IDxcUnsavedFile> unsavedFile;
VERIFY_SUCCEEDED(
TrivialDxcUnsavedFile::Create(fileName, program, &unsavedFile));
CComPtr<IDxcCodeCompleteResults> codeCompleteResults;
VERIFY_SUCCEEDED(result.TU->CodeCompleteAt(fileName, 2, 1, &unsavedFile.p, 1,
DxcCodeCompleteFlags_None,
&codeCompleteResults));
unsigned numResults;
VERIFY_SUCCEEDED(codeCompleteResults->GetNumResults(&numResults));
VERIFY_IS_GREATER_THAN_OR_EQUAL(numResults, 1u);
CComPtr<IDxcCompletionResult> completionResult;
VERIFY_SUCCEEDED(codeCompleteResults->GetResultAt(0, &completionResult));
DxcCursorKind completionResultCursorKind;
VERIFY_SUCCEEDED(
completionResult->GetCursorKind(&completionResultCursorKind));
VERIFY_ARE_EQUAL(DxcCursor_StructDecl, completionResultCursorKind);
CComPtr<IDxcCompletionString> completionString;
VERIFY_SUCCEEDED(completionResult->GetCompletionString(&completionString));
unsigned numCompletionChunks;
VERIFY_SUCCEEDED(
completionString->GetNumCompletionChunks(&numCompletionChunks));
VERIFY_ARE_EQUAL(1u, numCompletionChunks);
DxcCompletionChunkKind completionChunkKind;
VERIFY_SUCCEEDED(
completionString->GetCompletionChunkKind(0, &completionChunkKind));
VERIFY_ARE_EQUAL(DxcCompletionChunk_TypedText, completionChunkKind);
CComHeapPtr<char> completionChunkText;
VERIFY_SUCCEEDED(
completionString->GetCompletionChunkText(0, &completionChunkText));
VERIFY_ARE_EQUAL_STR("MyStruct", completionChunkText);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/PixTestUtils.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// PixTestUtils.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides utility functions for PIX tests. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "PixTestUtils.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HlslTestUtils.h"
static std::vector<std::string> Tokenize(const std::string &str,
const char *delimiters) {
std::vector<std::string> tokens;
std::string copy = str;
for (auto i = strtok(©[0], delimiters); i != nullptr;
i = strtok(nullptr, delimiters)) {
tokens.push_back(i);
}
return tokens;
}
// For RunAnnotationPasses
namespace {
std::string ToString(std::wstring from) {
std::string ret;
ret.assign(from.data(), from.data() + from.size());
return ret;
}
std::string ExtractBracedSubstring(std::string const &line) {
auto open = line.find('{');
auto close = line.find('}');
if (open != std::string::npos && close != std::string::npos &&
open + 1 < close) {
return line.substr(open + 1, close - open - 1);
}
return "";
}
int ExtractMetaInt32Value(std::string const &token) {
if (token.substr(0, 5) == " i32 ") {
return atoi(token.c_str() + 5);
}
return -1;
}
std::map<int, std::pair<int, int>>
MetaDataKeyToRegisterNumber(std::vector<std::string> const &lines) {
// Find lines of the exemplary form
// "!249 = !{i32 0, i32 20}" (in the case of a DXIL value)
// "!196 = !{i32 1, i32 5, i32 1}" (in the case of a DXIL alloca reg)
// The first i32 is a tag indicating what type of metadata this is.
// It doesn't matter if we parse poorly and find some data that don't match
// this pattern, as long as we do find all the data that do match (we won't
// be looking up the non-matchers in the resultant map anyway).
const char *valueMetaDataAssignment = "= !{i32 0, ";
const char *allocaMetaDataAssignment = "= !{i32 1, ";
std::map<int, std::pair<int, int>> ret;
for (auto const &line : lines) {
if (line[0] == '!') {
if (line.find(valueMetaDataAssignment) != std::string::npos ||
line.find(allocaMetaDataAssignment) != std::string::npos) {
int key = atoi(line.c_str() + 1);
if (key != 0) {
std::string bitInBraces = ExtractBracedSubstring(line);
if (bitInBraces != "") {
auto tokens = Tokenize(bitInBraces.c_str(), ",");
if (tokens.size() == 2) {
auto value = ExtractMetaInt32Value(tokens[1]);
if (value != -1) {
ret[key] = {value, 1};
}
}
if (tokens.size() == 3) {
auto value0 = ExtractMetaInt32Value(tokens[1]);
if (value0 != -1) {
auto value1 = ExtractMetaInt32Value(tokens[2]);
if (value1 != -1) {
ret[key] = {value0, value1};
}
}
}
}
}
}
}
}
return ret;
}
std::string ExtractValueName(std::string const &line) {
auto foundEquals = line.find('=');
if (foundEquals != std::string::npos && foundEquals > 4) {
return line.substr(2, foundEquals - 3);
}
return "";
}
using DxilRegisterToNameMap = std::map<std::pair<int, int>, std::string>;
void CheckForAndInsertMapEntryIfFound(
DxilRegisterToNameMap ®isterToNameMap,
std::map<int, std::pair<int, int>> const &metaDataKeyToValue,
std::string const &line, char const *tag, size_t tagLength) {
auto foundAlloca = line.find(tag);
if (foundAlloca != std::string::npos) {
auto valueName = ExtractValueName(line);
if (valueName != "") {
int key = atoi(line.c_str() + foundAlloca + tagLength);
auto foundKey = metaDataKeyToValue.find(key);
if (foundKey != metaDataKeyToValue.end()) {
registerToNameMap[foundKey->second] = valueName;
}
}
}
}
// Here's some exemplary DXIL to help understand what's going on:
//
// %5 = alloca [1 x float], i32 0, !pix-alloca-reg !196
// %25 = call float @dx.op.loadInput.f32(...), !pix-dxil-reg !255
//
// The %5 is an alloca name, and the %25 is a regular llvm value.
// The meta-data tags !pix-alloca-reg and !pix-dxil-reg denote this,
// and provide keys !196 and !255 respectively.
// Those keys are then given values later on in the DXIL like this:
//
// !196 = !{i32 1, i32 5, i32 1} (5 is the base alloca, 1 is the offset into
// it) !255 = !{i32 0, i32 23}
//
// So the task is first to find all of those key/value pairs and make a map
// from e.g. !196 to, e.g., (5,1), and then to find all of the alloca and reg
// tags and look up the keys in said map to build the map we're actually
// looking for, with key->values like e.g. "%5"->(5,1) and "%25"->(23)
DxilRegisterToNameMap BuildDxilRegisterToNameMap(char const *disassembly) {
DxilRegisterToNameMap ret;
auto lines = Tokenize(disassembly, "\n");
auto metaDataKeyToValue = MetaDataKeyToRegisterNumber(lines);
for (auto const &line : lines) {
if (line[0] == '!') {
// Stop searching for values when we've run into the metadata region of
// the disassembly
break;
}
const char allocaTag[] = "!pix-alloca-reg !";
CheckForAndInsertMapEntryIfFound(ret, metaDataKeyToValue, line, allocaTag,
_countof(allocaTag) - 1);
const char valueTag[] = "!pix-dxil-reg !";
CheckForAndInsertMapEntryIfFound(ret, metaDataKeyToValue, line, valueTag,
_countof(valueTag) - 1);
}
return ret;
}
std::wstring Disassemble(dxc::DxcDllSupport &dllSupport, IDxcBlob *pProgram) {
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(pix_test::CreateCompiler(dllSupport, &pCompiler));
CComPtr<IDxcBlobEncoding> pDbgDisassembly;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDbgDisassembly));
std::string disText = BlobToUtf8(pDbgDisassembly);
CA2W disTextW(disText.c_str());
return std::wstring(disTextW);
}
} // namespace
// For CreateBlobFromText
namespace {
void CreateBlobPinned(dxc::DxcDllSupport &dllSupport,
_In_bytecount_(size) LPCVOID data, SIZE_T size,
UINT32 codePage, IDxcBlobEncoding **ppBlob) {
CComPtr<IDxcLibrary> library;
IFT(dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
IFT(library->CreateBlobWithEncodingFromPinned(data, size, codePage, ppBlob));
}
} // namespace
namespace pix_test {
std::vector<std::string> SplitAndPreserveEmptyLines(std::string const &str,
char delimeter) {
std::vector<std::string> lines;
auto const *p = str.data();
auto const *justPastPreviousDelimiter = p;
while (p < str.data() + str.length()) {
if (*p == delimeter) {
lines.emplace_back(justPastPreviousDelimiter,
p - justPastPreviousDelimiter);
justPastPreviousDelimiter = p + 1;
p = justPastPreviousDelimiter;
} else {
p++;
}
}
lines.emplace_back(
std::string(justPastPreviousDelimiter, p - justPastPreviousDelimiter));
return lines;
}
void CompileAndLogErrors(dxc::DxcDllSupport &dllSupport, LPCSTR pText,
LPCWSTR pTargetProfile, std::vector<LPCWSTR> &args,
IDxcIncludeHandler *includer,
_Outptr_ IDxcBlob **ppResult) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcOperationResult> pResult;
HRESULT hrCompile;
*ppResult = nullptr;
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
Utf8ToBlob(dllSupport, pText, &pSource);
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
pTargetProfile, args.data(), args.size(),
nullptr, 0, includer, &pResult));
VERIFY_SUCCEEDED(pResult->GetStatus(&hrCompile));
if (FAILED(hrCompile)) {
CComPtr<IDxcBlobEncoding> textBlob;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&textBlob));
std::wstring text = BlobToWide(textBlob);
WEX::Logging::Log::Comment(text.c_str());
}
VERIFY_SUCCEEDED(hrCompile);
VERIFY_SUCCEEDED(pResult->GetResult(ppResult));
}
PassOutput RunAnnotationPasses(dxc::DxcDllSupport &dllSupport, IDxcBlob *dxil,
int startingLineNumber) {
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(L"-opt-mod-passes");
Options.push_back(L"-dxil-dbg-value-to-dbg-declare");
std::wstring annotationCommandLine =
L"-dxil-annotate-with-virtual-regs,startInstruction=" +
std::to_wstring(startingLineNumber);
Options.push_back(annotationCommandLine.c_str());
CComPtr<IDxcBlob> pOptimizedModule;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
dxil, Options.data(), Options.size(), &pOptimizedModule, &pText));
std::string outputText = BlobToUtf8(pText);
auto disasm = ToString(Disassemble(dllSupport, pOptimizedModule));
auto registerToName = BuildDxilRegisterToNameMap(disasm.c_str());
std::vector<ValueLocation> valueLocations;
for (auto const &r2n : registerToName) {
valueLocations.push_back({r2n.first.first, r2n.first.second});
}
return {std::move(pOptimizedModule), std::move(valueLocations),
Tokenize(outputText.c_str(), "\n")};
}
class InstructionOffsetSeekerImpl : public InstructionOffsetSeeker {
std::map<std::wstring, DWORD> m_labelToInstructionOffset;
public:
InstructionOffsetSeekerImpl(DebuggerInterfaces &debuggerInterfaces) {
DWORD SourceFileOrdinal = 0;
CComBSTR fileName;
CComBSTR fileContent;
while (SUCCEEDED(debuggerInterfaces.compilationInfo->GetSourceFile(
SourceFileOrdinal, &fileName, &fileContent))) {
auto lines = strtok(std::wstring(fileContent), L"\n");
for (size_t line = 0; line < lines.size(); ++line) {
const wchar_t DebugLocLabel[] = L"debug-loc(";
auto DebugLocPos = lines[line].find(DebugLocLabel);
if (DebugLocPos != std::wstring::npos) {
auto StartLabelPos = DebugLocPos + (_countof(DebugLocLabel) - 1);
auto CloseDebugLocPos = lines[line].find(L")", StartLabelPos);
if (CloseDebugLocPos == std::string::npos) {
VERIFY_ARE_NOT_EQUAL(CloseDebugLocPos, std::string::npos);
}
auto Label = lines[line].substr(StartLabelPos,
CloseDebugLocPos - StartLabelPos);
CComPtr<IDxcPixDxilInstructionOffsets> InstructionOffsets;
if (FAILED((debuggerInterfaces.debugInfo
->InstructionOffsetsFromSourceLocation(
fileName, line + 1, 0, &InstructionOffsets)))) {
VERIFY_FAIL(L"InstructionOffsetsFromSourceLocation failed");
}
auto InstructionOffsetCount = InstructionOffsets->GetCount();
if (InstructionOffsetCount == 0) {
VERIFY_FAIL(L"Instruction offset count was zero");
}
if (m_labelToInstructionOffset.find(Label) !=
m_labelToInstructionOffset.end()) {
VERIFY_FAIL(L"Duplicate label found!");
}
// Just the last offset is sufficient:
m_labelToInstructionOffset[Label] =
InstructionOffsets->GetOffsetByIndex(InstructionOffsetCount - 1);
}
}
SourceFileOrdinal++;
fileName.Empty();
fileContent.Empty();
}
}
virtual DWORD FindInstructionOffsetForLabel(const wchar_t *label) override {
VERIFY_ARE_NOT_EQUAL(m_labelToInstructionOffset.find(label),
m_labelToInstructionOffset.end());
return m_labelToInstructionOffset[label];
}
};
std::unique_ptr<pix_test::InstructionOffsetSeeker>
GatherDebugLocLabelsFromDxcUtils(DebuggerInterfaces &debuggerInterfaces) {
return std::make_unique<InstructionOffsetSeekerImpl>(debuggerInterfaces);
}
CComPtr<IDxcBlob> GetDebugPart(dxc::DxcDllSupport &dllSupport,
IDxcBlob *container) {
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CComPtr<IDxcContainerReflection> pReflection;
VERIFY_SUCCEEDED(
dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(pReflection->Load(container));
UINT32 index;
VERIFY_SUCCEEDED(
pReflection->FindFirstPartKind(hlsl::DFCC_ShaderDebugInfoDXIL, &index));
CComPtr<IDxcBlob> debugPart;
VERIFY_SUCCEEDED(pReflection->GetPartContent(index, &debugPart));
return debugPart;
}
void CreateBlobFromText(dxc::DxcDllSupport &dllSupport, const char *pText,
IDxcBlobEncoding **ppBlob) {
CreateBlobPinned(dllSupport, pText, strlen(pText) + 1, CP_UTF8, ppBlob);
}
HRESULT CreateCompiler(dxc::DxcDllSupport &dllSupport,
IDxcCompiler **ppResult) {
return dllSupport.CreateInstance(CLSID_DxcCompiler, ppResult);
}
CComPtr<IDxcBlob> Compile(dxc::DxcDllSupport &dllSupport, const char *hlsl,
const wchar_t *target,
std::vector<const wchar_t *> extraArgs,
const wchar_t *entry) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(CreateCompiler(dllSupport, &pCompiler));
CreateBlobFromText(dllSupport, hlsl, &pSource);
std::vector<const wchar_t *> args = {L"/Zi", L"/Qembed_debug"};
args.insert(args.end(), extraArgs.begin(), extraArgs.end());
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, L"source.hlsl", entry, target, args.data(),
static_cast<UINT32>(args.size()), nullptr, 0, nullptr, &pResult));
HRESULT compilationStatus;
VERIFY_SUCCEEDED(pResult->GetStatus(&compilationStatus));
if (FAILED(compilationStatus)) {
CComPtr<IDxcBlobEncoding> pErrros;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrros));
CA2W errorTextW(static_cast<const char *>(pErrros->GetBufferPointer()));
WEX::Logging::Log::Error(errorTextW);
return {};
}
#if 0 // handy for debugging
{
CComPtr<IDxcBlob> pProgram;
CheckOperationSucceeded(pResult, &pProgram);
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
const hlsl::DxilContainerHeader *pContainer = hlsl::IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_IS_NOT_NULL(pContainer);
hlsl::DxilPartIterator partIter =
std::find_if(hlsl::begin(pContainer), hlsl::end(pContainer),
hlsl::DxilPartIsType(hlsl::DFCC_ShaderDebugInfoDXIL));
const hlsl::DxilProgramHeader *pProgramHeader =
(const hlsl::DxilProgramHeader *)hlsl::GetDxilPartData(*partIter);
uint32_t bitcodeLength;
const char *pBitcode;
CComPtr<IDxcBlob> pProgramPdb;
hlsl::GetDxilProgramBitcode(pProgramHeader, &pBitcode, &bitcodeLength);
VERIFY_SUCCEEDED(pLib->CreateBlobFromBlob(
pProgram, pBitcode - (char *)pProgram->GetBufferPointer(),
bitcodeLength, &pProgramPdb));
CComPtr<IDxcBlobEncoding> pDbgDisassembly;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgramPdb, &pDbgDisassembly));
std::string disText = BlobToUtf8(pDbgDisassembly);
CA2W disTextW(disText.c_str());
WEX::Logging::Log::Comment(disTextW);
}
#endif
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
return pProgram;
}
CComPtr<IDxcBlob> WrapInNewContainer(dxc::DxcDllSupport &dllSupport,
IDxcBlob *part) {
CComPtr<IDxcAssembler> pAssembler;
IFT(dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
CComPtr<IDxcOperationResult> pAssembleResult;
VERIFY_SUCCEEDED(pAssembler->AssembleToContainer(part, &pAssembleResult));
CComPtr<IDxcBlobEncoding> pAssembleErrors;
VERIFY_SUCCEEDED(pAssembleResult->GetErrorBuffer(&pAssembleErrors));
if (pAssembleErrors && pAssembleErrors->GetBufferSize() != 0) {
OutputDebugStringA(
static_cast<LPCSTR>(pAssembleErrors->GetBufferPointer()));
VERIFY_SUCCEEDED(E_FAIL);
}
CComPtr<IDxcBlob> pNewContainer;
VERIFY_SUCCEEDED(pAssembleResult->GetResult(&pNewContainer));
return pNewContainer;
}
} // namespace pix_test
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/OptimizerTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// OptimizerTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for the optimizer API. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef UNICODE
#define UNICODE
#endif
#include <algorithm>
#include <cassert>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
// For DxilRuntimeReflection.h:
#include "dxc/Support/WinIncludes.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/DxilContainer/DxilPipelineStateValidation.h"
#include "dxc/DxilContainer/DxilRuntimeReflection.h"
#include "dxc/DxilRootSignature/DxilRootSignature.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HLSLTestData.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/HLSLOptions.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/Support/microcom.h"
#include "llvm/Support/raw_os_ostream.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace std;
using namespace hlsl_test;
///////////////////////////////////////////////////////////////////////////////
// Optimizer test cases.
#ifdef _WIN32
class OptimizerTest {
#else
class OptimizerTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(OptimizerTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
// Split just so we can run them with some degree of concurrency.
TEST_METHOD(OptimizerWhenSlice0ThenOK)
TEST_METHOD(OptimizerWhenSlice1ThenOK)
TEST_METHOD(OptimizerWhenSlice2ThenOK)
TEST_METHOD(OptimizerWhenSlice3ThenOK)
TEST_METHOD(OptimizerWhenSliceWithIntermediateOptionsThenOK)
TEST_METHOD(OptimizerWhenPassedContainerPreservesSubobjects)
TEST_METHOD(OptimizerWhenPassedContainerPreservesRootSig)
TEST_METHOD(
OptimizerWhenPassedContainerPreservesViewId_HSDependentPCDependent)
TEST_METHOD(
OptimizerWhenPassedContainerPreservesViewId_HSDependentPCNonDependent)
TEST_METHOD(
OptimizerWhenPassedContainerPreservesViewId_HSNonDependentPCDependent)
TEST_METHOD(
OptimizerWhenPassedContainerPreservesViewId_HSNonDependentPCNonDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_MSDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_MSNonDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_DSDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_DSNonDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_VSDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_VSNonDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_GSDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesViewId_GSNonDependent)
TEST_METHOD(OptimizerWhenPassedContainerPreservesResourceStats_PSMultiCBTex2D)
void OptimizerWhenSliceNThenOK(int optLevel);
void OptimizerWhenSliceNThenOK(int optLevel, LPCSTR pText, LPCWSTR pTarget,
llvm::ArrayRef<LPCWSTR> args = {});
CComPtr<IDxcBlob> Compile(char const *source, wchar_t const *entry,
wchar_t const *profile);
CComPtr<IDxcBlob> RunHlslEmitAndReturnContainer(IDxcBlob *container);
CComPtr<IDxcBlob> RetrievePartFromContainer(IDxcBlob *container, UINT32 part);
void ComparePSV0BeforeAndAfterOptimization(const char *source,
const wchar_t *entry,
const wchar_t *profile,
bool usesViewId,
int streamCount = 1);
void CompareSTATBeforeAndAfterOptimization(const char *source,
const wchar_t *entry,
const wchar_t *profile,
bool usesViewId,
int streamCount = 1);
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
HRESULT CreateCompiler(IDxcCompiler **ppResult) {
return m_dllSupport.CreateInstance(CLSID_DxcCompiler, ppResult);
}
HRESULT CreateContainerBuilder(IDxcContainerBuilder **ppResult) {
return m_dllSupport.CreateInstance(CLSID_DxcContainerBuilder, ppResult);
}
void VerifyOperationSucceeded(IDxcOperationResult *pResult) {
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
if (FAILED(result)) {
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
CA2W errorsWide(BlobToUtf8(pErrors).c_str());
WEX::Logging::Log::Comment(errorsWide);
}
VERIFY_SUCCEEDED(result);
}
};
bool OptimizerTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
TEST_F(OptimizerTest, OptimizerWhenSlice0ThenOK) {
OptimizerWhenSliceNThenOK(0);
}
TEST_F(OptimizerTest, OptimizerWhenSlice1ThenOK) {
OptimizerWhenSliceNThenOK(1);
}
TEST_F(OptimizerTest, OptimizerWhenSlice2ThenOK) {
OptimizerWhenSliceNThenOK(2);
}
TEST_F(OptimizerTest, OptimizerWhenSlice3ThenOK) {
OptimizerWhenSliceNThenOK(3);
}
TEST_F(OptimizerTest, OptimizerWhenSliceWithIntermediateOptionsThenOK) {
// The program below working depends on the LegacyResourceReservation option
// being carried through to the resource register allocator, even though it is
// not preserved in the final shader.
LPCSTR SampleProgram = "Texture2D tex0 : register(t0);\r\n"
"Texture2D tex1;\r\n" // tex1 should get register t1
"float4 main() : SV_Target {\r\n"
" return tex1.Load((int3)0);\r\n"
"}";
OptimizerWhenSliceNThenOK(1, SampleProgram, L"ps_6_0",
{L"-flegacy-resource-reservation"});
}
void OptimizerTest::OptimizerWhenSliceNThenOK(int optLevel) {
LPCSTR SampleProgram = "Texture2D g_Tex;\r\n"
"SamplerState g_Sampler;\r\n"
"void unused() { }\r\n"
"float4 main(float4 pos : SV_Position, float4 user : "
"USER, bool b : B) : SV_Target {\r\n"
" unused();\r\n"
" if (b) user = g_Tex.Sample(g_Sampler, pos.xy);\r\n"
" return user * pos;\r\n"
"}";
OptimizerWhenSliceNThenOK(
optLevel, SampleProgram, L"ps_6_0",
// Add -validator-version 1.4 to ensure it's not changed by DxcAssembler.
{L"-validator-version", L"1.4"});
}
static bool IsPassMarkerFunction(LPCWSTR pName) {
return 0 == _wcsicmp(pName, L"-opt-fn-passes");
}
static bool IsPassMarkerNotFunction(LPCWSTR pName) {
return 0 == _wcsnicmp(pName, L"-opt-", 5) && !IsPassMarkerFunction(pName);
}
static void ExtractFunctionPasses(std::vector<LPCWSTR> &passes,
std::vector<LPCWSTR> &functionPasses) {
// Assumption: contiguous range
typedef std::vector<LPCWSTR>::iterator it;
it firstPass =
std::find_if(passes.begin(), passes.end(), IsPassMarkerFunction);
if (firstPass == passes.end())
return;
it lastPass = std::find_if(firstPass, passes.end(), IsPassMarkerNotFunction);
it cursor = firstPass;
while (cursor != lastPass) {
functionPasses.push_back(*cursor);
++cursor;
}
passes.erase(firstPass, lastPass);
}
void OptimizerTest::OptimizerWhenSliceNThenOK(int optLevel, LPCSTR pText,
LPCWSTR pTarget,
llvm::ArrayRef<LPCWSTR> args) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOptimizer> pOptimizer;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlob> pProgramModule;
CComPtr<IDxcBlob> pProgramDisassemble;
CComPtr<IDxcBlob> pHighLevelBlob;
CComPtr<IDxcBlob> pOptDump;
std::string passes;
std::vector<LPCWSTR> passList;
std::vector<LPCWSTR> prefixPassList;
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
// Set up compilation args vector
wchar_t OptArg[4] = L"/O0";
OptArg[2] = L'0' + optLevel;
Utf8ToBlob(m_dllSupport, pText, &pSource);
std::vector<LPCWSTR> highLevelArgs = {L"/Vd", OptArg};
highLevelArgs.insert(highLevelArgs.end(), args.begin(), args.end());
// Create the target program with a single invocation.
highLevelArgs.emplace_back(L"/Qkeep_reflect_in_dxil");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main", pTarget,
highLevelArgs.data(),
static_cast<UINT32>(highLevelArgs.size()),
nullptr, 0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
pResult.Release();
std::string originalAssembly = DisassembleProgram(m_dllSupport, pProgram);
highLevelArgs.pop_back(); // Remove /keep_reflect_in_dxil
// Get a list of passes for this configuration.
highLevelArgs.emplace_back(L"/Odump");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main", pTarget,
highLevelArgs.data(),
static_cast<UINT32>(highLevelArgs.size()),
nullptr, 0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pOptDump));
pResult.Release();
passes = BlobToUtf8(pOptDump);
CA2W passesW(passes.c_str());
// Get the high-level compile of the program.
highLevelArgs.pop_back(); // Remove /Odump
highLevelArgs.emplace_back(L"/fcgl");
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main", pTarget,
highLevelArgs.data(),
static_cast<UINT32>(highLevelArgs.size()),
nullptr, 0, nullptr, &pResult));
VerifyOperationSucceeded(pResult);
VERIFY_SUCCEEDED(pResult->GetResult(&pHighLevelBlob));
pResult.Release();
// Create a list of passes.
SplitPassList(passesW.m_psz, passList);
ExtractFunctionPasses(passList, prefixPassList);
// For each point in between the passes ...
for (size_t i = 0; i <= passList.size(); ++i) {
size_t secondPassIdx = i;
size_t firstPassCount = i;
size_t secondPassCount = passList.size() - i;
// If we find an -hlsl-passes-nopause, pause/resume will not work past this.
if (i > 0 && 0 == wcscmp(L"-hlsl-passes-nopause", passList[i - 1])) {
break;
}
CComPtr<IDxcBlob> pFirstModule;
CComPtr<IDxcBlob> pSecondModule;
CComPtr<IDxcBlob> pAssembledBlob;
std::vector<LPCWSTR> firstPassList, secondPassList;
firstPassList = prefixPassList;
firstPassList.push_back(L"-opt-mod-passes");
secondPassList = firstPassList;
firstPassList.insert(firstPassList.end(), passList.begin(),
passList.begin() + firstPassCount);
firstPassList.push_back(L"-hlsl-passes-pause");
secondPassList.push_back(L"-hlsl-passes-resume");
secondPassList.insert(secondPassList.end(),
passList.begin() + secondPassIdx,
passList.begin() + secondPassIdx + secondPassCount);
// Run a first pass.
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
pHighLevelBlob, firstPassList.data(), (UINT32)firstPassList.size(),
&pFirstModule, nullptr));
// Run a second pass.
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(
pFirstModule, secondPassList.data(), (UINT32)secondPassList.size(),
&pSecondModule, nullptr));
// Assembly it into a container so the disassembler shows equivalent data.
AssembleToContainer(m_dllSupport, pSecondModule, &pAssembledBlob);
// Verify we get the same results as in the full version.
std::string assembly = DisassembleProgram(m_dllSupport, pAssembledBlob);
if (0 != strcmp(assembly.c_str(), originalAssembly.c_str())) {
LogCommentFmt(L"Difference found in disassembly in iteration %u when "
L"breaking before '%s'",
i, (i == passList.size()) ? L"(full list)" : passList[i]);
LogCommentFmt(L"Original assembly\r\n%S", originalAssembly.c_str());
LogCommentFmt(L"\r\nReassembled assembly\r\n%S", assembly.c_str());
VERIFY_FAIL();
}
}
}
CComPtr<IDxcBlob> OptimizerTest::Compile(char const *source,
wchar_t const *entry,
wchar_t const *profile) {
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
CComPtr<IDxcBlobEncoding> pSource;
Utf8ToBlob(m_dllSupport, source, &pSource);
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", entry, profile,
nullptr, 0, nullptr, 0, nullptr,
&pResult));
VerifyOperationSucceeded(pResult);
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
return pProgram;
}
CComPtr<IDxcBlob>
OptimizerTest::RunHlslEmitAndReturnContainer(IDxcBlob *container) {
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
std::vector<LPCWSTR> Options;
Options.push_back(L"-hlsl-dxilemit");
CComPtr<IDxcBlob> pDxil;
CComPtr<IDxcBlobEncoding> pText;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(container, Options.data(),
Options.size(), &pDxil, &pText));
CComPtr<IDxcAssembler> pAssembler;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
CComPtr<IDxcOperationResult> result;
pAssembler->AssembleToContainer(pDxil, &result);
CComPtr<IDxcBlob> pOptimizedContainer;
result->GetResult(&pOptimizedContainer);
return pOptimizedContainer;
}
CComPtr<IDxcBlob> OptimizerTest::RetrievePartFromContainer(IDxcBlob *container,
UINT32 part) {
CComPtr<IDxcContainerReflection> pReflection;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(pReflection->Load(container));
UINT32 dxilIndex;
VERIFY_SUCCEEDED(pReflection->FindFirstPartKind(part, &dxilIndex));
CComPtr<IDxcBlob> blob;
VERIFY_SUCCEEDED(pReflection->GetPartContent(dxilIndex, &blob));
return blob;
}
TEST_F(OptimizerTest, OptimizerWhenPassedContainerPreservesSubobjects) {
const char *source = R"x(
GlobalRootSignature so_GlobalRootSignature =
{
"RootConstants(num32BitConstants=1, b8), "
};
StateObjectConfig so_StateObjectConfig =
{
STATE_OBJECT_FLAGS_ALLOW_LOCAL_DEPENDENCIES_ON_EXTERNAL_DEFINITONS
};
LocalRootSignature so_LocalRootSignature1 =
{
"RootConstants(num32BitConstants=3, b2), "
"UAV(u6),RootFlags(LOCAL_ROOT_SIGNATURE)"
};
LocalRootSignature so_LocalRootSignature2 =
{
"RootConstants(num32BitConstants=3, b2), "
"UAV(u8, flags=DATA_STATIC), "
"RootFlags(LOCAL_ROOT_SIGNATURE)"
};
RaytracingShaderConfig so_RaytracingShaderConfig =
{
128, // max payload size
32 // max attribute size
};
RaytracingPipelineConfig so_RaytracingPipelineConfig =
{
2 // max trace recursion depth
};
TriangleHitGroup MyHitGroup =
{
"MyAnyHit", // AnyHit
"MyClosestHit", // ClosestHit
};
SubobjectToExportsAssociation so_Association1 =
{
"so_LocalRootSignature1", // subobject name
"MyRayGen" // export association
};
SubobjectToExportsAssociation so_Association2 =
{
"so_LocalRootSignature2", // subobject name
"MyAnyHit" // export association
};
struct MyPayload
{
float4 color;
};
[shader("raygeneration")]
void MyRayGen()
{
}
[shader("closesthit")]
void MyClosestHit(inout MyPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
}
[shader("anyhit")]
void MyAnyHit(inout MyPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
}
[shader("miss")]
void MyMiss(inout MyPayload payload)
{
}
)x";
auto pOptimizedContainer =
RunHlslEmitAndReturnContainer(Compile(source, L"", L"lib_6_6"));
auto runtimeDataPart =
RetrievePartFromContainer(pOptimizedContainer, hlsl::DFCC_RuntimeData);
hlsl::RDAT::DxilRuntimeData rdat(
runtimeDataPart->GetBufferPointer(),
static_cast<size_t>(runtimeDataPart->GetBufferSize()));
auto const subObjectTableReader = rdat.GetSubobjectTable();
// There are 9 subobjects in the HLSL above:
VERIFY_ARE_EQUAL(subObjectTableReader.Count(), 9u);
for (uint32_t i = 0; i < subObjectTableReader.Count(); ++i) {
auto subObject = subObjectTableReader[i];
hlsl::DXIL::SubobjectKind subobjectKind = subObject.getKind();
switch (subobjectKind) {
case hlsl::DXIL::SubobjectKind::StateObjectConfig:
VERIFY_ARE_EQUAL_STR(subObject.getName(), "so_StateObjectConfig");
break;
case hlsl::DXIL::SubobjectKind::GlobalRootSignature:
VERIFY_ARE_EQUAL_STR(subObject.getName(), "so_GlobalRootSignature");
break;
case hlsl::DXIL::SubobjectKind::LocalRootSignature:
VERIFY_IS_TRUE(
0 == strcmp(subObject.getName(), "so_LocalRootSignature1") ||
0 == strcmp(subObject.getName(), "so_LocalRootSignature2"));
break;
case hlsl::DXIL::SubobjectKind::SubobjectToExportsAssociation:
VERIFY_IS_TRUE(0 == strcmp(subObject.getName(), "so_Association1") ||
0 == strcmp(subObject.getName(), "so_Association2"));
break;
case hlsl::DXIL::SubobjectKind::RaytracingShaderConfig:
VERIFY_ARE_EQUAL_STR(subObject.getName(), "so_RaytracingShaderConfig");
break;
case hlsl::DXIL::SubobjectKind::RaytracingPipelineConfig:
VERIFY_ARE_EQUAL_STR(subObject.getName(), "so_RaytracingPipelineConfig");
break;
case hlsl::DXIL::SubobjectKind::HitGroup:
VERIFY_ARE_EQUAL_STR(subObject.getName(), "MyHitGroup");
break;
break;
}
}
}
TEST_F(OptimizerTest, OptimizerWhenPassedContainerPreservesRootSig) {
const char *source =
R"(
#define RootSig \
"UAV(u3, space=12), " \
"RootConstants(num32BitConstants=1, b7, space = 42) "
[numthreads(1, 1, 1)]
[RootSignature(RootSig)]
void CSMain(uint3 dispatchThreadID : SV_DispatchThreadID)
{
}
)";
auto pOptimizedContainer =
RunHlslEmitAndReturnContainer(Compile(source, L"CSMain", L"cs_6_6"));
auto rootSigPart =
RetrievePartFromContainer(pOptimizedContainer, hlsl::DFCC_RootSignature);
hlsl::RootSignatureHandle RSH;
RSH.LoadSerialized(
reinterpret_cast<const uint8_t *>(rootSigPart->GetBufferPointer()),
static_cast<uint32_t>(rootSigPart->GetBufferSize()));
RSH.Deserialize();
auto const *desc = RSH.GetDesc();
VERIFY_ARE_EQUAL(desc->Version, hlsl::DxilRootSignatureVersion::Version_1_1);
VERIFY_ARE_EQUAL(desc->Desc_1_1.NumParameters, 2u);
for (unsigned int i = 0; i < desc->Desc_1_1.NumParameters; ++i) {
hlsl::DxilRootParameter1 const *param = desc->Desc_1_1.pParameters + i;
switch (param->ParameterType) {
case hlsl::DxilRootParameterType::Constants32Bit:
VERIFY_ARE_EQUAL(param->Constants.Num32BitValues, 1u);
VERIFY_ARE_EQUAL(param->Constants.RegisterSpace, 42u);
VERIFY_ARE_EQUAL(param->Constants.ShaderRegister, 7u);
break;
case hlsl::DxilRootParameterType::UAV:
VERIFY_ARE_EQUAL(param->Descriptor.RegisterSpace, 12u);
VERIFY_ARE_EQUAL(param->Descriptor.ShaderRegister, 3u);
break;
default:
VERIFY_FAIL(L"Unexpected root param type");
break;
}
}
}
void VerifyIOTablesMatch(PSVDependencyTable original,
PSVDependencyTable optimized) {
VERIFY_ARE_EQUAL(original.IsValid(), optimized.IsValid());
if (original.IsValid()) {
VERIFY_ARE_EQUAL(original.InputVectors, optimized.InputVectors);
VERIFY_ARE_EQUAL(original.OutputVectors, optimized.OutputVectors);
if (original.InputVectors == optimized.InputVectors &&
original.OutputVectors == optimized.OutputVectors &&
original.InputVectors * original.OutputVectors > 0) {
VERIFY_ARE_EQUAL(
0, memcmp(original.Table, optimized.Table,
PSVComputeMaskDwordsFromVectors(original.OutputVectors) *
original.InputVectors * 4 * sizeof(uint32_t)));
}
}
}
void OptimizerTest::ComparePSV0BeforeAndAfterOptimization(
const char *source, const wchar_t *entry, const wchar_t *profile,
bool usesViewId, int streamCount /*= 1*/) {
auto originalContainer = Compile(source, entry, profile);
auto originalPsvPart = RetrievePartFromContainer(
originalContainer, hlsl::DFCC_PipelineStateValidation);
auto optimizedContainer = RunHlslEmitAndReturnContainer(originalContainer);
auto optimizedPsvPart = RetrievePartFromContainer(
optimizedContainer, hlsl::DFCC_PipelineStateValidation);
VERIFY_ARE_EQUAL(originalPsvPart->GetBufferSize(),
optimizedPsvPart->GetBufferSize());
VERIFY_ARE_EQUAL(memcmp(originalPsvPart->GetBufferPointer(),
optimizedPsvPart->GetBufferPointer(),
originalPsvPart->GetBufferSize()),
0);
DxilPipelineStateValidation originalPsv;
originalPsv.InitFromPSV0(
reinterpret_cast<const uint8_t *>(optimizedPsvPart->GetBufferPointer()),
static_cast<uint32_t>(optimizedPsvPart->GetBufferSize()));
const PSVRuntimeInfo1 *originalInfo1 = originalPsv.GetPSVRuntimeInfo1();
if (usesViewId) {
VERIFY_IS_TRUE(originalInfo1->UsesViewID);
}
DxilPipelineStateValidation optimizedPsv;
optimizedPsv.InitFromPSV0(
reinterpret_cast<const uint8_t *>(originalPsvPart->GetBufferPointer()),
static_cast<uint32_t>(originalPsvPart->GetBufferSize()));
const PSVRuntimeInfo1 *optimizedInfo1 = optimizedPsv.GetPSVRuntimeInfo1();
VERIFY_ARE_EQUAL(originalInfo1->ShaderStage, optimizedInfo1->ShaderStage);
VERIFY_ARE_EQUAL(originalInfo1->UsesViewID, optimizedInfo1->UsesViewID);
VERIFY_ARE_EQUAL(originalInfo1->SigInputElements,
optimizedInfo1->SigInputElements);
VERIFY_ARE_EQUAL(originalInfo1->SigOutputElements,
optimizedInfo1->SigOutputElements);
VERIFY_ARE_EQUAL(originalInfo1->SigPatchConstOrPrimElements,
optimizedInfo1->SigPatchConstOrPrimElements);
VERIFY_ARE_EQUAL(originalPsv.GetViewIDPCOutputMask().IsValid(),
optimizedPsv.GetViewIDPCOutputMask().IsValid());
VERIFY_ARE_EQUAL(originalPsv.GetSigInputElements(),
optimizedPsv.GetSigInputElements());
VERIFY_ARE_EQUAL(originalPsv.GetSigOutputElements(),
optimizedPsv.GetSigOutputElements());
if (originalPsv.GetViewIDPCOutputMask().IsValid()) {
VERIFY_ARE_EQUAL(*originalPsv.GetViewIDPCOutputMask().Mask,
*optimizedPsv.GetViewIDPCOutputMask().Mask);
VERIFY_ARE_EQUAL(originalPsv.GetViewIDPCOutputMask().NumVectors,
optimizedPsv.GetViewIDPCOutputMask().NumVectors);
}
for (int stream = 0; stream < streamCount; ++stream) {
VERIFY_ARE_EQUAL(originalInfo1->SigOutputVectors[stream],
optimizedInfo1->SigOutputVectors[stream]);
VERIFY_ARE_EQUAL(originalPsv.GetViewIDOutputMask(stream).IsValid(),
optimizedPsv.GetViewIDOutputMask(stream).IsValid());
VerifyIOTablesMatch(originalPsv.GetInputToOutputTable(),
optimizedPsv.GetInputToOutputTable());
VerifyIOTablesMatch(originalPsv.GetInputToPCOutputTable(),
optimizedPsv.GetInputToPCOutputTable());
VerifyIOTablesMatch(originalPsv.GetPCInputToOutputTable(),
optimizedPsv.GetPCInputToOutputTable());
if (originalPsv.GetViewIDOutputMask(stream).IsValid()) {
VERIFY_ARE_EQUAL(*originalPsv.GetViewIDOutputMask(stream).Mask,
*optimizedPsv.GetViewIDOutputMask(stream).Mask);
VERIFY_ARE_EQUAL(originalPsv.GetViewIDOutputMask(stream).NumVectors,
optimizedPsv.GetViewIDOutputMask(stream).NumVectors);
}
}
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_HSDependentPCDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
#define NumOutPoints 2
struct HsCpIn {
int foo : FOO;
};
struct HsCpOut {
int bar : BAR;
};
struct HsPcfOut {
float tessOuter[4] : SV_TessFactor;
float tessInner[2] : SV_InsideTessFactor;
};
// Patch Constant Function
HsPcfOut pcf(uint viewid : SV_ViewID) {
HsPcfOut output;
output = (HsPcfOut)viewid;
return output;
}
[domain("quad")]
[partitioning("fractional_odd")]
[outputtopology("triangle_ccw")]
[outputcontrolpoints(NumOutPoints)]
[patchconstantfunc("pcf")]
HsCpOut main(InputPatch<HsCpIn, NumOutPoints> patch,
uint id : SV_OutputControlPointID,
uint viewid : SV_ViewID) {
HsCpOut output;
output.bar = viewid;
return output;
}
)",
L"main", L"hs_6_6", true);
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_HSNonDependentPCDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
#define NumOutPoints 2
struct HsCpIn {
int foo : FOO;
};
struct HsCpOut {
int bar : BAR;
};
struct HsPcfOut {
float tessOuter[4] : SV_TessFactor;
float tessInner[2] : SV_InsideTessFactor;
};
// Patch Constant Function
HsPcfOut pcf(uint viewid : SV_ViewID) {
HsPcfOut output;
output = (HsPcfOut)viewid;
return output;
}
[domain("quad")]
[partitioning("fractional_odd")]
[outputtopology("triangle_ccw")]
[outputcontrolpoints(NumOutPoints)]
[patchconstantfunc("pcf")]
HsCpOut main(InputPatch<HsCpIn, NumOutPoints> patch,
uint id : SV_OutputControlPointID,
uint viewid : SV_ViewID) {
HsCpOut output;
output.bar = 0;
return output;
}
)",
L"main", L"hs_6_6", true);
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_HSDependentPCNonDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
#define NumOutPoints 2
struct HsCpIn {
int foo : FOO;
};
struct HsCpOut {
int bar : BAR;
};
struct HsPcfOut {
float tessOuter[4] : SV_TessFactor;
float tessInner[2] : SV_InsideTessFactor;
};
// Patch Constant Function
HsPcfOut pcf(uint viewid : SV_ViewID) {
HsPcfOut output;
output = (HsPcfOut)0;
return output;
}
[domain("quad")]
[partitioning("fractional_odd")]
[outputtopology("triangle_ccw")]
[outputcontrolpoints(NumOutPoints)]
[patchconstantfunc("pcf")]
HsCpOut main(InputPatch<HsCpIn, NumOutPoints> patch,
uint id : SV_OutputControlPointID,
uint viewid : SV_ViewID) {
HsCpOut output;
output.bar = viewid;
return output;
}
)",
L"main", L"hs_6_6", true);
}
TEST_F(
OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_HSNonDependentPCNonDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
#define NumOutPoints 2
struct HsCpIn {
int foo : FOO;
};
struct HsCpOut {
int bar : BAR;
};
struct HsPcfOut {
float tessOuter[4] : SV_TessFactor;
float tessInner[2] : SV_InsideTessFactor;
};
// Patch Constant Function
HsPcfOut pcf(uint viewid : SV_ViewID) {
HsPcfOut output;
output = (HsPcfOut)0;
return output;
}
[domain("quad")]
[partitioning("fractional_odd")]
[outputtopology("triangle_ccw")]
[outputcontrolpoints(NumOutPoints)]
[patchconstantfunc("pcf")]
HsCpOut main(InputPatch<HsCpIn, NumOutPoints> patch,
uint id : SV_OutputControlPointID,
uint viewid : SV_ViewID) {
HsCpOut output;
output.bar = 0;
return output;
}
)",
L"main", L"hs_6_6", false /*does not use view id*/);
}
TEST_F(OptimizerTest, OptimizerWhenPassedContainerPreservesViewId_MSDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
#define MAX_VERT 32
#define MAX_PRIM 16
#define NUM_THREADS 32
struct MeshPerVertex {
float4 position : SV_Position;
float color[4] : COLOR;
};
struct MeshPerPrimitive {
float normal : NORMAL;
float malnor : MALNOR;
float alnorm : ALNORM;
float ormaln : ORMALN;
int layer[6] : LAYER;
};
struct MeshPayload {
float normal;
float malnor;
float alnorm;
float ormaln;
int layer[6];
};
groupshared float gsMem[MAX_PRIM];
[numthreads(NUM_THREADS, 1, 1)]
[outputtopology("triangle")]
void main(
out indices uint3 primIndices[MAX_PRIM],
out vertices MeshPerVertex verts[MAX_VERT],
out primitives MeshPerPrimitive prims[MAX_PRIM],
in payload MeshPayload mpl,
in uint tig : SV_GroupIndex,
in uint vid : SV_ViewID
)
{
SetMeshOutputCounts(MAX_VERT, MAX_PRIM);
MeshPerVertex ov;
if (vid % 2) {
ov.position = float4(4.0,5.0,6.0,7.0);
ov.color[0] = 4.0;
ov.color[1] = 5.0;
ov.color[2] = 6.0;
ov.color[3] = 7.0;
} else {
ov.position = float4(14.0,15.0,16.0,17.0);
ov.color[0] = 14.0;
ov.color[1] = 15.0;
ov.color[2] = 16.0;
ov.color[3] = 17.0;
}
if (tig % 3) {
primIndices[tig / 3] = uint3(tig, tig + 1, tig + 2);
MeshPerPrimitive op;
op.normal = mpl.normal;
op.malnor = gsMem[tig / 3 + 1];
op.alnorm = mpl.alnorm;
op.ormaln = mpl.ormaln;
op.layer[0] = mpl.layer[0];
op.layer[1] = mpl.layer[1];
op.layer[2] = mpl.layer[2];
op.layer[3] = mpl.layer[3];
op.layer[4] = mpl.layer[4];
op.layer[5] = mpl.layer[5];
gsMem[tig / 3] = op.normal;
prims[tig / 3] = op;
}
verts[tig] = ov;
}
)",
L"main", L"ms_6_5", true /*does use view id*/);
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_MSNonDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
#define MAX_VERT 32
#define MAX_PRIM 16
#define NUM_THREADS 32
struct MeshPerVertex {
float4 position : SV_Position;
float color[4] : COLOR;
};
struct MeshPerPrimitive {
float normal : NORMAL;
float malnor : MALNOR;
float alnorm : ALNORM;
float ormaln : ORMALN;
int layer[6] : LAYER;
};
struct MeshPayload {
float normal;
float malnor;
float alnorm;
float ormaln;
int layer[6];
};
groupshared float gsMem[MAX_PRIM];
[numthreads(NUM_THREADS, 1, 1)]
[outputtopology("triangle")]
void main(
out indices uint3 primIndices[MAX_PRIM],
out vertices MeshPerVertex verts[MAX_VERT],
out primitives MeshPerPrimitive prims[MAX_PRIM],
in payload MeshPayload mpl,
in uint tig : SV_GroupIndex,
in uint vid : SV_ViewID
)
{
SetMeshOutputCounts(MAX_VERT, MAX_PRIM);
MeshPerVertex ov;
if (false) {
ov.position = float4(4.0,5.0,6.0,7.0);
ov.color[0] = 4.0;
ov.color[1] = 5.0;
ov.color[2] = 6.0;
ov.color[3] = 7.0;
} else {
ov.position = float4(14.0,15.0,16.0,17.0);
ov.color[0] = 14.0;
ov.color[1] = 15.0;
ov.color[2] = 16.0;
ov.color[3] = 17.0;
}
if (tig % 3) {
primIndices[tig / 3] = uint3(tig, tig + 1, tig + 2);
MeshPerPrimitive op;
op.normal = mpl.normal;
op.malnor = gsMem[tig / 3 + 1];
op.alnorm = mpl.alnorm;
op.ormaln = mpl.ormaln;
op.layer[0] = mpl.layer[0];
op.layer[1] = mpl.layer[1];
op.layer[2] = mpl.layer[2];
op.layer[3] = mpl.layer[3];
op.layer[4] = mpl.layer[4];
op.layer[5] = mpl.layer[5];
gsMem[tig / 3] = op.normal;
prims[tig / 3] = op;
}
verts[tig] = ov;
}
)",
L"main", L"ms_6_5", false /*does not use view id*/);
}
TEST_F(OptimizerTest, OptimizerWhenPassedContainerPreservesViewId_DSDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
struct PSInput
{
float4 position : SV_POSITION;
float4 color : COLOR;
};
struct HS_CONSTANT_DATA_OUTPUT
{
float Edges[3] : SV_TessFactor;
float Inside : SV_InsideTessFactor;
};
struct BEZIER_CONTROL_POINT
{
float3 vPosition : BEZIERPOS;
float4 color : COLOR;
};
[domain("tri")]
PSInput DSMain(HS_CONSTANT_DATA_OUTPUT input,
float3 UV : SV_DomainLocation,
uint viewID : SV_ViewID,
const OutputPatch<BEZIER_CONTROL_POINT, 3> bezpatch)
{
PSInput Output;
Output.position = float4(
bezpatch[0].vPosition * UV.x + viewID +
bezpatch[1].vPosition * UV.y +
bezpatch[2].vPosition * UV.z
,1);
Output.color = float4(
bezpatch[0].color * UV.x +
bezpatch[1].color * UV.y +
bezpatch[2].color * UV.z
);
return Output;
}
)",
L"DSMain", L"ds_6_5", true /*does use view id*/);
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_DSNonDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
struct PSInput
{
float4 position : SV_POSITION;
float4 color : COLOR;
};
struct HS_CONSTANT_DATA_OUTPUT
{
float Edges[3] : SV_TessFactor;
float Inside : SV_InsideTessFactor;
};
struct BEZIER_CONTROL_POINT
{
float3 vPosition : BEZIERPOS;
float4 color : COLOR;
};
[domain("tri")]
PSInput DSMain(HS_CONSTANT_DATA_OUTPUT input,
float3 UV : SV_DomainLocation,
uint viewID : SV_ViewID,
const OutputPatch<BEZIER_CONTROL_POINT, 3> bezpatch)
{
PSInput Output;
Output.position = float4(
bezpatch[0].vPosition * UV.x +
bezpatch[1].vPosition * UV.y +
bezpatch[2].vPosition * UV.z
,1);
Output.color = float4(
bezpatch[0].color * UV.x +
bezpatch[1].color * UV.y +
bezpatch[2].color * UV.z
);
return Output;
}
)",
L"DSMain", L"ds_6_5", false /*does not use view id*/);
}
TEST_F(OptimizerTest, OptimizerWhenPassedContainerPreservesViewId_VSDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
struct VertexShaderInput
{
float3 pos : POSITION;
float3 color : COLOR0;
uint viewID : SV_ViewID;
};
struct VertexShaderOutput
{
float4 pos : SV_POSITION;
float3 color : COLOR0;
};
VertexShaderOutput main(VertexShaderInput input)
{
VertexShaderOutput output;
output.pos = float4(input.pos, 1.0f);
if (input.viewID % 2) {
output.color = float3(1.0f, 0.0f, 1.0f);
} else {
output.color = float3(0.0f, 1.0f, 0.0f);
}
return output;
}
)",
L"main", L"vs_6_5", true /*does use view id*/);
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_VSNonDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
struct VertexShaderInput
{
float3 pos : POSITION;
float3 color : COLOR0;
uint viewID : SV_ViewID;
};
struct VertexShaderOutput
{
float4 pos : SV_POSITION;
float3 color : COLOR0;
};
VertexShaderOutput main(VertexShaderInput input)
{
VertexShaderOutput output;
output.pos = float4(input.pos, 1.0f);
if (false) {
output.color = float3(1.0f, 0.0f, 1.0f);
} else {
output.color = float3(0.0f, 1.0f, 0.0f);
}
return output;
}
)",
L"main", L"vs_6_5", false /*does not use view id*/);
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesViewId_GSNonDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
struct MyStructIn
{
// float4 pos : SV_Position;
float4 a : AAA;
float2 b : BBB;
float4 c[3] : CCC;
//uint d : SV_RenderTargetIndex;
float4 pos : SV_Position;
};
struct MyStructOut
{
float4 pos : SV_Position;
float2 out_a : OUT_AAA;
uint d : SV_RenderTargetArrayIndex;
};
[maxvertexcount(18)]
void main(triangleadj MyStructIn array[6], inout TriangleStream<MyStructOut> OutputStream0)
{
float4 r = array[1].a + array[2].b.x + array[3].pos;
r += array[r.x].c[r.y].w;
MyStructOut output = (MyStructOut)0;
output.pos = array[r.x].a;
output.out_a = array[r.y].b;
output.d = array[r.x].a + 3;
OutputStream0.Append(output);
OutputStream0.RestartStrip();
}
)",
L"main", L"gs_6_5", false /*does not use view id*/);
}
TEST_F(OptimizerTest, OptimizerWhenPassedContainerPreservesViewId_GSDependent) {
ComparePSV0BeforeAndAfterOptimization(
R"(
struct MyStructIn
{
// float4 pos : SV_Position;
float4 a : AAA;
float2 b : BBB;
float4 c[3] : CCC;
float4 pos : SV_Position;
};
struct MyStructOut
{
float4 pos : SV_Position;
float2 out_a : OUT_AAA;
uint d : SV_RenderTargetArrayIndex;
};
[maxvertexcount(18)]
void main(triangleadj MyStructIn array[6], inout TriangleStream<MyStructOut> OutputStream0, uint viewid : SV_ViewID)
{
float4 r = array[1].a + array[2].b.x + array[3].pos;
r += array[r.x].c[r.y].w + viewid;
MyStructOut output = (MyStructOut)0;
output.pos = array[r.x].a;
output.out_a = array[r.y].b;
output.d = array[r.x].a + 3;
OutputStream0.Append(output);
OutputStream0.RestartStrip();
}
)",
L"main", L"gs_6_5", true /*does use view id*/, 4);
}
using namespace llvm;
using namespace hlsl;
static std::unique_ptr<llvm::Module>
GetDxilModuleFromStatsBlobInContainer(LLVMContext &Context, IDxcBlob *pBlob) {
const char *pBlobContent =
reinterpret_cast<const char *>(pBlob->GetBufferPointer());
unsigned blobSize = pBlob->GetBufferSize();
const DxilContainerHeader *pContainerHeader =
IsDxilContainerLike(pBlobContent, blobSize);
const DxilPartHeader *pPartHeader =
GetDxilPartByType(pContainerHeader, DFCC_ShaderStatistics);
const DxilProgramHeader *pReflProgramHeader =
reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(pPartHeader));
(void)IsValidDxilProgramHeader(pReflProgramHeader, pPartHeader->PartSize);
const char *pReflBitcode;
uint32_t reflBitcodeLength;
GetDxilProgramBitcode((const DxilProgramHeader *)pReflProgramHeader,
&pReflBitcode, &reflBitcodeLength);
std::string DiagStr;
return hlsl::dxilutil::LoadModuleFromBitcode(
llvm::StringRef(pReflBitcode, reflBitcodeLength), Context, DiagStr);
}
template <typename ResourceType>
void CompareResources(const vector<unique_ptr<ResourceType>> &original,
const vector<unique_ptr<ResourceType>> &optimized) {
VERIFY_ARE_EQUAL(original.size(), optimized.size());
for (size_t i = 0; i < original.size(); ++i) {
auto const &originalRes = original.at(i);
auto const &optimizedRes = optimized.at(i);
VERIFY_ARE_EQUAL(originalRes->GetClass(), optimizedRes->GetClass());
VERIFY_ARE_EQUAL(originalRes->GetGlobalName(),
optimizedRes->GetGlobalName());
if (originalRes->GetGlobalSymbol() != nullptr &&
optimizedRes->GetGlobalSymbol() != nullptr) {
VERIFY_ARE_EQUAL(originalRes->GetGlobalSymbol()->getName(),
optimizedRes->GetGlobalSymbol()->getName());
}
if (originalRes->GetHLSLType() != nullptr &&
optimizedRes->GetHLSLType() != nullptr) {
VERIFY_ARE_EQUAL(originalRes->GetHLSLType()->getTypeID(),
optimizedRes->GetHLSLType()->getTypeID());
if (originalRes->GetHLSLType()->getTypeID() == Type::PointerTyID) {
auto originalPointedType =
originalRes->GetHLSLType()->getArrayElementType();
auto optimizedPointedType =
optimizedRes->GetHLSLType()->getArrayElementType();
VERIFY_ARE_EQUAL(originalPointedType->getTypeID(),
optimizedPointedType->getTypeID());
if (optimizedPointedType->getTypeID() == Type::StructTyID) {
VERIFY_ARE_EQUAL(originalPointedType->getStructName(),
optimizedPointedType->getStructName());
}
}
}
VERIFY_ARE_EQUAL(originalRes->GetID(), optimizedRes->GetID());
VERIFY_ARE_EQUAL(originalRes->GetKind(), optimizedRes->GetKind());
VERIFY_ARE_EQUAL(originalRes->GetLowerBound(),
optimizedRes->GetLowerBound());
VERIFY_ARE_EQUAL(originalRes->GetRangeSize(), optimizedRes->GetRangeSize());
VERIFY_ARE_EQUAL(originalRes->GetSpaceID(), optimizedRes->GetSpaceID());
VERIFY_ARE_EQUAL(originalRes->GetUpperBound(),
optimizedRes->GetUpperBound());
}
}
void OptimizerTest::CompareSTATBeforeAndAfterOptimization(
const char *source, const wchar_t *entry, const wchar_t *profile,
bool usesViewId, int streamCount /*= 1*/) {
auto originalContainer = Compile(source, entry, profile);
auto optimizedContainer = RunHlslEmitAndReturnContainer(originalContainer);
::llvm::sys::fs::MSFileSystem *msfPtr;
IFT(CreateMSFileSystemForDisk(&msfPtr));
std::unique_ptr<::llvm::sys::fs::MSFileSystem> msf(msfPtr);
::llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
LLVMContext originalContext, optimizedContext;
auto originalStatModule =
GetDxilModuleFromStatsBlobInContainer(originalContext, originalContainer);
auto optimizedStatModule = GetDxilModuleFromStatsBlobInContainer(
optimizedContext, optimizedContainer);
auto &originalDM = originalStatModule->GetOrCreateDxilModule();
auto &optimizeDM = optimizedStatModule->GetOrCreateDxilModule();
CompareResources(originalDM.GetCBuffers(), optimizeDM.GetCBuffers());
CompareResources(originalDM.GetSRVs(), optimizeDM.GetSRVs());
CompareResources(originalDM.GetUAVs(), optimizeDM.GetUAVs());
CompareResources(originalDM.GetSamplers(), optimizeDM.GetSamplers());
}
TEST_F(OptimizerTest,
OptimizerWhenPassedContainerPreservesResourceStats_PSMultiCBTex2D) {
CompareSTATBeforeAndAfterOptimization(
R"(
#define MOD4(x) ((x)&3)
#ifndef MAX_POINTS
#define MAX_POINTS 32
#endif
#define MAX_BONE_MATRICES 80
//--------------------------------------------------------------------------------------
// Textures
//--------------------------------------------------------------------------------------
Texture2D g_txHeight : register( t0 ); // Height and Bump texture
Texture2D g_txDiffuse : register( t1 ); // Diffuse texture
Texture2D g_txSpecular : register( t2 ); // Specular texture
//--------------------------------------------------------------------------------------
// Samplers
//--------------------------------------------------------------------------------------
SamplerState g_samLinear : register( s0 );
SamplerState g_samPoint : register( s0 );
//--------------------------------------------------------------------------------------
// Constant Buffers
//--------------------------------------------------------------------------------------
cbuffer cbTangentStencilConstants : register( b0 )
{
float g_TanM[1024]; // Tangent patch stencils precomputed by the application
float g_fCi[16]; // Valence coefficients precomputed by the application
};
cbuffer cbPerMesh : register( b1 )
{
matrix g_mConstBoneWorld[MAX_BONE_MATRICES];
};
cbuffer cbPerFrame : register( b2 )
{
matrix g_mViewProjection;
float3 g_vCameraPosWorld;
float g_fTessellationFactor;
float g_fDisplacementHeight;
float3 g_vSolidColor;
};
cbuffer cbPerSubset : register( b3 )
{
int g_iPatchStartIndex;
}
//--------------------------------------------------------------------------------------
Buffer<uint4> g_ValencePrefixBuffer : register( t0 );
//--------------------------------------------------------------------------------------
struct VS_CONTROL_POINT_OUTPUT
{
float3 vPosition : WORLDPOS;
float2 vUV : TEXCOORD0;
float3 vTangent : TANGENT;
};
struct BEZIER_CONTROL_POINT
{
float3 vPosition : BEZIERPOS;
};
struct PS_INPUT
{
float3 vWorldPos : POSITION;
float3 vNormal : NORMAL;
float2 vUV : TEXCOORD;
float3 vTangent : TANGENT;
float3 vBiTangent : BITANGENT;
};
//--------------------------------------------------------------------------------------
// Smooth shading pixel shader section
//--------------------------------------------------------------------------------------
float3 safe_normalize( float3 vInput )
{
float len2 = dot( vInput, vInput );
if( len2 > 0 )
{
return vInput * rsqrt( len2 );
}
return vInput;
}
static const float g_fSpecularExponent = 32.0f;
static const float g_fSpecularIntensity = 0.6f;
static const float g_fNormalMapIntensity = 1.5f;
float2 ComputeDirectionalLight( float3 vWorldPos, float3 vWorldNormal, float3 vDirLightDir )
{
// Result.x is diffuse illumination, Result.y is specular illumination
float2 Result = float2( 0, 0 );
Result.x = pow( saturate( dot( vWorldNormal, -vDirLightDir ) ), 2 );
float3 vPointToCamera = normalize( g_vCameraPosWorld - vWorldPos );
float3 vHalfAngle = normalize( vPointToCamera - vDirLightDir );
Result.y = pow( saturate( dot( vHalfAngle, vWorldNormal ) ), g_fSpecularExponent );
return Result;
}
float3 ColorGamma( float3 Input )
{
return pow( Input, 2.2f );
}
float4 main( PS_INPUT Input ) : SV_TARGET
{
float4 vNormalMapSampleRaw = g_txHeight.Sample( g_samLinear, Input.vUV );
float3 vNormalMapSampleBiased = ( vNormalMapSampleRaw.xyz * 2 ) - 1;
vNormalMapSampleBiased.xy *= g_fNormalMapIntensity;
float3 vNormalMapSample = normalize( vNormalMapSampleBiased );
float3 vNormal = safe_normalize( Input.vNormal ) * vNormalMapSample.z;
vNormal += safe_normalize( Input.vTangent ) * vNormalMapSample.x;
vNormal += safe_normalize( Input.vBiTangent ) * vNormalMapSample.y;
//float3 vColor = float3( 1, 1, 1 );
float3 vColor = g_txDiffuse.Sample( g_samLinear, Input.vUV ).rgb;
float vSpecular = g_txSpecular.Sample( g_samLinear, Input.vUV ).r * g_fSpecularIntensity;
const float3 DirLightDirections[4] =
{
// key light
normalize( float3( -63.345150, -58.043934, 27.785097 ) ),
// fill light
normalize( float3( 23.652107, -17.391443, 54.972504 ) ),
// back light 1
normalize( float3( 20.470509, -22.939510, -33.929531 ) ),
// back light 2
normalize( float3( -31.003685, 24.242104, -41.352859 ) ),
};
const float3 DirLightColors[4] =
{
// key light
ColorGamma( float3( 1.0f, 0.964f, 0.706f ) * 1.0f ),
// fill light
ColorGamma( float3( 0.446f, 0.641f, 1.0f ) * 1.0f ),
// back light 1
ColorGamma( float3( 1.0f, 0.862f, 0.419f ) * 1.0f ),
// back light 2
ColorGamma( float3( 0.405f, 0.630f, 1.0f ) * 1.0f ),
};
float3 fLightColor = 0;
for( int i = 0; i < 4; ++i )
{
float2 LightDiffuseSpecular = ComputeDirectionalLight( Input.vWorldPos, vNormal, DirLightDirections[i] );
fLightColor += DirLightColors[i] * vColor * LightDiffuseSpecular.x;
fLightColor += DirLightColors[i] * LightDiffuseSpecular.y * vSpecular;
}
return float4( fLightColor, 1 );
}
)",
L"main", L"ps_6_5", false /*does not use view id*/, 4);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/VerifierTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// VerifierTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/CompilationResult.h"
#include "dxc/Test/HLSLTestData.h"
#include <memory>
#include <string>
#include <vector>
#include <fstream>
#ifdef _WIN32
#define TEST_CLASS_DERIVATION
#else
#define TEST_CLASS_DERIVATION : public ::testing::Test
#endif
#include "dxc/Test/HlslTestUtils.h"
using namespace std;
// The test fixture.
class VerifierTest TEST_CLASS_DERIVATION {
public:
BEGIN_TEST_CLASS(VerifierTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_METHOD(RunCppErrors)
TEST_METHOD(RunCppErrorsHV2015)
void CheckVerifies(const wchar_t *path) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
const char startMarker[] = "%clang_cc1";
const char endMarker[] = "%s";
// I bumped this up to 1024, if we have a run line that large in our tests
// bad will happen, and we probably deserve the pain...
char firstLine[1024];
memset(firstLine, 0, sizeof(firstLine));
char *commandLine;
//
// Very simple processing for now.
// See utils\lit\lit\TestRunner.py for the more thorough implementation.
//
// The first line for HLSL tests will always look like this:
// // RUN: %clang_cc1 -fsyntax-only -Wno-unused-value -ffreestanding -verify
// %s
//
// We turn this into ' -fsyntax-only -Wno-unused-value -ffreestanding
// -verify ' by offseting after %clang_cc1 and chopping off everything after
// '%s'.
//
ifstream infile(CW2A(path).m_psz);
ASSERT_EQ(false, infile.bad());
bool FoundRun = false;
// This loop is super hacky, and not at all how we should do this. We should
// have _one_ implementation of reading and interpreting RUN but instead we
// currently have many, and this one only supports one RUN directive, which
// is confusing and has resulted in test cases that aren't being run at all,
// and are hiding bugs.
// The goal of this loop is to process RUN lines at the top of the file,
// until the first non-run line. This also isn't ideal, but is better.
while (!infile.eof()) {
infile.getline(firstLine, _countof(firstLine));
char *found = strstr(firstLine, startMarker);
if (found)
FoundRun = true;
else
break;
commandLine = found + strlen(startMarker);
char *fileArgument = strstr(commandLine, endMarker);
ASSERT_NE(nullptr, fileArgument);
*fileArgument = '\0';
CW2A asciiPath(path);
CompilationResult result =
CompilationResult::CreateForCommandLine(commandLine, asciiPath);
if (!result.ParseSucceeded()) {
std::stringstream ss;
ss << "for program " << asciiPath << " with errors:\n"
<< result.GetTextForErrors();
CA2W pszW(ss.str().c_str());
::WEX::Logging::Log::Comment(pszW);
}
VERIFY_IS_TRUE(result.ParseSucceeded());
}
ASSERT_EQ(true, FoundRun);
}
void CheckVerifiesHLSL(LPCWSTR name) {
// Having a test per file makes it very easy to filter from the command
// line.
CheckVerifies(hlsl_test::GetPathToHlslDataFile(name).c_str());
}
};
TEST_F(VerifierTest, RunCppErrors) { CheckVerifiesHLSL(L"cpp-errors.hlsl"); }
TEST_F(VerifierTest, RunCppErrorsHV2015) {
CheckVerifiesHLSL(L"cpp-errors-hv2015.hlsl");
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/ExtensionTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// ExtensionTest.cpp //
// //
// Provides tests for the language extension APIs. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/HLSL/HLOperationLowerExtension.h"
#include "dxc/HlslIntrinsicOp.h"
#include "dxc/Support/microcom.h"
#include "dxc/Test/CompilationResult.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/dxcapi.internal.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Regex.h"
///////////////////////////////////////////////////////////////////////////////
// Support for test intrinsics.
// $result = test_fn(any_vector<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT TestFnArgs[] = {
{"test_fn", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
// void test_proc(any_vector<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT TestProcArgs[] = {
{"test_proc", 0, 0, LITEMPLATE_VOID, 0, LICOMPTYPE_VOID, 0, 0},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
// $result = test_poly(any_vector<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT TestFnCustomArgs[] = {
{"test_poly", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1,
IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
// $result = test_int(int<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT TestFnIntArgs[] = {
{"test_int", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_INT, 1, IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_INT, 1, IA_C}};
// $result = test_nolower(any_vector<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT TestFnNoLowerArgs[] = {
{"test_nolower", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1,
IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
// void test_pack_0(any_vector<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT TestFnPack0[] = {
{"test_pack_0", 0, 0, LITEMPLATE_VOID, 0, LICOMPTYPE_VOID, 0, 0},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
// $result = test_pack_1()
static const HLSL_INTRINSIC_ARGUMENT TestFnPack1[] = {
{"test_pack_1", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_FLOAT, 1,
2},
};
// $result = test_pack_2(any_vector<any_cardinality> value1,
// any_vector<any_cardinality> value2)
static const HLSL_INTRINSIC_ARGUMENT TestFnPack2[] = {
{"test_pack_2", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1,
IA_C},
{"value1", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C},
{"value2", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C},
};
// $scalar = test_pack_3(any_vector<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT TestFnPack3[] = {
{"test_pack_3", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_FLOAT, 1,
1},
{"value1", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_FLOAT, 1, 2},
};
// float<2> = test_pack_4(float<3> value)
static const HLSL_INTRINSIC_ARGUMENT TestFnPack4[] = {
{"test_pack_4", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_FLOAT, 1,
2},
{"value", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_FLOAT, 1, 3},
};
// float<2> = test_rand()
static const HLSL_INTRINSIC_ARGUMENT TestRand[] = {
{"test_rand", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_FLOAT, 1, 2},
};
// uint = test_rand(uint x)
static const HLSL_INTRINSIC_ARGUMENT TestUnsigned[] = {
{"test_unsigned", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_UINT, 1,
1},
{"x", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 1},
};
// float2 = MyBufferOp(uint2 addr)
static const HLSL_INTRINSIC_ARGUMENT TestMyBufferOp[] = {
{"MyBufferOp", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_FLOAT, 1,
2},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 2},
};
// float2 = CustomLoadOp(uint2 addr)
static const HLSL_INTRINSIC_ARGUMENT TestCustomLoadOp[] = {
{"CustomLoadOp", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_FLOAT, 1,
2},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 2},
};
// float2 = CustomLoadOp(uint2 addr, bool val)
static const HLSL_INTRINSIC_ARGUMENT TestCustomLoadOpBool[] = {
{"CustomLoadOp", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_FLOAT, 1,
2},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 2},
{"val", AR_QUAL_IN, 2, LITEMPLATE_SCALAR, 2, LICOMPTYPE_BOOL, 1, 1},
};
// float2 = CustomLoadOp(uint2 addr, bool val, uint2 subscript)
static const HLSL_INTRINSIC_ARGUMENT TestCustomLoadOpSubscript[] = {
{"CustomLoadOp", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_FLOAT, 1,
2},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 2},
{"val", AR_QUAL_IN, 2, LITEMPLATE_SCALAR, 2, LICOMPTYPE_BOOL, 1, 1},
{"subscript", AR_QUAL_IN, 3, LITEMPLATE_VECTOR, 3, LICOMPTYPE_UINT, 1, 2},
};
// bool<> = test_isinf(float<> x)
static const HLSL_INTRINSIC_ARGUMENT TestIsInf[] = {
{"test_isinf", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_BOOL, 1,
IA_C},
{"x", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_FLOAT, 1, IA_C},
};
// int = test_ibfe(uint width, uint offset, uint val)
static const HLSL_INTRINSIC_ARGUMENT TestIBFE[] = {
{"test_ibfe", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_INT, 1, 1},
{"width", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
{"offset", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
{"val", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
};
// float2 = MySamplerOp(uint2 addr)
static const HLSL_INTRINSIC_ARGUMENT TestMySamplerOp[] = {
{"MySamplerOp", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_FLOAT, 1,
2},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 2},
};
// $result = wave_proc(any_vector<any_cardinality> value)
static const HLSL_INTRINSIC_ARGUMENT WaveProcArgs[] = {
{"wave_proc", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1,
IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
// uint = Texutre1D.MyTextureOp(uint addr, uint offset)
static const HLSL_INTRINSIC_ARGUMENT TestMyTexture1DOp_0[] = {
{"MyTextureOp", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_UINT, 1,
1},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
{"offset", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
};
// uint = Texutre1D.MyTextureOp(uint addr, uint offset, uint val)
static const HLSL_INTRINSIC_ARGUMENT TestMyTexture1DOp_1[] = {
{"MyTextureOp", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_UINT, 1,
1},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
{"offset", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
{"val", AR_QUAL_IN, 1, LITEMPLATE_SCALAR, 1, LICOMPTYPE_UINT, 1, 1},
};
// uint2 = Texture2D.MyTextureOp(uint2 addr, uint2 val)
static const HLSL_INTRINSIC_ARGUMENT TestMyTexture2DOp[] = {
{"MyTextureOp", AR_QUAL_OUT, 0, LITEMPLATE_VECTOR, 0, LICOMPTYPE_UINT, 1,
1},
{"addr", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 2},
{"val", AR_QUAL_IN, 1, LITEMPLATE_VECTOR, 1, LICOMPTYPE_UINT, 1, 2},
};
// float = test_overload(float a, uint b, double c)
static const HLSL_INTRINSIC_ARGUMENT TestOverloadArgs[] = {
{"test_overload", AR_QUAL_OUT, 0, LITEMPLATE_SCALAR, 0, LICOMPTYPE_NUMERIC,
1, IA_C},
{"a", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_FLOAT, 1, IA_C},
{"b", AR_QUAL_IN, 2, LITEMPLATE_ANY, 2, LICOMPTYPE_UINT, 1, IA_C},
{"c", AR_QUAL_IN, 3, LITEMPLATE_SCALAR, 3, LICOMPTYPE_DOUBLE, 1, IA_C},
};
struct Intrinsic {
LPCWSTR hlslName;
const char *dxilName;
const char *strategy;
HLSL_INTRINSIC hlsl;
};
const char *DEFAULT_NAME = "";
// llvm::array_lengthof that returns a UINT instead of size_t
template <class T, std::size_t N> UINT countof(T (&)[N]) {
return static_cast<UINT>(N);
}
Intrinsic Intrinsics[] = {
{L"test_fn",
DEFAULT_NAME,
"r",
{1, false, true, false, -1, countof(TestFnArgs), TestFnArgs}},
{L"test_proc",
DEFAULT_NAME,
"r",
{2, false, false, false, -1, countof(TestProcArgs), TestProcArgs}},
{L"test_poly",
"test_poly.$o",
"r",
{3, false, true, false, -1, countof(TestFnCustomArgs), TestFnCustomArgs}},
{L"test_int",
"test_int",
"r",
{4, false, true, false, -1, countof(TestFnIntArgs), TestFnIntArgs}},
{L"test_nolower",
"test_nolower.$o",
"n",
{5, false, true, false, -1, countof(TestFnNoLowerArgs),
TestFnNoLowerArgs}},
{L"test_pack_0",
"test_pack_0.$o",
"p",
{6, false, false, false, -1, countof(TestFnPack0), TestFnPack0}},
{L"test_pack_1",
"test_pack_1.$o",
"p",
{7, false, true, false, -1, countof(TestFnPack1), TestFnPack1}},
{L"test_pack_2",
"test_pack_2.$o",
"p",
{8, false, true, false, -1, countof(TestFnPack2), TestFnPack2}},
{L"test_pack_3",
"test_pack_3.$o",
"p",
{9, false, true, false, -1, countof(TestFnPack3), TestFnPack3}},
{L"test_pack_4",
"test_pack_4.$o",
"p",
{10, false, false, false, -1, countof(TestFnPack4), TestFnPack4}},
{L"test_rand",
"test_rand",
"r",
{11, false, false, false, -1, countof(TestRand), TestRand}},
{L"test_isinf",
"test_isinf",
"d",
{13, true, true, false, -1, countof(TestIsInf), TestIsInf}},
{L"test_ibfe",
"test_ibfe",
"d",
{14, true, true, false, -1, countof(TestIBFE), TestIBFE}},
// Make this intrinsic have the same opcode as an hlsl intrinsic with an
// unsigned counterpart for testing purposes.
{L"test_unsigned",
"test_unsigned",
"n",
{static_cast<unsigned>(hlsl::IntrinsicOp::IOP_min), false, true, false, -1,
countof(TestUnsigned), TestUnsigned}},
{L"wave_proc",
DEFAULT_NAME,
"r",
{16, false, true, true, -1, countof(WaveProcArgs), WaveProcArgs}},
{L"test_o_1",
"test_o_1.$o:1",
"r",
{18, false, true, true, -1, countof(TestOverloadArgs), TestOverloadArgs}},
{L"test_o_2",
"test_o_2.$o:2",
"r",
{19, false, true, true, -1, countof(TestOverloadArgs), TestOverloadArgs}},
{L"test_o_3",
"test_o_3.$o:3",
"r",
{20, false, true, true, -1, countof(TestOverloadArgs), TestOverloadArgs}},
// custom lowering with both optional arguments and vector exploding.
// Arg 0 = Opcode
// Arg 1 = Pass as is
// Arg 2:?i1 = Optional boolean argument
// Arg 3.0:?i32 = Optional x component (in i32) of 3rd HLSL arg
// Arg 3.1:?i32 = Optional y component (in i32) of 3rd HLSL arg
{L"CustomLoadOp",
"CustomLoadOp",
"c:{\"default\" : \"0,1,2:?i1,3.0:?i32,3.1:?i32\"}",
{21, true, false, false, -1, countof(TestCustomLoadOp), TestCustomLoadOp}},
{L"CustomLoadOp",
"CustomLoadOp",
"c:{\"default\" : \"0,1,2:?i1,3.0:?i32,3.1:?i32\"}",
{21, true, false, false, -1, countof(TestCustomLoadOpBool),
TestCustomLoadOpBool}},
{L"CustomLoadOp",
"CustomLoadOp",
"c:{\"default\" : \"0,1,2:?i1,3.0:?i32,3.1:?i32\"}",
{21, true, false, false, -1, countof(TestCustomLoadOpSubscript),
TestCustomLoadOpSubscript}},
};
Intrinsic BufferIntrinsics[] = {
{L"MyBufferOp",
"MyBufferOp",
"m",
{12, false, true, false, -1, countof(TestMyBufferOp), TestMyBufferOp}},
};
// Test adding a method to an object that normally has no methods (SamplerState
// will do).
Intrinsic SamplerIntrinsics[] = {
{L"MySamplerOp",
"MySamplerOp",
"m",
{15, false, true, false, -1, countof(TestMySamplerOp), TestMySamplerOp}},
};
// Define a lowering string to target a common dxil extension operation defined
// like this:
//
// @MyTextureOp(i32 opcode, %dx.types.Handle, i32 addr0, i32 addr1, i32 offset,
// i32 val0, i32 val1);
//
// This would produce the following lowerings (assuming the MyTextureOp opcode
// is 17)
//
// hlsl: Texture1D.MyTextureOp(a, b)
// hl: @MyTextureOp(17, handle, a, b)
// dxil: @MyTextureOp(17, handle, a, undef, b, undef, undef)
//
// hlsl: Texture1D.MyTextureOp(a, b, c)
// hl: @MyTextureOp(17, handle, a, b, c)
// dxil: @MyTextureOp(17, handle, a, undef, b, c, undef)
//
// hlsl: Texture2D.MyTextureOp(a, c)
// hl: @MyTextureOp(17, handle, a, c)
// dxil: @MyTextureOp(17, handle, a.x, a.y, undef, c.x, c.y)
//
static const char *MyTextureOp_LoweringInfo =
"m:{"
"\"default\" : \"0,1,2.0,2.1,3,4.0:?i32,4.1:?i32\","
"\"Texture2D\" : \"0,1,2.0,2.1,-1:?i32,3.0,3.1\""
"}";
Intrinsic Texture1DIntrinsics[] = {
{L"MyTextureOp",
"MyTextureOp",
MyTextureOp_LoweringInfo,
{17, false, true, false, -1, countof(TestMyTexture1DOp_0),
TestMyTexture1DOp_0}},
{L"MyTextureOp",
"MyTextureOp",
MyTextureOp_LoweringInfo,
{17, false, true, false, -1, countof(TestMyTexture1DOp_1),
TestMyTexture1DOp_1}},
};
Intrinsic Texture2DIntrinsics[] = {
{L"MyTextureOp",
"MyTextureOp",
MyTextureOp_LoweringInfo,
{17, false, true, false, -1, countof(TestMyTexture2DOp),
TestMyTexture2DOp}},
};
class IntrinsicTable {
public:
IntrinsicTable(const wchar_t *ns, Intrinsic *begin, Intrinsic *end)
: m_namespace(ns), m_begin(begin), m_end(end) {}
struct SearchResult {
Intrinsic *intrinsic;
uint64_t index;
SearchResult() : SearchResult(nullptr, 0) {}
SearchResult(Intrinsic *i, uint64_t n) : intrinsic(i), index(n) {}
operator bool() { return intrinsic != nullptr; }
};
SearchResult Search(const wchar_t *name, std::ptrdiff_t startIndex) const {
Intrinsic *begin = m_begin + startIndex;
assert(std::distance(begin, m_end) >= 0);
if (IsStar(name))
return BuildResult(begin);
Intrinsic *found = std::find_if(begin, m_end, [name](const Intrinsic &i) {
return wcscmp(i.hlslName, name) == 0;
});
return BuildResult(found);
}
SearchResult Search(unsigned opcode) const {
Intrinsic *begin = m_begin;
assert(std::distance(begin, m_end) >= 0);
Intrinsic *found = std::find_if(begin, m_end, [opcode](const Intrinsic &i) {
return i.hlsl.Op == opcode;
});
return BuildResult(found);
}
bool MatchesNamespace(const wchar_t *ns) const {
return wcscmp(m_namespace, ns) == 0;
}
private:
const wchar_t *m_namespace;
Intrinsic *m_begin;
Intrinsic *m_end;
bool IsStar(const wchar_t *name) const { return wcscmp(name, L"*") == 0; }
SearchResult BuildResult(Intrinsic *found) const {
if (found == m_end)
return SearchResult{nullptr, std::numeric_limits<uint64_t>::max()};
return SearchResult{found,
static_cast<uint64_t>(std::distance(m_begin, found))};
}
};
class TestIntrinsicTable : public IDxcIntrinsicTable {
private:
DXC_MICROCOM_REF_FIELD(m_dwRef)
std::vector<IntrinsicTable> m_tables;
public:
TestIntrinsicTable(Intrinsic *Intrinsics, unsigned IntrinsicsCount)
: m_dwRef(0) {
m_tables.push_back(
IntrinsicTable(L"", Intrinsics, Intrinsics + IntrinsicsCount));
m_tables.push_back(IntrinsicTable(L"Buffer", std::begin(BufferIntrinsics),
std::end(BufferIntrinsics)));
m_tables.push_back(IntrinsicTable(L"SamplerState",
std::begin(SamplerIntrinsics),
std::end(SamplerIntrinsics)));
m_tables.push_back(IntrinsicTable(L"Texture1D",
std::begin(Texture1DIntrinsics),
std::end(Texture1DIntrinsics)));
m_tables.push_back(IntrinsicTable(L"Texture2D",
std::begin(Texture2DIntrinsics),
std::end(Texture2DIntrinsics)));
}
TestIntrinsicTable()
: TestIntrinsicTable(::Intrinsics, _countof(::Intrinsics)) {}
DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcIntrinsicTable>(this, iid, ppvObject);
}
HRESULT STDMETHODCALLTYPE GetTableName(LPCSTR *pTableName) override {
*pTableName = "test";
return S_OK;
}
HRESULT STDMETHODCALLTYPE LookupIntrinsic(LPCWSTR typeName,
LPCWSTR functionName,
const HLSL_INTRINSIC **pIntrinsic,
UINT64 *pLookupCookie) override {
if (typeName == nullptr)
return E_FAIL;
// Search for matching intrinsic name in matching namespace.
IntrinsicTable::SearchResult result;
for (const IntrinsicTable &table : m_tables) {
if (table.MatchesNamespace(typeName)) {
result = table.Search(functionName, *pLookupCookie);
break;
}
}
if (result) {
*pIntrinsic = &result.intrinsic->hlsl;
*pLookupCookie = result.index + 1;
} else {
*pIntrinsic = nullptr;
*pLookupCookie = 0;
}
return result.intrinsic ? S_OK : E_FAIL;
}
HRESULT STDMETHODCALLTYPE GetLoweringStrategy(UINT opcode,
LPCSTR *pStrategy) override {
Intrinsic *intrinsic = FindByOpcode(opcode);
if (!intrinsic)
return E_FAIL;
*pStrategy = intrinsic->strategy;
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetIntrinsicName(UINT opcode,
LPCSTR *pName) override {
Intrinsic *intrinsic = FindByOpcode(opcode);
if (!intrinsic)
return E_FAIL;
*pName = intrinsic->dxilName;
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetDxilOpCode(UINT opcode,
UINT *pDxilOpcode) override {
if (opcode == 13) {
*pDxilOpcode = static_cast<UINT>(hlsl::OP::OpCode::IsInf);
return S_OK;
} else if (opcode == 14) {
*pDxilOpcode = static_cast<UINT>(hlsl::OP::OpCode::Ibfe);
return S_OK;
}
return E_FAIL;
}
Intrinsic *FindByOpcode(UINT opcode) {
IntrinsicTable::SearchResult result;
for (const IntrinsicTable &table : m_tables) {
result = table.Search(opcode);
if (result)
break;
}
return result.intrinsic;
}
};
// A class to test semantic define validation.
// It takes a list of defines that when present should cause errors
// and defines that should cause warnings. A more realistic validator
// would look at the values and make sure (for example) they are
// the correct type (integer, string, etc).
class TestSemanticDefineValidator : public IDxcSemanticDefineValidator {
private:
DXC_MICROCOM_REF_FIELD(m_dwRef)
std::vector<std::string> m_errorDefines;
std::vector<std::string> m_warningDefines;
public:
TestSemanticDefineValidator(const std::vector<std::string> &errorDefines,
const std::vector<std::string> &warningDefines)
: m_dwRef(0), m_errorDefines(errorDefines),
m_warningDefines(warningDefines) {}
DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcSemanticDefineValidator>(this, iid,
ppvObject);
}
virtual HRESULT STDMETHODCALLTYPE GetSemanticDefineWarningsAndErrors(
LPCSTR pName, LPCSTR pValue, IDxcBlobEncoding **ppWarningBlob,
IDxcBlobEncoding **ppErrorBlob) override {
if (!pName || !pValue || !ppWarningBlob || !ppErrorBlob)
return E_FAIL;
auto Check = [pName](const std::vector<std::string> &errors,
IDxcBlobEncoding **blob) {
if (std::find(errors.begin(), errors.end(), pName) != errors.end()) {
dxc::DxcDllSupport dllSupport;
VERIFY_SUCCEEDED(dllSupport.Initialize());
std::string error("bad define: ");
error.append(pName);
Utf8ToBlob(dllSupport, error.c_str(), blob);
}
};
Check(m_errorDefines, ppErrorBlob);
Check(m_warningDefines, ppWarningBlob);
return S_OK;
}
};
static void CheckOperationFailed(IDxcOperationResult *pResult) {
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
VERIFY_FAILED(status);
}
static std::string GetCompileErrors(IDxcOperationResult *pResult) {
CComPtr<IDxcBlobEncoding> pErrors;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrors));
if (!pErrors)
return "";
return BlobToUtf8(pErrors);
}
class Compiler {
public:
Compiler(dxc::DxcDllSupport &dll) : m_dllSupport(dll) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
VERIFY_SUCCEEDED(pCompiler.QueryInterface(&pLangExtensions));
}
void RegisterSemanticDefine(LPCWSTR define) {
VERIFY_SUCCEEDED(pLangExtensions->RegisterSemanticDefine(define));
}
void RegisterSemanticDefineExclusion(LPCWSTR define) {
VERIFY_SUCCEEDED(pLangExtensions->RegisterSemanticDefineExclusion(define));
}
void SetSemanticDefineValidator(IDxcSemanticDefineValidator *validator) {
pTestSemanticDefineValidator = validator;
VERIFY_SUCCEEDED(pLangExtensions->SetSemanticDefineValidator(
pTestSemanticDefineValidator));
}
void SetSemanticDefineMetaDataName(const char *name) {
VERIFY_SUCCEEDED(
pLangExtensions->SetSemanticDefineMetaDataName("test.defs"));
}
void SetTargetTriple(const char *name) {
VERIFY_SUCCEEDED(pLangExtensions->SetTargetTriple(name));
}
void RegisterIntrinsicTable(IDxcIntrinsicTable *table) {
pTestIntrinsicTable = table;
VERIFY_SUCCEEDED(
pLangExtensions->RegisterIntrinsicTable(pTestIntrinsicTable));
}
IDxcOperationResult *Compile(const char *program) {
return Compile(program, {}, {});
}
IDxcOperationResult *Compile(const char *program,
const std::vector<LPCWSTR> &arguments,
const std::vector<DxcDefine> defs,
LPCWSTR target = L"ps_6_0") {
Utf8ToBlob(m_dllSupport, program, &pCodeBlob);
VERIFY_SUCCEEDED(pCompiler->Compile(
pCodeBlob, L"hlsl.hlsl", L"main", target,
const_cast<LPCWSTR *>(arguments.data()), arguments.size(), defs.data(),
defs.size(), nullptr, &pCompileResult));
return pCompileResult;
}
std::string Disassemble() {
CComPtr<IDxcBlob> pBlob;
CheckOperationSucceeded(pCompileResult, &pBlob);
return DisassembleProgram(m_dllSupport, pBlob);
}
dxc::DxcDllSupport &m_dllSupport;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcLangExtensions3> pLangExtensions;
CComPtr<IDxcBlobEncoding> pCodeBlob;
CComPtr<IDxcOperationResult> pCompileResult;
CComPtr<IDxcSemanticDefineValidator> pTestSemanticDefineValidator;
CComPtr<IDxcIntrinsicTable> pTestIntrinsicTable;
};
///////////////////////////////////////////////////////////////////////////////
// Extension unit tests.
#ifdef _WIN32
class ExtensionTest {
#else
class ExtensionTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(ExtensionTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
dxc::DxcDllSupport m_dllSupport;
TEST_METHOD(EvalAttributeCollision)
TEST_METHOD(NoUnwind)
TEST_METHOD(DCE)
TEST_METHOD(DefineWhenRegisteredThenPreserved)
TEST_METHOD(DefineValidationError)
TEST_METHOD(DefineValidationWarning)
TEST_METHOD(DefineNoValidatorOk)
TEST_METHOD(DefineFromMacro)
TEST_METHOD(DefineContradictionFail)
TEST_METHOD(DefineOverrideSource)
TEST_METHOD(DefineOverrideDefinesList)
TEST_METHOD(DefineOverrideCommandLine)
TEST_METHOD(DefineOverrideNone)
TEST_METHOD(DefineOverrideDeterministicOutput)
TEST_METHOD(OptionFromDefineGVN)
TEST_METHOD(OptionFromDefineStructurizeReturns)
TEST_METHOD(OptionFromDefineLifetimeMarkers)
TEST_METHOD(TargetTriple)
TEST_METHOD(IntrinsicWhenAvailableThenUsed)
TEST_METHOD(CustomIntrinsicName)
TEST_METHOD(NoLowering)
TEST_METHOD(PackedLowering)
TEST_METHOD(ReplicateLoweringWhenOnlyVectorIsResult)
TEST_METHOD(UnsignedOpcodeIsUnchanged)
TEST_METHOD(ResourceExtensionIntrinsic)
TEST_METHOD(NameLoweredWhenNoReplicationNeeded)
TEST_METHOD(DxilLoweringVector1)
TEST_METHOD(DxilLoweringVector2)
TEST_METHOD(DxilLoweringScalar)
TEST_METHOD(SamplerExtensionIntrinsic)
TEST_METHOD(WaveIntrinsic)
TEST_METHOD(ResourceExtensionIntrinsicCustomLowering1)
TEST_METHOD(ResourceExtensionIntrinsicCustomLowering2)
TEST_METHOD(ResourceExtensionIntrinsicCustomLowering3)
TEST_METHOD(CustomOverloadArg1)
TEST_METHOD(CustomLoadOp)
};
TEST_F(ExtensionTest, DefineWhenRegisteredThenPreserved) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.RegisterSemanticDefineExclusion(L"FOOBAR");
c.SetSemanticDefineValidator(
new TestSemanticDefineValidator({"FOOLALA"}, {}));
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("#define FOOTBALL AWESOME\n"
"#define FOOTLOOSE TOO\n"
"#define FOOBAR 123\n"
"#define FOOD\n"
"#define FOO 1 2 3\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {{L"FOODEF", L"1"}});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// #define FOODEF 1
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOODEF\", !\"1\"}"));
// #define FOOTBALL AWESOME
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOOTBALL\", !\"AWESOME\"}"));
// #define FOOTLOOSE TOO
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOOTLOOSE\", !\"TOO\"}"));
// #define FOOD
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!{!\"FOOD\", !\"\"}"));
// #define FOO 1 2 3
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO\", !\"1 2 3\"}"));
// FOOBAR should be excluded.
VERIFY_IS_TRUE(disassembly.npos == disassembly.find("!{!\"FOOBAR\""));
}
TEST_F(ExtensionTest, DefineValidationError) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineValidator(new TestSemanticDefineValidator({"FOO"}, {}));
IDxcOperationResult *pCompileResult =
c.Compile("#define FOO 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {});
// Check that validation error causes compile failure.
CheckOperationFailed(pCompileResult);
std::string errors = GetCompileErrors(pCompileResult);
// Check that the error message is for the validation failure.
VERIFY_IS_TRUE(errors.npos !=
errors.find("hlsl.hlsl:1:9: error: bad define: FOO"));
}
TEST_F(ExtensionTest, DefineValidationWarning) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineValidator(new TestSemanticDefineValidator({}, {"FOO"}));
IDxcOperationResult *pCompileResult =
c.Compile("#define FOO 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {});
std::string errors = GetCompileErrors(pCompileResult);
// Check that the error message is for the validation failure.
VERIFY_IS_TRUE(errors.npos !=
errors.find("hlsl.hlsl:1:9: warning: bad define: FOO"));
// Check the define is still emitted.
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!hlsl.semdefs"));
// #define FOO 1
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!{!\"FOO\", !\"1\"}"));
}
TEST_F(ExtensionTest, DefineNoValidatorOk) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.Compile("#define FOO 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check the define is emitted.
// #define FOO 1
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!{!\"FOO\", !\"1\"}"));
}
TEST_F(ExtensionTest, DefineFromMacro) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.Compile("#define BAR 1\n"
"#define FOO BAR\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check the define is emitted.
// #define FOO 1
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!{!\"FOO\", !\"1\"}"));
}
// Test failure of contradictory optimization toggles
TEST_F(ExtensionTest, DefineContradictionFail) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
IDxcOperationResult *pCompileResult = c.Compile(
"#define FOO 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"-opt-disable", L"whatever", L"-opt-enable", L"whatever"}, {});
CheckOperationFailed(pCompileResult);
std::string errors = GetCompileErrors(pCompileResult);
// Check that the error message is for the option contradiction
VERIFY_IS_TRUE(errors.npos !=
errors.find("Contradictory use of -opt-disable and "
"-opt-enable with \"whatever\""));
Compiler c2(m_dllSupport);
c2.RegisterSemanticDefine(L"FOO*");
pCompileResult = c2.Compile("#define FOO 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"-opt-select", L"yook", L"butterUP",
L"-opt-select", L"yook", L"butterdown"},
{});
CheckOperationFailed(pCompileResult);
errors = GetCompileErrors(pCompileResult);
// Check that the error message is for the option contradiction
VERIFY_IS_TRUE(errors.npos !=
errors.find("Contradictory -opt-selects for \"yook\""));
}
// Test that the override-semdef flag can override a define from the source.
TEST_F(ExtensionTest, DefineOverrideSource) {
// Compile baseline without the override.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("#define FOO_A 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"1\"}"));
}
// Compile with an override.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("#define FOO_A 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"-override-semdef", L"FOO_A=7"}, {});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"7\"}"));
}
}
// Test that the override-semdef flag can override a define from the compile
// defines list.
TEST_F(ExtensionTest, DefineOverrideDefinesList) {
// Compile baseline without the override.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {{L"FOO_A", L"1"}});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"1\"}"));
}
// Compile with an override.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"-override-semdef", L"FOO_A=7"}, {{L"FOO_A", L"1"}});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"7\"}"));
}
}
// Test that the override-semdef flag can override a define from the command
// line.
TEST_F(ExtensionTest, DefineOverrideCommandLine) {
// Compile baseline without the override.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"/DFOO_A=1"}, {});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"1\"}"));
}
// Compile with an override after the /D define.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"/DFOO_A=1", L"-override-semdef", L"FOO_A=7"},
{{L"FOO_A", L"1"}});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"7\"}"));
}
// Compile with an override before the /D define.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"-override-semdef", L"FOO_A=7", L"/DFOO_A=1"},
{{L"FOO_A", L"1"}});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"7\"}"));
}
}
// Test that the override-semdef flag can override a define when there is no
// previous def.
TEST_F(ExtensionTest, DefineOverrideNone) {
// Compile baseline without the define.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos == disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos ==
disassembly.find("!{!\"FOO_A\", !\"7\"}"));
}
// Compile with an override.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd", L"-override-semdef", L"FOO_A=7"}, {});
std::string disassembly = c.Disassemble();
// Check for root named md node. It contains pointers to md nodes for each
// define.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("!test.defs"));
// Make sure we get the overrriden value.
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("!{!\"FOO_A\", !\"7\"}"));
}
}
TEST_F(ExtensionTest, DefineOverrideDeterministicOutput) {
std::string source = "#define FOO_B 1\n"
"#define FOO_A 1\n"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n";
std::string baselineOutput;
// Compile baseline.
{
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile(source.data(),
{L"/Vd", L"-override-semdef", L"FOO_A=7", L"-override-semdef",
L"FOO_B=7"},
{});
baselineOutput = c.Disassemble();
}
// Compile NUM_COMPILES times and make sure the output always matches.
enum { NUM_COMPILES = 10 };
for (int i = 0; i < NUM_COMPILES; ++i) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.SetSemanticDefineMetaDataName("test.defs");
c.Compile(source.data(),
{L"/Vd", L"-override-semdef", L"FOO_A=7", L"-override-semdef",
L"FOO_B=7"},
{});
std::string disassembly = c.Disassemble();
// Make sure the outputs are the same.
VERIFY_ARE_EQUAL(baselineOutput, disassembly);
}
}
// Test setting of codegen options from semantic defines
TEST_F(ExtensionTest, OptionFromDefineGVN) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.Compile("float4 main(float a : A) : SV_Target {\n"
" float res = sin(a);\n"
" return res + sin(a);\n"
"}\n",
{L"/Vd", L"-DFOO_DISABLE_GVN"}, {});
std::string disassembly = c.Disassemble();
// Verify that GVN is disabled by the presence
// of the second sin(), which GVN would have removed
llvm::Regex regex(
"call float @dx.op.unary.f32.*\n.*call float @dx.op.unary.f32");
std::string regexErrors;
VERIFY_IS_TRUE(regex.isValid(regexErrors));
VERIFY_IS_TRUE(regex.match(disassembly));
}
// Test setting of codegen options from semantic defines
TEST_F(ExtensionTest, OptionFromDefineStructurizeReturns) {
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.Compile("int i;\n"
"float main(float4 a:A) : SV_Target {\n"
"float c = 0;\n"
"if (i < 0) {\n"
" if (a.w > 2)\n"
" return -1;\n"
" c += a.z;\n"
"}\n"
"return c;\n"
"}\n",
{L"/Vd", L"-fcgl", L"-DFOO_ENABLE_STRUCTURIZE_RETURNS"}, {});
std::string disassembly = c.Disassemble();
// Verify that structurize returns is enabled by the presence
// of the associated annotation. Just a simple test to
// verify that it's on. No need to go into detail here
llvm::Regex regex("bReturned.* = alloca i1");
std::string regexErrors;
VERIFY_IS_TRUE(regex.isValid(regexErrors));
VERIFY_IS_TRUE(regex.match(disassembly));
}
// Test setting of codegen options from semantic defines
TEST_F(ExtensionTest, OptionFromDefineLifetimeMarkers) {
std::string shader =
"\n"
"float foo(float a) {\n"
"float res[2] = {a, 2 * 2};\n"
"return res[a];\n"
"}\n"
"float4 main(float a : A) : SV_Target { return foo(a); }\n";
Compiler c(m_dllSupport);
c.RegisterSemanticDefine(L"FOO*");
c.Compile(shader.data(), {L"/Vd", L"-DFOO_DISABLE_LIFETIME_MARKERS"}, {},
L"ps_6_6");
std::string disassembly = c.Disassemble();
Compiler c2(m_dllSupport);
c2.Compile(shader.data(), {L"/Vd", L""}, {}, L"ps_6_6");
std::string disassembly2 = c2.Disassemble();
// Make sure lifetime marker not exist with FOO_DISABLE_LIFETIME_MARKERS.
VERIFY_IS_TRUE(disassembly.find("lifetime") == std::string::npos);
VERIFY_IS_TRUE(disassembly.find("FOO_DISABLE_LIFETIME_MARKERS\", !\"1\"") !=
std::string::npos);
// Make sure lifetime marker exist by default.
VERIFY_IS_TRUE(disassembly2.find("lifetime") != std::string::npos);
}
TEST_F(ExtensionTest, TargetTriple) {
Compiler c(m_dllSupport);
c.SetTargetTriple("dxil-ms-win32");
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check the triple is updated.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("dxil-ms-win32"));
}
TEST_F(ExtensionTest, IntrinsicWhenAvailableThenUsed) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("float2 main(float2 v : V, int2 i : I) : SV_Target {\n"
" test_proc(v);\n"
" float2 a = test_fn(v);\n"
" int2 b = test_fn(i);\n"
" return a + b;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Things to call out:
// - result is float, not a vector
// - mangled name contains the 'test' and '.r' parts
// - opcode is first i32 argument
// - second argument is float, ie it got scalarized
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call void "
"@\"test.\\01?test_proc@hlsl@@YAXV?$vector@M$"
"01@@@Z.r\"(i32 2, float"));
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call float "
"@\"test.\\01?test_fn@hlsl@@YA?AV?$vector@M$"
"01@@V2@@Z.r\"(i32 1, float"));
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call i32 "
"@\"test.\\01?test_fn@hlsl@@YA?AV?$vector@H$"
"01@@V2@@Z.r\"(i32 1, i32"));
// - attributes are added to the declaration (the # at the end of the decl)
// TODO: would be nice to check for the actual attribute (e.g. readonly)
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("declare float "
"@\"test.\\01?test_fn@hlsl@@YA?AV?$vector@M$"
"01@@V2@@Z.r\"(i32, float) #"));
}
TEST_F(ExtensionTest, CustomIntrinsicName) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("float2 main(float2 v : V, int2 i : I) : SV_Target {\n"
" float2 a = test_poly(v);\n"
" int2 b = test_poly(i);\n"
" int2 c = test_int(i);\n"
" return a + b + c;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// - custom name works for polymorphic function
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call float @test_poly.float(i32 3, float"));
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call i32 @test_poly.i32(i32 3, i32"));
// - custom name works for non-polymorphic function
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call i32 @test_int(i32 4, i32"));
}
TEST_F(ExtensionTest, NoLowering) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("float2 main(float2 v : V, int2 i : I) : SV_Target {\n"
" float2 a = test_nolower(v);\n"
" float2 b = test_nolower(i);\n"
" return a + b;\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// - custom name works for non-lowered function
// - non-lowered function has vector type as argument
VERIFY_IS_TRUE(
disassembly.npos !=
disassembly.find(
"call <2 x float> @test_nolower.float(i32 5, <2 x float>"));
VERIFY_IS_TRUE(
disassembly.npos !=
disassembly.find("call <2 x i32> @test_nolower.i32(i32 5, <2 x i32>"));
}
TEST_F(ExtensionTest, PackedLowering) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("float2 main(float2 v1 : V1, float2 v2 : V2, float3 v3 : V3) : "
"SV_Target {\n"
" test_pack_0(v1);\n"
" int2 a = test_pack_1();\n"
" float2 b = test_pack_2(v1, v2);\n"
" float c = test_pack_3(v1);\n"
" float2 d = test_pack_4(v3);\n"
" return a + b + float2(c, c);\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// - pack strategy changes vectors into structs
VERIFY_IS_TRUE(
disassembly.npos !=
disassembly.find("call void @test_pack_0.float(i32 6, { float, float }"));
VERIFY_IS_TRUE(
disassembly.npos !=
disassembly.find("call { float, float } @test_pack_1.float(i32 7)"));
VERIFY_IS_TRUE(
disassembly.npos !=
disassembly.find(
"call { float, float } @test_pack_2.float(i32 8, { float, float }"));
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find(
"call float @test_pack_3.float(i32 9, { float, float }"));
VERIFY_IS_TRUE(
disassembly.npos !=
disassembly.find("call { float, float } @test_pack_4.float(i32 10, { "
"float, float, float }"));
}
TEST_F(ExtensionTest, ReplicateLoweringWhenOnlyVectorIsResult) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("float2 main(float2 v1 : V1, float2 v2 : V2, float3 v3 : V3) : "
"SV_Target {\n"
" return test_rand();\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// - replicate strategy works for vector results
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call float @test_rand(i32 11)"));
}
TEST_F(ExtensionTest, UnsignedOpcodeIsUnchanged) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("uint main(uint v1 : V1) : SV_Target {\n"
" return test_unsigned(v1);\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// - opcode is unchanged when it matches an hlsl intrinsic with
// an unsigned version.
// This should use the same value as IOP_min.
std::string matchStr;
std::ostringstream ss(matchStr);
ss << "call i32 @test_unsigned(i32 " << (unsigned)hlsl::IntrinsicOp::IOP_min
<< ", ";
VERIFY_IS_TRUE(disassembly.npos != disassembly.find(ss.str()));
}
TEST_F(ExtensionTest, ResourceExtensionIntrinsic) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("Buffer<float2> buf;"
"float2 main(uint2 v1 : V1) : SV_Target {\n"
" return buf.MyBufferOp(uint2(1, 2));\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Things to check
// - return type is translated to dx.types.ResRet
// - buffer is translated to dx.types.Handle
// - vector is exploded
llvm::Regex regex("call %dx.types.ResRet.f32 @MyBufferOp\\(i32 12, "
"%dx.types.Handle %.*, i32 1, i32 2\\)");
std::string regexErrors;
VERIFY_IS_TRUE(regex.isValid(regexErrors));
VERIFY_IS_TRUE(regex.match(disassembly));
}
TEST_F(ExtensionTest, CustomLoadOp) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
auto result =
c.Compile("float2 main(uint2 v1 : V1) : SV_Target {\n"
" float2 a = CustomLoadOp(uint2(1,2));\n"
" float2 b = CustomLoadOp(uint2(3,4),1);\n"
" float2 c = CustomLoadOp(uint2(5,6),1,uint2(7,8));\n"
" return a+b+c;\n"
"}\n",
{L"/Vd"}, {});
CheckOperationResultMsgs(result, {}, true, false);
std::string disassembly = c.Disassemble();
// Things to check
// - return type is 2xfloat
// - input type is 2x struct
// - function overload handles variable arguments (and replaces them with
// undefs)
// - output struct gets converted to vector
LPCSTR expected[] = {
"%1 = call { float, float } @CustomLoadOp(i32 21, { i32, i32 } { i32 1, "
"i32 2 }, i1 undef, i32 undef, i32 undef)",
"%2 = extractvalue { float, float } %1, 0",
"%3 = extractvalue { float, float } %1, 1",
"%4 = call { float, float } @CustomLoadOp(i32 21, { i32, i32 } { i32 3, "
"i32 4 }, i1 true, i32 undef, i32 undef)",
"%5 = extractvalue { float, float } %4, 0",
"%6 = extractvalue { float, float } %4, 1",
"%7 = call { float, float } @CustomLoadOp(i32 21, { i32, i32 } { i32 5, "
"i32 6 }, i1 true, i32 7, i32 8)",
"%8 = extractvalue { float, float } %7, 0",
"%9 = extractvalue { float, float } %7, 1"};
CheckMsgs(disassembly.c_str(), disassembly.length(), expected,
llvm::array_lengthof(expected), false);
}
TEST_F(ExtensionTest, NameLoweredWhenNoReplicationNeeded) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("int main(int v1 : V1) : SV_Target {\n"
" return test_int(v1);\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Make sure the name is still lowered even when no replication
// is needed because a non-vector overload of the function
// was used.
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("call i32 @test_int("));
}
TEST_F(ExtensionTest, DxilLoweringVector1) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("int main(float v1 : V1) : SV_Target {\n"
" return test_isinf(v1);\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check that the extension was lowered to the correct dxil intrinsic.
static_assert(9 == (unsigned)hlsl::OP::OpCode::IsInf,
"isinf opcode changed?");
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call i1 @dx.op.isSpecialFloat.f32(i32 9"));
}
TEST_F(ExtensionTest, DxilLoweringVector2) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("int2 main(float2 v1 : V1) : SV_Target {\n"
" return test_isinf(v1);\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check that the extension was lowered to the correct dxil intrinsic.
static_assert(9 == (unsigned)hlsl::OP::OpCode::IsInf,
"isinf opcode changed?");
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call i1 @dx.op.isSpecialFloat.f32(i32 9"));
}
TEST_F(ExtensionTest, DxilLoweringScalar) {
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("int main(uint v1 : V1, uint v2 : V2, uint v3 : V3) : SV_Target {\n"
" return test_ibfe(v1, v2, v3);\n"
"}\n",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check that the extension was lowered to the correct dxil intrinsic.
static_assert(51 == (unsigned)hlsl::OP::OpCode::Ibfe, "ibfe opcode changed?");
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call i32 @dx.op.tertiary.i32(i32 51"));
}
TEST_F(ExtensionTest, SamplerExtensionIntrinsic) {
// Test adding methods to objects that don't have any methods normally,
// and therefore have null default intrinsic table.
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
auto result = c.Compile("SamplerState samp;"
"float2 main(uint2 v1 : V1) : SV_Target {\n"
" return samp.MySamplerOp(uint2(1, 2));\n"
"}\n",
{L"/Vd"}, {});
CheckOperationResultMsgs(result, {}, true, false);
std::string disassembly = c.Disassemble();
// Things to check
// - works when SamplerState normally has no methods
// - return type is translated to dx.types.ResRet
// - buffer is translated to dx.types.Handle
// - vector is exploded
LPCSTR expected[] = {"call %dx.types.ResRet.f32 @MySamplerOp\\(i32 15, "
"%dx.types.Handle %.*, i32 1, i32 2\\)"};
CheckMsgs(disassembly.c_str(), disassembly.length(), expected, 1, true);
}
// Takes a string to match, and a regex pattern string, returns the first match
// at index [0], as well as sub expressions starting at index [1]
static std::vector<std::string> Match(const std::string &str,
const std::string pattern) {
std::vector<std::string> ret;
llvm::Regex regex(pattern);
std::string err;
VERIFY_IS_TRUE(regex.isValid(err));
llvm::SmallVector<llvm::StringRef, 4> matches;
if (!regex.match(str, &matches))
return ret;
ret.assign(matches.begin(), matches.end());
return ret;
}
//
// Regression test for extension functions having the same opcode as the
// following HLSL intrinsics, and triggering DxilLegalizeEvalOperations to make
// incorrect assumptions about allocas associated with it, causing them to be
// removed.
//
TEST_F(ExtensionTest, EvalAttributeCollision) {
static const HLSL_INTRINSIC_ARGUMENT Args[] = {
{"collide_proc", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1,
IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
hlsl::IntrinsicOp ops[] = {
hlsl::IntrinsicOp::IOP_GetAttributeAtVertex,
hlsl::IntrinsicOp::IOP_EvaluateAttributeSnapped,
hlsl::IntrinsicOp::IOP_EvaluateAttributeCentroid,
hlsl::IntrinsicOp::IOP_EvaluateAttributeAtSample,
};
for (hlsl::IntrinsicOp op : ops) {
Intrinsic Intrinsic = {L"collide_proc",
"collide_proc",
"r",
{static_cast<unsigned>(op), true, false, false, -1,
countof(Args), Args}};
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable(&Intrinsic, 1));
c.Compile(R"(
float2 main(float2 a : A, float2 b : B) : SV_Target {
float2 ret = b;
ret.x = collide_proc(ret.x);
return ret;
}
)",
{L"/Vd", L"/Od"}, {});
std::string disassembly = c.Disassemble();
auto match1 = Match(
disassembly,
std::string("%([0-9.a-zA-Z]*) = call float @collide_proc\\(i32 ") +
std::to_string(Intrinsic.hlsl.Op));
VERIFY_IS_TRUE(match1.size() == 2U);
VERIFY_IS_TRUE(
Match(disassembly, std::string("call void @dx.op.storeOutput.f32\\(i32 "
"5, i32 0, i32 0, i8 0, float %") +
match1[1])
.size() != 0U);
}
}
// Regression test for extension functions having no 'nounwind' attribute
TEST_F(ExtensionTest, NoUnwind) {
static const HLSL_INTRINSIC_ARGUMENT Args[] = {
{"test_proc", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1,
IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
Intrinsic Intrinsic = {L"test_proc",
"test_proc",
"r",
{1, false, false, false, -1, countof(Args), Args}};
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable(&Intrinsic, 1));
c.Compile(R"(
float main(float a : A) : SV_Target {
return test_proc(a);
}
)",
{L"/Vd", L"/Od"}, {});
std::string disassembly = c.Disassemble();
/*
* We're looking for this:
* declare float @test_proc(i32, float) #1
* attributes #1 = { nounwind }
*/
auto m1 =
Match(disassembly,
std::string("declare float @test_proc\\(i32, float\\) #([0-9]*)"));
VERIFY_IS_TRUE(m1.size() == 2U);
VERIFY_IS_TRUE(
Match(disassembly, std::string("attributes #") + m1[1] + " = { nounwind")
.size() != 0U);
}
// Regression test for extension function calls not getting DCE'ed becuase they
// had no 'nounwind' attribute
TEST_F(ExtensionTest, DCE) {
static const HLSL_INTRINSIC_ARGUMENT Args[] = {
{"test_proc", AR_QUAL_OUT, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1,
IA_C},
{"value", AR_QUAL_IN, 1, LITEMPLATE_ANY, 1, LICOMPTYPE_NUMERIC, 1, IA_C}};
Intrinsic Intrinsic = {L"test_proc",
"test_proc",
"r",
{1, true, true, false, -1, countof(Args), Args}};
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable(&Intrinsic, 1));
c.Compile(R"(
float main(float a : A) : SV_Target {
float dce = test_proc(a);
return 0;
}
)",
{L"/Vd", L"/Od"}, {});
std::string disassembly = c.Disassemble();
VERIFY_IS_TRUE(disassembly.npos == disassembly.find("call float @test_proc"));
}
TEST_F(ExtensionTest, WaveIntrinsic) {
// Test wave-sensitive intrinsic in breaked loop
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
c.Compile("StructuredBuffer<int> buf[]: register(t2);"
"float2 main(float2 a : A, int b : B) : SV_Target {"
" int res = 0;"
" float2 u = {0,0};"
" for (;;) {"
" u += wave_proc(a);"
" if (a.x == u.x) {"
" res += buf[b][(int)u.y];"
" break;"
" }"
" }"
" return res;"
"}",
{L"/Vd"}, {});
std::string disassembly = c.Disassemble();
// Check that the wave op causes the break block to be retained
VERIFY_IS_TRUE(
disassembly.npos !=
disassembly.find(
"@dx.break.cond = internal constant [1 x i32] zeroinitializer"));
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("%1 = load i32, i32* getelementptr inbounds "
"([1 x i32], [1 x i32]* @dx.break.cond"));
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("%2 = icmp eq i32 %1, 0"));
VERIFY_IS_TRUE(disassembly.npos !=
disassembly.find("call float "
"@\"test.\\01?wave_proc@hlsl@@YA?AV?$vector@"
"M$01@@V2@@Z.r\"(i32 16, float"));
VERIFY_IS_TRUE(disassembly.npos != disassembly.find("br i1 %2"));
}
TEST_F(ExtensionTest, ResourceExtensionIntrinsicCustomLowering1) {
// Test adding methods to objects that don't have any methods normally,
// and therefore have null default intrinsic table.
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
auto result = c.Compile("Texture1D tex1;"
"float2 main() : SV_Target {\n"
" return tex1.MyTextureOp(1,2,3);\n"
"}\n",
{L"/Vd"}, {});
CheckOperationResultMsgs(result, {}, true, false);
std::string disassembly = c.Disassemble();
// Things to check
// @MyTextureOp(i32 opcode, %dx.types.Handle, i32 addr0, i32 addr1, i32
// offset, i32 val0, i32 val1);
//
// hlsl: Texture1D.MyTextureOp(a, b, c)
// dxil: @MyTextureOp(17, handle, a, undef, b, c, undef)
//
LPCSTR expected[] = {
"call %dx.types.ResRet.i32 @MyTextureOp\\(i32 17, %dx.types.Handle %.*, "
"i32 1, i32 undef, i32 2, i32 3, i32 undef\\)",
};
CheckMsgs(disassembly.c_str(), disassembly.length(), expected, 1, true);
}
TEST_F(ExtensionTest, ResourceExtensionIntrinsicCustomLowering2) {
// Test adding methods to objects that don't have any methods normally,
// and therefore have null default intrinsic table.
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
auto result = c.Compile("Texture2D tex2;"
"float2 main() : SV_Target {\n"
" return tex2.MyTextureOp(uint2(4,5), uint2(6,7));\n"
"}\n",
{L"/Vd"}, {});
CheckOperationResultMsgs(result, {}, true, false);
std::string disassembly = c.Disassemble();
// Things to check
// @MyTextureOp(i32 opcode, %dx.types.Handle, i32 addr0, i32 addr1, i32
// offset, i32 val0, i32 val1);
//
// hlsl: Texture2D.MyTextureOp(a, c)
// dxil: @MyTextureOp(17, handle, a.x, a.y, undef, c.x, c.y)
LPCSTR expected[] = {
"call %dx.types.ResRet.i32 @MyTextureOp\\(i32 17, %dx.types.Handle %.*, "
"i32 4, i32 5, i32 undef, i32 6, i32 7\\)",
};
CheckMsgs(disassembly.c_str(), disassembly.length(), expected, 1, true);
}
TEST_F(ExtensionTest, ResourceExtensionIntrinsicCustomLowering3) {
// Test adding methods to objects that don't have any methods normally,
// and therefore have null default intrinsic table.
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
auto result = c.Compile("Texture1D tex1;"
"float2 main() : SV_Target {\n"
" return tex1.MyTextureOp(1,2);\n"
"}\n",
{L"/Vd"}, {});
CheckOperationResultMsgs(result, {}, true, false);
std::string disassembly = c.Disassemble();
// Things to check
// @MyTextureOp(i32 opcode, %dx.types.Handle, i32 addr0, i32 addr1, i32
// offset, i32 val0, i32 val1);
//
// hlsl: Texture1D.MyTextureOp(a, b)
// dxil: @MyTextureOp(17, handle, a, undef, b, undef, undef)
//
LPCSTR expected[] = {
"call %dx.types.ResRet.i32 @MyTextureOp\\(i32 17, %dx.types.Handle %.*, "
"i32 1, i32 undef, i32 2, i32 undef, i32 undef\\)",
};
CheckMsgs(disassembly.c_str(), disassembly.length(), expected, 1, true);
}
TEST_F(ExtensionTest, CustomOverloadArg1) {
// Test that we pick the overload name based on the first arg.
Compiler c(m_dllSupport);
c.RegisterIntrinsicTable(new TestIntrinsicTable());
auto result = c.Compile("float main() : SV_Target {\n"
" float o1 = test_o_1(1.0f, 2u, 4.0);\n"
" float o2 = test_o_2(1.0f, 2u, 4.0);\n"
" float o3 = test_o_3(1.0f, 2u, 4.0);\n"
" return o1 + o2 + o3;\n"
"}\n",
{L"/Vd"}, {});
CheckOperationResultMsgs(result, {}, true, false);
std::string disassembly = c.Disassemble();
// The function name should match the first arg (float)
LPCSTR expected[] = {
"call float @test_o_1.float(i32 18, float 1.000000e+00, i32 2, double "
"4.000000e+00)",
"call float @test_o_2.i32(i32 18, float 1.000000e+00, i32 2, double "
"4.000000e+00)",
"call float @test_o_3.double(i32 18, float 1.000000e+00, i32 2, double "
"4.000000e+00)",
};
CheckMsgs(disassembly.c_str(), disassembly.length(), expected, 1, false);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/RewriterTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// RewriterTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// The following HLSL tests contain static_asserts and are not useful for //
// the HLSL rewriter: more-operators.hlsl, object-operators.hlsl, //
// scalar-operators-assign.hlsl, scalar-operators.hlsl, string.hlsl. //
// They have been omitted. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef UNICODE
#define UNICODE
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
// clang-format off
// Includes on Windows are highly order dependent.
#include <memory>
#include <vector>
#include <string>
#include <cassert>
#include <sstream>
#include <algorithm>
#ifdef _WIN32
#include <windows.h>
#include <unknwn.h>
#endif
#include "dxc/dxcapi.h"
#ifdef _WIN32
#include <atlbase.h>
#include <atlfile.h>
#endif
#include "dxc/Test/HLSLTestData.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Support/Global.h"
#include "dxc/dxctools.h"
#include "dxc/Support/dxcapi.use.h"
#include "dxc/dxcapi.internal.h"
// clang-format on
using namespace std;
using namespace hlsl_test;
#ifdef _WIN32
class RewriterTest {
#else
class RewriterTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(RewriterTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
TEST_METHOD(RunArrayLength)
TEST_METHOD(RunAttributes)
TEST_METHOD(RunAnonymousStruct)
TEST_METHOD(RunCppErrors)
TEST_METHOD(RunForceExtern)
TEST_METHOD(RunIndexingOperator)
TEST_METHOD(RunIntrinsicExamples)
TEST_METHOD(RunMatrixAssignments)
TEST_METHOD(RunMatrixPackOrientation)
TEST_METHOD(RunMatrixSyntax)
TEST_METHOD(RunPackReg)
TEST_METHOD(RunScalarAssignments)
TEST_METHOD(RunShared)
TEST_METHOD(RunStructAssignments)
TEST_METHOD(RunTemplateChecks)
TEST_METHOD(RunTypemodsSyntax)
TEST_METHOD(RunVarmodsSyntax)
TEST_METHOD(RunVectorAssignments)
TEST_METHOD(RunVectorSyntaxMix)
TEST_METHOD(RunVectorSyntax)
TEST_METHOD(RunIncludes)
TEST_METHOD(RunSpirv)
TEST_METHOD(RunStructMethods)
TEST_METHOD(RunPredefines)
TEST_METHOD(RunWideOneByte)
TEST_METHOD(RunWideTwoByte)
TEST_METHOD(RunWideThreeByteBadChar)
TEST_METHOD(RunWideThreeByte)
TEST_METHOD(RunNonUnicode)
TEST_METHOD(RunEffect)
TEST_METHOD(RunSemanticDefines)
TEST_METHOD(RunNoFunctionBody)
TEST_METHOD(RunNoFunctionBodyInclude)
TEST_METHOD(RunNoStatic)
TEST_METHOD(RunKeepUserMacro)
TEST_METHOD(RunExtractUniforms)
TEST_METHOD(RunGlobalsUsedInMethod)
TEST_METHOD(RunRewriterFails)
dxc::DxcDllSupport m_dllSupport;
CComPtr<IDxcIncludeHandler> m_pIncludeHandler;
struct VerifyResult {
std::string warnings; // warnings from first compilation
std::string rewrite; // output of rewrite
bool HasSubstringInRewrite(const char *val) {
return std::string::npos != rewrite.find(val);
}
bool HasSubstringInWarnings(const char *val) {
return std::string::npos != warnings.find(val);
}
};
void CreateBlobPinned(LPCVOID data, SIZE_T size, UINT32 codePage,
IDxcBlobEncoding **ppBlob) {
CComPtr<IDxcLibrary> library;
IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
IFT(library->CreateBlobWithEncodingFromPinned(data, size, codePage,
ppBlob));
}
VerifyResult CheckVerifies(LPCWSTR path, LPCWSTR goldPath) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
return CheckVerifies(pRewriter, path, goldPath);
}
VerifyResult CheckVerifies(IDxcRewriter *pRewriter, LPCWSTR path,
LPCWSTR goldPath) {
CComPtr<IDxcOperationResult> pRewriteResult;
RewriteCompareGold(path, goldPath, &pRewriteResult, pRewriter);
VerifyResult toReturn;
CComPtr<IDxcBlob> pResultBlob;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&pResultBlob));
toReturn.rewrite = BlobToUtf8(pResultBlob);
CComPtr<IDxcBlobEncoding> pErrorsBlob;
VERIFY_SUCCEEDED(pRewriteResult->GetErrorBuffer(&pErrorsBlob));
toReturn.warnings = BlobToUtf8(pErrorsBlob);
return toReturn;
}
HRESULT CreateRewriter(IDxcRewriter **pRewriter) {
return m_dllSupport.CreateInstance(CLSID_DxcRewriter, pRewriter);
}
HRESULT CreateRewriterWithSemanticDefines(IDxcRewriter **pRewriter,
std::vector<LPCWSTR> defines) {
VERIFY_SUCCEEDED(CreateRewriter(pRewriter));
CComPtr<IDxcLangExtensions> pLangExtensions;
VERIFY_SUCCEEDED((*pRewriter)->QueryInterface(&pLangExtensions));
for (LPCWSTR define : defines)
VERIFY_SUCCEEDED(pLangExtensions->RegisterSemanticDefine(define));
return S_OK;
}
VerifyResult CheckVerifiesHLSL(LPCWSTR name, LPCWSTR goldName) {
return CheckVerifies(GetPathToHlslDataFile(name).c_str(),
GetPathToHlslDataFile(goldName).c_str());
}
struct FileWithBlob {
CComPtr<IDxcBlobEncoding> BlobEncoding;
FileWithBlob(dxc::DxcDllSupport &support, LPCWSTR path) {
CComPtr<IDxcLibrary> library;
IFT(support.CreateInstance(CLSID_DxcLibrary, &library));
UINT32 codePage = CP_UTF8;
IFT(library->CreateBlobFromFile(path, &codePage, &BlobEncoding));
}
};
bool CompareGold(std::string &firstPass, LPCWSTR goldPath) {
FileWithBlob goldBlob(m_dllSupport, goldPath);
std::string gold =
std::string((LPSTR)goldBlob.BlobEncoding->GetBufferPointer(),
goldBlob.BlobEncoding->GetBufferSize());
gold.erase(std::remove(gold.begin(), gold.end(), '\r'), gold.end());
// Kept because useful for debugging
// int atChar = 0;
// int numDiffChar = 0;
// while (atChar < result.size){
// char rewriteChar = (firstPass.data())[atChar];
// char goldChar = (gold.data())[atChar];
//
// if (rewriteChar != goldChar){
// numDiffChar++;
// }
// atChar++;
// }
return firstPass.compare(gold) == 0;
}
// Note: Previous versions of this file included a RewriteCompareRewrite
// method here that rewrote twice and compared to check for stable output. It
// has now been replaced by a new test that checks against a gold baseline.
void RewriteCompareGold(LPCWSTR path, LPCWSTR goldPath,
IDxcOperationResult **ppResult,
IDxcRewriter *rewriter) {
// Get the source text from a file
FileWithBlob source(m_dllSupport, path);
const int myDefinesCount = 3;
DxcDefine myDefines[myDefinesCount] = {
{L"myDefine", L"2"}, {L"myDefine3", L"1994"}, {L"myDefine4", nullptr}};
LPCWSTR args[] = {L"-HV", L"2016"};
CComPtr<IDxcRewriter2> rewriter2;
VERIFY_SUCCEEDED(rewriter->QueryInterface(&rewriter2));
// Run rewrite unchanged on the source code
VERIFY_SUCCEEDED(rewriter2->RewriteWithOptions(
source.BlobEncoding, path, args, _countof(args), myDefines,
myDefinesCount, nullptr, ppResult));
// check for compilation errors
HRESULT hrStatus;
VERIFY_SUCCEEDED((*ppResult)->GetStatus(&hrStatus));
if (!(SUCCEEDED(hrStatus))) {
::WEX::Logging::Log::Error(L"\nCompilation failed.\n");
CComPtr<IDxcBlobEncoding> pErrorBuffer;
IFT((*ppResult)->GetErrorBuffer(&pErrorBuffer));
std::wstring errorStr = BlobToWide(pErrorBuffer);
::WEX::Logging::Log::Error(errorStr.data());
VERIFY_SUCCEEDED(hrStatus);
return;
}
CComPtr<IDxcBlob> pRewriteResult;
IFT((*ppResult)->GetResult(&pRewriteResult));
std::string firstPass = BlobToUtf8(pRewriteResult);
if (CompareGold(firstPass, goldPath)) {
return;
}
// Log things out before failing.
std::wstring TestFileName(path);
int index1 = TestFileName.find_last_of(L"\\");
int index2 = TestFileName.find_last_of(L".");
TestFileName = TestFileName.substr(index1 + 1, index2 - (index1 + 1));
wchar_t TempPath[MAX_PATH];
#ifdef _WIN32
DWORD length = GetTempPathW(MAX_PATH, TempPath);
VERIFY_WIN32_BOOL_SUCCEEDED(length != 0);
#else
const char *TempDir = std::getenv("TMPDIR");
if (TempDir == nullptr) {
TempDir = "/tmp";
}
mbstowcs(TempPath, TempDir, strlen(TempDir) + 1);
#endif
std::wstring PrintName(TempPath);
PrintName += TestFileName;
PrintName += L"_rewrite_test_pass.txt";
CHandle checkedWHandle(CreateNewFileForReadWrite(PrintName.data()));
LPDWORD wnumWrite = 0;
VERIFY_WIN32_BOOL_SUCCEEDED(WriteFile(checkedWHandle, firstPass.data(),
firstPass.size(), wnumWrite, NULL));
std::wstringstream ss;
ss << L"\nMismatch occurred between rewriter output and expected "
L"output. To see the differences, run:\n"
L"diff "
<< goldPath << L" " << PrintName << L"\n";
::WEX::Logging::Log::Error(ss.str().c_str());
}
bool RewriteCompareGoldInclude(LPCWSTR path, LPCWSTR goldPath,
unsigned rewriteOption) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
std::wstring fileName = GetPathToHlslDataFile(path);
// Get the source text from a file
FileWithBlob source(m_dllSupport, fileName.c_str());
const int myDefinesCount = 3;
DxcDefine myDefines[myDefinesCount] = {
{L"myDefine", L"2"}, {L"myDefine3", L"1994"}, {L"myDefine4", nullptr}};
// Run rewrite no function body on the source code
VERIFY_SUCCEEDED(pRewriter->RewriteUnchangedWithInclude(
source.BlobEncoding, fileName.c_str(), myDefines, myDefinesCount,
m_pIncludeHandler, rewriteOption, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
std::string rewriteText = BlobToUtf8(result);
return CompareGold(rewriteText, GetPathToHlslDataFile(goldPath).c_str());
}
};
bool RewriterTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
CComPtr<IDxcLibrary> library;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
VERIFY_SUCCEEDED(library->CreateIncludeHandler(&m_pIncludeHandler));
}
return true;
}
TEST_F(RewriterTest, RunArrayLength) {
CheckVerifiesHLSL(L"rewriter\\array-length-rw.hlsl",
L"rewriter\\correct_rewrites\\array-length-rw_gold.hlsl");
}
TEST_F(RewriterTest, RunAttributes) {
CheckVerifiesHLSL(L"rewriter\\attributes_noerr.hlsl",
L"rewriter\\correct_rewrites\\attributes_gold.hlsl");
}
TEST_F(RewriterTest, RunAnonymousStruct) {
CheckVerifiesHLSL(L"rewriter\\anonymous_struct.hlsl",
L"rewriter\\correct_rewrites\\anonymous_struct_gold.hlsl");
}
TEST_F(RewriterTest, RunCppErrors) {
CheckVerifiesHLSL(L"rewriter\\cpp-errors_noerr.hlsl",
L"rewriter\\correct_rewrites\\cpp-errors_gold.hlsl");
}
TEST_F(RewriterTest, RunIndexingOperator) {
CheckVerifiesHLSL(L"rewriter\\indexing-operator_noerr.hlsl",
L"rewriter\\correct_rewrites\\indexing-operator_gold.hlsl");
}
TEST_F(RewriterTest, RunIntrinsicExamples) {
CheckVerifiesHLSL(
L"rewriter\\intrinsic-examples_noerr.hlsl",
L"rewriter\\correct_rewrites\\intrinsic-examples_gold.hlsl");
}
TEST_F(RewriterTest, RunMatrixAssignments) {
CheckVerifiesHLSL(
L"rewriter\\matrix-assignments_noerr.hlsl",
L"rewriter\\correct_rewrites\\matrix-assignments_gold.hlsl");
}
TEST_F(RewriterTest, RunMatrixPackOrientation) {
CheckVerifiesHLSL(
L"rewriter\\matrix-pack-orientation.hlsl",
L"rewriter\\correct_rewrites\\matrix-pack-orientation_gold.hlsl");
}
TEST_F(RewriterTest, RunMatrixSyntax) {
CheckVerifiesHLSL(L"rewriter\\matrix-syntax_noerr.hlsl",
L"rewriter\\correct_rewrites\\matrix-syntax_gold.hlsl");
}
TEST_F(RewriterTest, RunPackReg) {
CheckVerifiesHLSL(L"rewriter\\packreg_noerr.hlsl",
L"rewriter\\correct_rewrites\\packreg_gold.hlsl");
}
TEST_F(RewriterTest, RunScalarAssignments) {
CheckVerifiesHLSL(
L"rewriter\\scalar-assignments_noerr.hlsl",
L"rewriter\\correct_rewrites\\scalar-assignments_gold.hlsl");
}
TEST_F(RewriterTest, RunShared) {
CheckVerifiesHLSL(L"rewriter\\shared.hlsl",
L"rewriter\\correct_rewrites\\shared.hlsl");
}
TEST_F(RewriterTest, RunStructAssignments) {
CheckVerifiesHLSL(
L"rewriter\\struct-assignments_noerr.hlsl",
L"rewriter\\correct_rewrites\\struct-assignments_gold.hlsl");
}
TEST_F(RewriterTest, RunTemplateChecks) {
CheckVerifiesHLSL(L"rewriter\\template-checks_noerr.hlsl",
L"rewriter\\correct_rewrites\\template-checks_gold.hlsl");
}
TEST_F(RewriterTest, RunTypemodsSyntax) {
CheckVerifiesHLSL(L"rewriter\\typemods-syntax_noerr.hlsl",
L"rewriter\\correct_rewrites\\typemods-syntax_gold.hlsl");
}
TEST_F(RewriterTest, RunVarmodsSyntax) {
CheckVerifiesHLSL(L"rewriter\\varmods-syntax_noerr.hlsl",
L"rewriter\\correct_rewrites\\varmods-syntax_gold.hlsl");
}
TEST_F(RewriterTest, RunVectorAssignments) {
CheckVerifiesHLSL(
L"rewriter\\vector-assignments_noerr.hlsl",
L"rewriter\\correct_rewrites\\vector-assignments_gold.hlsl");
}
TEST_F(RewriterTest, RunVectorSyntaxMix) {
CheckVerifiesHLSL(L"rewriter\\vector-syntax-mix_noerr.hlsl",
L"rewriter\\correct_rewrites\\vector-syntax-mix_gold.hlsl");
}
TEST_F(RewriterTest, RunVectorSyntax) {
CheckVerifiesHLSL(L"rewriter\\vector-syntax_noerr.hlsl",
L"rewriter\\correct_rewrites\\vector-syntax_gold.hlsl");
}
TEST_F(RewriterTest, RunIncludes) {
VERIFY_IS_TRUE(RewriteCompareGoldInclude(
L"rewriter\\includes.hlsl",
L"rewriter\\correct_rewrites\\includes_gold.hlsl",
RewriterOptionMask::Default));
}
TEST_F(RewriterTest, RunNoFunctionBodyInclude) {
VERIFY_IS_TRUE(RewriteCompareGoldInclude(
L"rewriter\\includes.hlsl",
L"rewriter\\correct_rewrites\\includes_gold_nobody.hlsl",
RewriterOptionMask::SkipFunctionBody));
}
TEST_F(RewriterTest, RunSpirv) {
CComPtr<IDxcRewriter> pRewriter;
CComPtr<IDxcRewriter2> pRewriter2;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
VERIFY_SUCCEEDED(pRewriter->QueryInterface(&pRewriter2));
CComPtr<IDxcOperationResult> pRewriteResult;
// Get the source text from a file
FileWithBlob source(m_dllSupport,
GetPathToHlslDataFile(L"rewriter\\spirv.hlsl").c_str());
LPCWSTR compileOptions[] = {L"-E", L"main", L"-HV", L"2021", L"-spirv"};
// Run rewriter with HLSL 2021 specification and SPIR-V support
VERIFY_SUCCEEDED(pRewriter2->RewriteWithOptions(
source.BlobEncoding, L"spirv.hlsl", compileOptions,
_countof(compileOptions), nullptr, 0, nullptr, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
std::string strResult = BlobToUtf8(result);
// No built-in namespace "vk"
VERIFY_IS_TRUE(strResult.find("namespace vk") == std::string::npos);
}
TEST_F(RewriterTest, RunStructMethods) {
CheckVerifiesHLSL(L"rewriter\\struct-methods.hlsl",
L"rewriter\\correct_rewrites\\struct-methods_gold.hlsl");
}
TEST_F(RewriterTest, RunPredefines) {
CheckVerifiesHLSL(L"rewriter\\predefines.hlsl",
L"rewriter\\correct_rewrites\\predefines_gold.hlsl");
}
TEST_F(RewriterTest, RunWideOneByte) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
WCHAR widetext[] = {L"\x0069\x006e\x0074\x0020\x0069\x003b"}; // "int i;"
CComPtr<IDxcBlobEncoding> source;
CreateBlobPinned(widetext, sizeof(widetext), DXC_CP_WIDE, &source);
VERIFY_SUCCEEDED(pRewriter->RewriteUnchanged(source, 0, 0, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
VERIFY_IS_TRUE(
strcmp(BlobToUtf8(result).c_str(),
"// Rewrite unchanged "
"result:\n\x63\x6f\x6e\x73\x74\x20\x69\x6e\x74\x20\x69\x3b\n") ==
0); // const added by default
}
TEST_F(RewriterTest, RunWideTwoByte) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
WCHAR widetext[] = {
L"\x0069\x006e\x0074\x0020\x00ed\x00f1\x0167\x003b"}; // "int (i w/
// acute)(n
// w/tilde)(t w/ 2
// strokes);"
CComPtr<IDxcBlobEncoding> source;
CreateBlobPinned(widetext, sizeof(widetext), DXC_CP_WIDE, &source);
VERIFY_SUCCEEDED(pRewriter->RewriteUnchanged(source, 0, 0, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
VERIFY_IS_TRUE(strcmp(BlobToUtf8(result).c_str(),
"// Rewrite unchanged "
"result:"
"\n\x63\x6f\x6e\x73\x74\x20\x69\x6e\x74\x20\xc3\xad\xc3"
"\xb1\xc5\xa7\x3b\n") == 0); // const added by default
}
TEST_F(RewriterTest, RunWideThreeByteBadChar) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
WCHAR widetext[] = {
L"\x0069\x006e\x0074\x0020\x0041\x2655\x265a\x003b"}; // "int A(white
// queen)(black
// king);"
CComPtr<IDxcBlobEncoding> source;
CreateBlobPinned(widetext, sizeof(widetext), DXC_CP_WIDE, &source);
VERIFY_SUCCEEDED(pRewriter->RewriteUnchanged(source, 0, 0, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
VERIFY_IS_TRUE(
strcmp(BlobToUtf8(result).c_str(),
"// Rewrite unchanged "
"result:\n\x63\x6f\x6e\x73\x74\x20\x69\x6e\x74\x20\x41\x3b\n") ==
0); //"const int A;" -> should remove the weird characters
}
TEST_F(RewriterTest, RunWideThreeByte) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
WCHAR widetext[] = {
L"\x0069\x006e\x0074\x0020\x1e8b\x003b"}; // "int (x with dot above);"
CComPtr<IDxcBlobEncoding> source;
CreateBlobPinned(widetext, sizeof(widetext), DXC_CP_WIDE, &source);
VERIFY_SUCCEEDED(pRewriter->RewriteUnchanged(source, 0, 0, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
VERIFY_IS_TRUE(
strcmp(BlobToUtf8(result).c_str(),
"// Rewrite unchanged "
"result:"
"\n\x63\x6f\x6e\x73\x74\x20\x69\x6e\x74\x20\xe1\xba\x8b\x3b\n") ==
0); // const added by default
}
#ifdef _WIN32
TEST_F(RewriterTest, RunNonUnicode) {
#else
// Need to enable ANSI Greek support.
TEST_F(RewriterTest, DISABLED_RunNonUnicode) {
#endif
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
char greektext[] = {
"\x69\x6e\x74\x20\xe1\xe2\xe3\x3b"}; // "int (small alpha)(small
// beta)(small kappa);"
CComPtr<IDxcBlobEncoding> source;
CreateBlobPinned(greektext, sizeof(greektext), 1253,
&source); // 1253 == ANSI Greek
VERIFY_SUCCEEDED(pRewriter->RewriteUnchanged(source, 0, 0, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
VERIFY_IS_TRUE(strcmp(BlobToUtf8(result).c_str(),
"// Rewrite unchanged "
"result:"
"\n\x63\x6f\x6e\x73\x74\x20\x69\x6e\x74\x20\xce\xb1\xce"
"\xb2\xce\xb3\x3b\n") == 0); // const added by default
}
TEST_F(RewriterTest, RunEffect) {
CheckVerifiesHLSL(L"rewriter\\effects-syntax_noerr.hlsl",
L"rewriter\\correct_rewrites\\effects-syntax_gold.hlsl");
}
TEST_F(RewriterTest, RunSemanticDefines) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriterWithSemanticDefines(&pRewriter, {L"SD_*"}));
CheckVerifies(
pRewriter,
hlsl_test::GetPathToHlslDataFile(L"rewriter\\semantic-defines.hlsl")
.c_str(),
hlsl_test::GetPathToHlslDataFile(
L"rewriter\\correct_rewrites\\semantic-defines_gold.hlsl")
.c_str());
}
TEST_F(RewriterTest, RunNoFunctionBody) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
// Get the source text from a file
FileWithBlob source(
m_dllSupport,
GetPathToHlslDataFile(L"rewriter\\vector-assignments_noerr.hlsl")
.c_str());
const int myDefinesCount = 3;
DxcDefine myDefines[myDefinesCount] = {
{L"myDefine", L"2"}, {L"myDefine3", L"1994"}, {L"myDefine4", nullptr}};
// Run rewrite no function body on the source code
VERIFY_SUCCEEDED(pRewriter->RewriteUnchangedWithInclude(
source.BlobEncoding, L"vector-assignments_noerr.hlsl", myDefines,
myDefinesCount, /*pIncludeHandler*/ nullptr,
RewriterOptionMask::SkipFunctionBody, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
// Function decl only.
VERIFY_IS_TRUE(strcmp(BlobToUtf8(result).c_str(),
"// Rewrite unchanged result:\nfloat pick_one(float2 "
"f2);\nvoid main();\n") == 0);
}
TEST_F(RewriterTest, RunNoStatic) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
// Get the source text from a file
FileWithBlob source(
m_dllSupport,
GetPathToHlslDataFile(L"rewriter\\attributes_noerr.hlsl").c_str());
const int myDefinesCount = 3;
DxcDefine myDefines[myDefinesCount] = {
{L"myDefine", L"2"}, {L"myDefine3", L"1994"}, {L"myDefine4", nullptr}};
// Run rewrite no function body on the source code
VERIFY_SUCCEEDED(pRewriter->RewriteUnchangedWithInclude(
source.BlobEncoding, L"attributes_noerr.hlsl", myDefines, myDefinesCount,
/*pIncludeHandler*/ nullptr,
RewriterOptionMask::SkipFunctionBody | RewriterOptionMask::SkipStatic,
&pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
std::string strResult = BlobToUtf8(result);
// No static.
VERIFY_IS_TRUE(strResult.find("static") == std::string::npos);
}
TEST_F(RewriterTest, RunGlobalsUsedInMethod) {
CComPtr<IDxcRewriter> pRewriter;
CComPtr<IDxcRewriter2> pRewriter2;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
VERIFY_SUCCEEDED(pRewriter->QueryInterface(&pRewriter2));
CComPtr<IDxcOperationResult> pRewriteResult;
// Get the source text from a file
FileWithBlob source(m_dllSupport,
GetPathToHlslDataFile(
L"rewriter\\not_remove_globals_used_in_methods.hlsl")
.c_str());
LPCWSTR compileOptions[] = {L"-E", L"main", L" -remove-unused-globals"};
// Run rewrite on the source code to move uniform params to globals
VERIFY_SUCCEEDED(pRewriter2->RewriteWithOptions(
source.BlobEncoding, L"rewrite-uniforms.hlsl", compileOptions,
_countof(compileOptions), nullptr, 0, nullptr, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
std::string strResult = BlobToUtf8(result);
// No static.
VERIFY_IS_TRUE(strResult.find("RWBuffer<uint> u;") != std::string::npos);
}
TEST_F(RewriterTest, RunForceExtern) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
// Get the source text from a file
FileWithBlob source(
m_dllSupport,
GetPathToHlslDataFile(L"rewriter\\force_extern.hlsl").c_str());
const int myDefinesCount = 3;
DxcDefine myDefines[myDefinesCount] = {
{L"myDefine", L"2"}, {L"myDefine3", L"1994"}, {L"myDefine4", nullptr}};
// Run rewrite no function body on the source code
VERIFY_SUCCEEDED(pRewriter->RewriteUnchangedWithInclude(
source.BlobEncoding, L"vector-assignments_noerr.hlsl", myDefines,
myDefinesCount, /*pIncludeHandler*/ nullptr,
RewriterOptionMask::SkipFunctionBody |
RewriterOptionMask::GlobalExternByDefault,
&pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
// Function decl only.
VERIFY_IS_TRUE(
strcmp(BlobToUtf8(result).c_str(), "// Rewrite unchanged result:\n\
extern const float a;\n\
namespace b {\n\
extern const float c;\n\
namespace d {\n\
extern const float e;\n\
}\n\
}\n\
static int f;\n\
float4 main() : SV_Target;\n") == 0);
}
TEST_F(RewriterTest, RunKeepUserMacro) {
CComPtr<IDxcRewriter> pRewriter;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
CComPtr<IDxcOperationResult> pRewriteResult;
// Get the source text from a file
FileWithBlob source(
m_dllSupport,
GetPathToHlslDataFile(L"rewriter\\predefines2.hlsl").c_str());
const int myDefinesCount = 3;
DxcDefine myDefines[myDefinesCount] = {
{L"myDefine", L"2"}, {L"myDefine3", L"1994"}, {L"myDefine4", nullptr}};
// Run rewrite no function body on the source code
VERIFY_SUCCEEDED(pRewriter->RewriteUnchangedWithInclude(
source.BlobEncoding, L"vector-assignments_noerr.hlsl", myDefines,
myDefinesCount, /*pIncludeHandler*/ nullptr,
RewriterOptionMask::KeepUserMacro, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
// Function decl only.
VERIFY_IS_TRUE(
strcmp(BlobToUtf8(result).c_str(), "// Rewrite unchanged result:\n\
const float x = 1;\n\
float test(float a, float b) {\n\
return ((a) + (b));\n\
}\n\
\n\n\n\
// Macros:\n\
#define X 1\n\
#define Y(A, B) ( ( A ) + ( B ) )\n\
") == 0);
}
TEST_F(RewriterTest, RunExtractUniforms) {
CComPtr<IDxcRewriter> pRewriter;
CComPtr<IDxcRewriter2> pRewriter2;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
VERIFY_SUCCEEDED(pRewriter->QueryInterface(&pRewriter2));
CComPtr<IDxcOperationResult> pRewriteResult;
// Get the source text from a file
FileWithBlob source(
m_dllSupport,
GetPathToHlslDataFile(L"rewriter\\rewrite-uniforms.hlsl").c_str());
LPCWSTR compileOptions[] = {L"-E", L"FloatFunc", L"-extract-entry-uniforms"};
// Run rewrite on the source code to move uniform params to globals
VERIFY_SUCCEEDED(pRewriter2->RewriteWithOptions(
source.BlobEncoding, L"rewrite-uniforms.hlsl", compileOptions,
_countof(compileOptions), nullptr, 0, nullptr, &pRewriteResult));
CComPtr<IDxcBlob> result;
VERIFY_SUCCEEDED(pRewriteResult->GetResult(&result));
VERIFY_IS_TRUE(
strcmp(BlobToUtf8(result).c_str(), "// Rewrite unchanged result:\n\
[RootSignature(\"RootFlags(0),DescriptorTable(UAV(u0, numDescriptors = 1), CBV(b0, numDescriptors = 1))\")]\n\
[numthreads(4, 8, 16)]\n\
void IntFunc(uint3 id : SV_DispatchThreadID, uniform RWStructuredBuffer<int> buf, uniform uint ui) {\n\
buf[id.x + id.y + id.z] = id.x + ui;\n\
}\n\
\n\
\n\
uniform RWStructuredBuffer<float> buf;\n\
cbuffer _Params {\n\
uniform uint ui;\n\
}\n\
[RootSignature(\"RootFlags(0),DescriptorTable(UAV(u0, numDescriptors = 1), CBV(b0, numDescriptors = 1))\")]\n\
[numthreads(4, 8, 16)]\n\
void FloatFunc(uint3 id : SV_DispatchThreadID) {\n\
buf[id.x + id.y + id.z] = id.x;\n\
}\n\
\n\
") == 0);
}
TEST_F(RewriterTest, RunRewriterFails) {
CComPtr<IDxcRewriter> pRewriter;
CComPtr<IDxcRewriter2> pRewriter2;
VERIFY_SUCCEEDED(CreateRewriter(&pRewriter));
VERIFY_SUCCEEDED(pRewriter->QueryInterface(&pRewriter2));
// Get the source text from a file
std::wstring sourceName =
GetPathToHlslDataFile(L"rewriter\\array-length-rw.hlsl");
FileWithBlob source(m_dllSupport, sourceName.c_str());
// Compilation should fail with these options
CComPtr<IDxcOperationResult> pRewriteResult;
LPCWSTR compileOptions[] = {L"-HV", L"2018"};
// Run rewrite on the source code
VERIFY_SUCCEEDED(pRewriter2->RewriteWithOptions(
source.BlobEncoding, sourceName.c_str(), compileOptions, 2, nullptr, 0,
nullptr, &pRewriteResult));
// Verify it failed
HRESULT hrStatus;
VERIFY_SUCCEEDED(pRewriteResult->GetStatus(&hrStatus));
VERIFY_FAILED(hrStatus);
::WEX::Logging::Log::Comment(L"\nCompilation failed as expected.\n");
CComPtr<IDxcBlobEncoding> pErrorBuffer;
IFT(pRewriteResult->GetErrorBuffer(&pErrorBuffer));
std::wstring errorStr = BlobToWide(pErrorBuffer);
::WEX::Logging::Log::Comment(errorStr.data());
VERIFY_IS_TRUE(
errorStr.find(L"Length is only allowed for HLSL 2016 and lower.") >= 0);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/CMakeLists.txt
|
# Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
if(WIN32)
find_package(TAEF REQUIRED)
find_package(DiaSDK REQUIRED) # Used for constants and declarations.
find_package(D3D12 REQUIRED) # Used in DxilContainerTest for DXBC compilation/reflection
endif(WIN32)
set( LLVM_LINK_COMPONENTS
support
mssupport
dxcsupport
dxil
dxilcontainer
dxilrootsignature
hlsl
dxilhash
option
bitreader
bitwriter
analysis
ipa
irreader
transformutils # for CloneModule
)
if(WIN32)
set(HLSL_IGNORE_SOURCES
TestMain.cpp
HLSLTestOptions.cpp
)
add_clang_library(ClangHLSLTests SHARED
AllocatorTest.cpp
CompilerTest.cpp
DxilContainerTest.cpp
DxilModuleTest.cpp
DxilResourceTests.cpp
DXIsenseTest.cpp
ExtensionTest.cpp
FunctionTest.cpp
LinkerTest.cpp
MSFileSysTest.cpp
Objects.cpp
OptimizerTest.cpp
OptionsTest.cpp
PixDiaTest.cpp
PixTest.cpp
PixTestUtils.cpp
RewriterTest.cpp
SystemValueTest.cpp
ValidationTest.cpp
VerifierTest.cpp
)
add_dependencies(ClangUnitTests ClangHLSLTests)
else (WIN32)
set(HLSL_IGNORE_SOURCES
MSFileSysTest.cpp
PixDiaTest.cpp
)
add_clang_unittest(ClangHLSLTests
AllocatorTest.cpp
CompilerTest.cpp
DxilContainerTest.cpp
DxilModuleTest.cpp
DxilResourceTests.cpp
DXIsenseTest.cpp
ExtensionTest.cpp
FunctionTest.cpp
HLSLTestOptions.cpp
LinkerTest.cpp
Objects.cpp
OptimizerTest.cpp
OptionsTest.cpp
RewriterTest.cpp
PixTest.cpp
PixTestUtils.cpp
SystemValueTest.cpp
TestMain.cpp
ValidationTest.cpp
VerifierTest.cpp
)
endif(WIN32)
set_target_properties(ClangHLSLTests PROPERTIES FOLDER "Clang tests")
if (WIN32)
target_link_libraries(ClangHLSLTests PRIVATE
dxcompiler
HLSLTestLib
LLVMDxilContainer
LLVMDxilDia
${TAEF_LIBRARIES}
${DIASDK_LIBRARIES}
${D3D12_LIBRARIES}
shlwapi
)
else(WIN32)
target_link_libraries(ClangHLSLTests
dxcompiler
LLVMDxilDia
HLSLTestLib
)
endif(WIN32)
if(WIN32)
# Add includes for platform helpers and dxc API.
include_directories(${TAEF_INCLUDE_DIRS})
include_directories(${DIASDK_INCLUDE_DIRS})
include_directories(${D3D12_INCLUDE_DIRS})
include_directories(${LLVM_MAIN_INCLUDE_DIR}/dxc/Test)
endif(WIN32)
# Add includes to directly reference intrinsic tables.
include_directories(${CLANG_BINARY_DIR}/lib/Sema)
add_dependencies(ClangHLSLTests dxcompiler)
if (NOT CLANG_INCLUDE_TESTS)
set_output_directory(ClangHLSLTests
${LLVM_RUNTIME_OUTPUT_INTDIR} ${LLVM_LIBRARY_OUTPUT_INTDIR})
if (NOT WIN32)
add_test(NAME test-hlsl-codegen
COMMAND $<TARGET_FILE:ClangHLSLTests> --HlslDataDir
${PROJECT_SOURCE_DIR}/tools/clang/test/HLSL)
endif()
endif()
if(WIN32)
# Add a .user file with settings for te.exe.
file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}" DOS_STYLE_SOURCE_DIR)
file(TO_NATIVE_PATH "${TAEF_BIN_DIR}" DOS_TAEF_BIN_DIR)
configure_file(ClangHLSLTests.vcxproj.user.txt ClangHLSLTests.vcxproj.user)
endif(WIN32)
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/HLSLTestOptions.cpp
|
//===- unittests/HLSL/HLSLTestOptions.cpp ----- Test Options Init -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines and initializes command line options that can be passed to
// HLSL gtests.
//
//===----------------------------------------------------------------------===//
#include "HLSLTestOptions.h"
#include "dxc/Test/WEXAdapter.h"
#include "dxc/WinAdapter.h"
namespace clang {
namespace hlsl {
namespace testOptions {
#define ARG_DEFINE(argname) std::string argname = "";
ARG_LIST(ARG_DEFINE)
} // namespace testOptions
} // namespace hlsl
} // namespace clang
namespace WEX {
namespace TestExecution {
namespace RuntimeParameters {
HRESULT TryGetValue(const wchar_t *param, WEX::Common::String &retStr) {
#define RETURN_ARG(argname) \
if (wcscmp(param, L## #argname) == 0) { \
if (!clang::hlsl::testOptions::argname.empty()) { \
retStr.assign(CA2W(clang::hlsl::testOptions::argname.c_str()).m_psz); \
return S_OK; \
} else \
return E_FAIL; \
}
ARG_LIST(RETURN_ARG)
return E_NOTIMPL;
}
} // namespace RuntimeParameters
} // namespace TestExecution
} // namespace WEX
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/LinkerTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// LinkerTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/CompilationResult.h"
#include "dxc/Test/HLSLTestData.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/ManagedStatic.h"
#include <memory>
#include <string>
#include <vector>
#include <fstream>
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h" // for IFT macro
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/dxcapi.h"
using namespace std;
using namespace hlsl;
using namespace llvm;
// The test fixture.
#ifdef _WIN32
class LinkerTest {
#else
class LinkerTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(LinkerTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport)
TEST_METHOD(RunLinkResource)
TEST_METHOD(RunLinkModulesDifferentVersions)
TEST_METHOD(RunLinkResourceWithBinding)
TEST_METHOD(RunLinkAllProfiles)
TEST_METHOD(RunLinkFailNoDefine)
TEST_METHOD(RunLinkFailReDefine)
TEST_METHOD(RunLinkGlobalInit)
TEST_METHOD(RunLinkNoAlloca)
TEST_METHOD(RunLinkMatArrayParam)
TEST_METHOD(RunLinkMatParam)
TEST_METHOD(RunLinkMatParamToLib)
TEST_METHOD(RunLinkResRet)
TEST_METHOD(RunLinkToLib)
TEST_METHOD(RunLinkToLibOdNops)
TEST_METHOD(RunLinkToLibExport)
TEST_METHOD(RunLinkToLibExportShadersOnly)
TEST_METHOD(RunLinkFailReDefineGlobal)
TEST_METHOD(RunLinkFailProfileMismatch)
TEST_METHOD(RunLinkFailEntryNoProps)
TEST_METHOD(RunLinkFailSelectRes)
TEST_METHOD(RunLinkToLibWithUnresolvedFunctions)
TEST_METHOD(RunLinkToLibWithUnresolvedFunctionsExports)
TEST_METHOD(RunLinkToLibWithExportNamesSwapped)
TEST_METHOD(RunLinkToLibWithExportCollision)
TEST_METHOD(RunLinkToLibWithUnusedExport)
TEST_METHOD(RunLinkToLibWithNoExports)
TEST_METHOD(RunLinkWithPotentialIntrinsicNameCollisions)
TEST_METHOD(RunLinkWithValidatorVersion)
TEST_METHOD(RunLinkWithInvalidValidatorVersion)
TEST_METHOD(RunLinkWithTempReg)
TEST_METHOD(RunLinkToLibWithGlobalCtor)
TEST_METHOD(LinkSm63ToSm66)
TEST_METHOD(RunLinkWithRootSig)
TEST_METHOD(RunLinkWithDxcResultOutputs)
TEST_METHOD(RunLinkWithDxcResultNames)
TEST_METHOD(RunLinkWithDxcResultRdat)
TEST_METHOD(RunLinkWithDxcResultErrors)
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
void CreateLinker(IDxcLinker **pResultLinker) {
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcLinker, pResultLinker));
}
void Compile(LPCWSTR filename, IDxcBlob **pResultBlob,
llvm::ArrayRef<LPCWSTR> pArguments = {}, LPCWSTR pEntry = L"",
LPCWSTR pShaderTarget = L"lib_6_x") {
std::wstring fullPath = hlsl_test::GetPathToHlslDataFile(filename);
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcLibrary> pLibrary;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
VERIFY_SUCCEEDED(
pLibrary->CreateBlobFromFile(fullPath.c_str(), nullptr, &pSource));
CComPtr<IDxcIncludeHandler> pIncludeHandler;
VERIFY_SUCCEEDED(pLibrary->CreateIncludeHandler(&pIncludeHandler));
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, fullPath.c_str(), pEntry, pShaderTarget,
const_cast<LPCWSTR *>(pArguments.data()), pArguments.size(), nullptr, 0,
pIncludeHandler, &pResult));
CheckOperationSucceeded(pResult, pResultBlob);
}
void CompileLib(LPCWSTR filename, IDxcBlob **pResultBlob,
llvm::ArrayRef<LPCWSTR> pArguments = {},
LPCWSTR pShaderTarget = L"lib_6_x") {
Compile(filename, pResultBlob, pArguments, L"", pShaderTarget);
}
void AssembleLib(LPCWSTR filename, IDxcBlob **pResultBlob) {
std::wstring fullPath = hlsl_test::GetPathToHlslDataFile(filename);
CComPtr<IDxcLibrary> pLibrary;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(
pLibrary->CreateBlobFromFile(fullPath.c_str(), nullptr, &pSource));
CComPtr<IDxcAssembler> pAssembler;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pAssembler->AssembleToContainer(pSource, &pResult));
CheckOperationSucceeded(pResult, pResultBlob);
}
void RegisterDxcModule(LPCWSTR pLibName, IDxcBlob *pBlob,
IDxcLinker *pLinker) {
VERIFY_SUCCEEDED(pLinker->RegisterLibrary(pLibName, pBlob));
}
void Link(LPCWSTR pEntryName, LPCWSTR pShaderModel, IDxcLinker *pLinker,
ArrayRef<LPCWSTR> libNames, llvm::ArrayRef<LPCSTR> pCheckMsgs,
llvm::ArrayRef<LPCSTR> pCheckNotMsgs,
llvm::ArrayRef<LPCWSTR> pArguments = {}, bool bRegEx = false,
IDxcResult **ppResult = nullptr) {
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pLinker->Link(pEntryName, pShaderModel, libNames.data(),
libNames.size(), pArguments.data(),
pArguments.size(), &pResult));
CComPtr<IDxcBlob> pProgram;
CheckOperationSucceeded(pResult, &pProgram);
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pDisassembly;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembly));
std::string IR = BlobToUtf8(pDisassembly);
CheckMsgs(IR.c_str(), IR.size(), pCheckMsgs.data(), pCheckMsgs.size(),
bRegEx);
CheckNotMsgs(IR.c_str(), IR.size(), pCheckNotMsgs.data(),
pCheckNotMsgs.size(), bRegEx);
if (ppResult)
VERIFY_SUCCEEDED(pResult->QueryInterface(ppResult));
}
void LinkCheckMsg(LPCWSTR pEntryName, LPCWSTR pShaderModel,
IDxcLinker *pLinker, ArrayRef<LPCWSTR> libNames,
llvm::ArrayRef<LPCSTR> pErrorMsgs,
llvm::ArrayRef<LPCWSTR> pArguments = {},
bool bRegex = false, IDxcResult **ppResult = nullptr) {
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(pLinker->Link(pEntryName, pShaderModel, libNames.data(),
libNames.size(), pArguments.data(),
pArguments.size(), &pResult));
CheckOperationResultMsgs(pResult, pErrorMsgs.data(), pErrorMsgs.size(),
false, bRegex);
if (ppResult)
VERIFY_SUCCEEDED(pResult->QueryInterface(ppResult));
}
};
bool LinkerTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
TEST_F(LinkerTest, RunLinkResource) {
CComPtr<IDxcBlob> pResLib;
CompileLib(L"..\\CodeGenHLSL\\lib_resource2.hlsl", &pResLib);
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_cs_entry.hlsl", &pEntryLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libResName = L"res";
RegisterDxcModule(libResName, pResLib, pLinker);
Link(L"entry", L"cs_6_0", pLinker, {libResName, libName}, {}, {});
}
TEST_F(LinkerTest, RunLinkResourceWithBinding) {
// These two libraries both have a ConstantBuffer resource named g_buf.
// These are explicitly bound to different slots, and the types don't match.
// This test runs a pass to rename resources to prevent merging of resource
// globals. Then tests linking these, which requires dxil op overload renaming
// because of a typename collision between the two libraries.
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\lib_res_bound1.hlsl", &pLib1);
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\lib_res_bound2.hlsl", &pLib2);
LPCWSTR optOptions[] = {
L"-dxil-rename-resources,prefix=lib1",
L"-dxil-rename-resources,prefix=lib2",
};
CComPtr<IDxcOptimizer> pOptimizer;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
CComPtr<IDxcContainerReflection> pContainerReflection;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&pContainerReflection));
UINT32 partIdx = 0;
VERIFY_SUCCEEDED(pContainerReflection->Load(pLib1));
VERIFY_SUCCEEDED(
pContainerReflection->FindFirstPartKind(DXC_PART_DXIL, &partIdx));
CComPtr<IDxcBlob> pLib1Module;
VERIFY_SUCCEEDED(pContainerReflection->GetPartContent(partIdx, &pLib1Module));
CComPtr<IDxcBlob> pLib1ModuleRenamed;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(pLib1Module, &optOptions[0], 1,
&pLib1ModuleRenamed, nullptr));
pLib1Module.Release();
pLib1.Release();
AssembleToContainer(m_dllSupport, pLib1ModuleRenamed, &pLib1);
VERIFY_SUCCEEDED(pContainerReflection->Load(pLib2));
VERIFY_SUCCEEDED(
pContainerReflection->FindFirstPartKind(DXC_PART_DXIL, &partIdx));
CComPtr<IDxcBlob> pLib2Module;
VERIFY_SUCCEEDED(pContainerReflection->GetPartContent(partIdx, &pLib2Module));
CComPtr<IDxcBlob> pLib2ModuleRenamed;
VERIFY_SUCCEEDED(pOptimizer->RunOptimizer(pLib2Module, &optOptions[1], 1,
&pLib2ModuleRenamed, nullptr));
pLib2Module.Release();
pLib2.Release();
AssembleToContainer(m_dllSupport, pLib2ModuleRenamed, &pLib2);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR lib1Name = L"lib1";
RegisterDxcModule(lib1Name, pLib1, pLinker);
LPCWSTR lib2Name = L"lib2";
RegisterDxcModule(lib2Name, pLib2, pLinker);
Link(L"main", L"cs_6_0", pLinker, {lib1Name, lib2Name}, {}, {});
}
TEST_F(LinkerTest, RunLinkAllProfiles) {
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_entries2.hlsl", &pEntryLib, option);
RegisterDxcModule(libName, pEntryLib, pLinker);
Link(L"vs_main", L"vs_6_0", pLinker, {libName}, {}, {});
Link(L"hs_main", L"hs_6_0", pLinker, {libName}, {}, {});
Link(L"ds_main", L"ds_6_0", pLinker, {libName}, {}, {});
Link(L"gs_main", L"gs_6_0", pLinker, {libName}, {}, {});
Link(L"ps_main", L"ps_6_0", pLinker, {libName}, {}, {});
CComPtr<IDxcBlob> pResLib;
CompileLib(L"..\\CodeGenHLSL\\lib_resource2.hlsl", &pResLib);
LPCWSTR libResName = L"res";
RegisterDxcModule(libResName, pResLib, pLinker);
Link(L"cs_main", L"cs_6_0", pLinker, {libName, libResName}, {}, {});
}
TEST_F(LinkerTest, RunLinkModulesDifferentVersions) {
CComPtr<IDxcLinker> pLinker1, pLinker2, pLinker3;
CreateLinker(&pLinker1);
CreateLinker(&pLinker2);
CreateLinker(&pLinker3);
LPCWSTR libName = L"entry";
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_entries2.hlsl", &pEntryLib, option);
// the 2nd blob is the "good" blob that stays constant
CComPtr<IDxcBlob> pResLib;
CompileLib(L"..\\CodeGenHLSL\\lib_resource2.hlsl", &pResLib);
LPCWSTR libResName = L"res";
// modify the first compiled blob to force it to have a different compiler
// version
CComPtr<IDxcContainerReflection> containerReflection;
IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection,
&containerReflection));
IFT(containerReflection->Load(pEntryLib));
UINT part_index;
VERIFY_SUCCEEDED(containerReflection->FindFirstPartKind(
hlsl::DFCC_CompilerVersion, &part_index));
CComPtr<IDxcBlob> pBlob;
IFT(containerReflection->GetPartContent(part_index, &pBlob));
void *pBlobPtr = pBlob->GetBufferPointer();
std::string commonMismatchStr =
"error: Cannot link libraries with conflicting compiler versions.";
hlsl::DxilCompilerVersion *pDCV = (hlsl::DxilCompilerVersion *)pBlobPtr;
if (pDCV->VersionStringListSizeInBytes) {
// first just get both strings, the compiler version and the commit hash
char *pVersionStringListPtr =
(char *)pBlobPtr + sizeof(hlsl::DxilCompilerVersion);
std::string commitHashStr(pVersionStringListPtr);
std::string oldCommitHashStr = commitHashStr;
std::string compilerVersionStr(pVersionStringListPtr +
commitHashStr.size() + 1);
std::string oldCompilerVersionStr = compilerVersionStr;
// flip a character to change the commit hash
*pVersionStringListPtr = commitHashStr[0] == 'a' ? 'b' : 'a';
// store the modified compiler version part.
RegisterDxcModule(libName, pEntryLib, pLinker1);
// and the "good" version part
RegisterDxcModule(libResName, pResLib, pLinker1);
// 2 blobs with different compiler versions should not be linkable
LinkCheckMsg(L"hs_main", L"hs_6_1", pLinker1, {libName, libResName},
{commonMismatchStr.c_str()});
// reset the modified part back to normal
*pVersionStringListPtr = oldCommitHashStr[0];
// flip a character to change the compiler version
*(pVersionStringListPtr + commitHashStr.size() + 1) =
compilerVersionStr[0] == '1' ? '2' : '1';
// store the modified compiler version part.
RegisterDxcModule(libName, pEntryLib, pLinker2);
// and the "good" version part
RegisterDxcModule(libResName, pResLib, pLinker2);
// 2 blobs with different compiler versions should not be linkable
LinkCheckMsg(L"hs_main", L"hs_6_1", pLinker2, {libName, libResName},
{commonMismatchStr.c_str()});
// reset the modified part back to normal
*(pVersionStringListPtr + commitHashStr.size() + 1) =
oldCompilerVersionStr[0];
} else {
// The blob can't be changed by adding data, since the
// the data after this header could be a subsequent header.
// The test should announce that it can't make any version string
// modifications
#if _WIN32
WEX::Logging::Log::Warning(
L"Cannot modify compiler version string for test");
#else
FAIL() << "Cannot modify compiler version string for test";
#endif
}
// finally, test that a difference is detected if a member of the struct, say
// the major member, is different.
pDCV->Major = pDCV->Major == 2 ? 1 : 2;
// store the modified compiler version part.
RegisterDxcModule(libName, pEntryLib, pLinker3);
// and the "good" version part
RegisterDxcModule(libResName, pResLib, pLinker3);
// 2 blobs with different compiler versions should not be linkable
LinkCheckMsg(L"hs_main", L"hs_6_1", pLinker3, {libName, libResName},
{commonMismatchStr.c_str()});
}
TEST_F(LinkerTest, RunLinkFailNoDefine) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_cs_entry.hlsl", &pEntryLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
LinkCheckMsg(L"entry", L"cs_6_0", pLinker, {libName},
{"Cannot find definition of function"});
}
TEST_F(LinkerTest, RunLinkFailReDefine) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_cs_entry.hlsl", &pEntryLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"entry2";
RegisterDxcModule(libName2, pEntryLib, pLinker);
LinkCheckMsg(L"entry", L"cs_6_0", pLinker, {libName, libName2},
{"Definition already exists for function"});
}
TEST_F(LinkerTest, RunLinkGlobalInit) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_global.hlsl", &pEntryLib, {}, L"lib_6_3");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
Link(L"test", L"ps_6_0", pLinker, {libName},
// Make sure cbuffer load is generated.
{"dx.op.cbufferLoad"}, {});
}
TEST_F(LinkerTest, RunLinkFailReDefineGlobal) {
LPCWSTR option[] = {L"-default-linkage", L"external"};
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_global2.hlsl", &pEntryLib, option,
L"lib_6_3");
CComPtr<IDxcBlob> pLib0;
CompileLib(L"..\\CodeGenHLSL\\lib_global3.hlsl", &pLib0, option, L"lib_6_3");
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\lib_global4.hlsl", &pLib1, option, L"lib_6_3");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName1 = L"lib0";
RegisterDxcModule(libName1, pLib0, pLinker);
LPCWSTR libName2 = L"lib1";
RegisterDxcModule(libName2, pLib1, pLinker);
LinkCheckMsg(L"entry", L"cs_6_0", pLinker, {libName, libName1, libName2},
{"Definition already exists for global variable",
"Resource already exists"});
}
TEST_F(LinkerTest, RunLinkFailProfileMismatch) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_global.hlsl", &pEntryLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
LinkCheckMsg(L"test", L"cs_6_0", pLinker, {libName},
{"Profile mismatch between entry function and target profile"});
}
TEST_F(LinkerTest, RunLinkFailEntryNoProps) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_global.hlsl", &pEntryLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
LinkCheckMsg(L"\01?update@@YAXXZ", L"cs_6_0", pLinker, {libName},
{"Cannot find function property for entry function"});
}
TEST_F(LinkerTest, RunLinkNoAlloca) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_no_alloca.hlsl", &pEntryLib);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\lib_no_alloca.h", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"ps_main", L"ps_6_0", pLinker, {libName, libName2}, {}, {"alloca"});
}
TEST_F(LinkerTest, RunLinkMatArrayParam) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry.hlsl", &pEntryLib);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast.hlsl", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"main", L"ps_6_0", pLinker, {libName, libName2},
{"alloca [24 x float]", "getelementptr [12 x float], [12 x float]*"},
{});
}
TEST_F(LinkerTest, RunLinkMatParam) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast2.hlsl", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"main", L"ps_6_0", pLinker, {libName, libName2},
{"alloca [12 x float]"}, {});
}
TEST_F(LinkerTest, RunLinkMatParamToLib) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName},
// The bitcast cannot be removed because user function call use it as
// argument.
{"bitcast <12 x float>\\* %.* to %class\\.matrix\\.float\\.4\\.3\\*"},
{}, {}, true);
}
TEST_F(LinkerTest, RunLinkResRet) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_out_param_res.hlsl", &pEntryLib);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_out_param_res_imp.hlsl", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"test", L"ps_6_0", pLinker, {libName, libName2}, {}, {"alloca"});
}
TEST_F(LinkerTest, RunLinkToLib) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib,
option);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast2.hlsl", &pLib, option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName, libName2}, {"!llvm.dbg.cu"}, {},
option);
}
TEST_F(LinkerTest, RunLinkToLibOdNops) {
LPCWSTR option[] = {L"-Od"};
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib,
option);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast2.hlsl", &pLib, option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName, libName2},
{"load i32, i32* getelementptr inbounds ([1 x i32], [1 x i32]* "
"@dx.nothing.a, i32 0, i32 0"},
{}, option);
}
TEST_F(LinkerTest, RunLinkToLibExport) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast2.hlsl", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName, libName2},
{"@\"\\01?renamed_test@@", "@\"\\01?cloned_test@@", "@main"},
{"@\"\\01?mat_test", "@renamed_test", "@cloned_test"},
{L"-exports", L"renamed_test,cloned_test=\\01?mat_test@@YA?AV?$vector@M$"
L"02@@V?$vector@M$03@@0AIAV?$matrix@M$03$02@@@Z;main"});
}
TEST_F(LinkerTest, RunLinkToLibExportShadersOnly) {
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast2.hlsl", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName, libName2}, {"@main"},
{"@\"\\01?mat_test"}, {L"-export-shaders-only"});
}
TEST_F(LinkerTest, RunLinkFailSelectRes) {
if (m_ver.SkipDxilVersion(1, 3))
return;
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\lib_select_res_entry.hlsl", &pEntryLib);
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\lib_select_res.hlsl", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
LinkCheckMsg(
L"main", L"ps_6_0", pLinker, {libName, libName2},
{"local resource not guaranteed to map to unique global resource"});
}
TEST_F(LinkerTest, RunLinkToLibWithUnresolvedFunctions) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func1.hlsl", &pLib1,
option);
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func2.hlsl", &pLib2,
option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName1 = L"lib1";
RegisterDxcModule(libName1, pLib1, pLinker);
LPCWSTR libName2 = L"lib2";
RegisterDxcModule(libName2, pLib2, pLinker);
Link(
L"", L"lib_6_3", pLinker, {libName1, libName2},
{"declare float @\"\\01?external_fn1@@YAMXZ\"()",
"declare float @\"\\01?external_fn2@@YAMXZ\"()",
"declare float @\"\\01?external_fn@@YAMXZ\"()",
"define float @\"\\01?lib1_fn@@YAMXZ\"()",
"define float @\"\\01?lib2_fn@@YAMXZ\"()",
"define float @\"\\01?call_lib1@@YAMXZ\"()",
"define float @\"\\01?call_lib2@@YAMXZ\"()"},
{"declare float @\"\\01?unused_fn1", "declare float @\"\\01?unused_fn2"});
}
TEST_F(LinkerTest, RunLinkToLibWithUnresolvedFunctionsExports) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func1.hlsl", &pLib1,
option);
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func2.hlsl", &pLib2,
option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName1 = L"lib1";
RegisterDxcModule(libName1, pLib1, pLinker);
LPCWSTR libName2 = L"lib2";
RegisterDxcModule(libName2, pLib2, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName1, libName2},
{"declare float @\"\\01?external_fn1@@YAMXZ\"()",
"declare float @\"\\01?external_fn2@@YAMXZ\"()",
"declare float @\"\\01?external_fn@@YAMXZ\"()",
"define float @\"\\01?renamed_lib1@@YAMXZ\"()",
"define float @\"\\01?call_lib2@@YAMXZ\"()"},
{"float @\"\\01?unused_fn1", "float @\"\\01?unused_fn2",
"float @\"\\01?lib1_fn", "float @\"\\01?lib2_fn",
"float @\"\\01?call_lib1"},
{L"-exports", L"renamed_lib1=call_lib1", L"-exports", L"call_lib2"});
}
TEST_F(LinkerTest, RunLinkToLibWithExportNamesSwapped) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func1.hlsl", &pLib1,
option);
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func2.hlsl", &pLib2,
option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName1 = L"lib1";
RegisterDxcModule(libName1, pLib1, pLinker);
LPCWSTR libName2 = L"lib2";
RegisterDxcModule(libName2, pLib2, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName1, libName2},
{"declare float @\"\\01?external_fn1@@YAMXZ\"()",
"declare float @\"\\01?external_fn2@@YAMXZ\"()",
"declare float @\"\\01?external_fn@@YAMXZ\"()",
"define float @\"\\01?call_lib1@@YAMXZ\"()",
"define float @\"\\01?call_lib2@@YAMXZ\"()"},
{"float @\"\\01?unused_fn1", "float @\"\\01?unused_fn2",
"float @\"\\01?lib1_fn", "float @\"\\01?lib2_fn"},
{L"-exports", L"call_lib2=call_lib1;call_lib1=call_lib2"});
}
TEST_F(LinkerTest, RunLinkToLibWithExportCollision) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func1.hlsl", &pLib1,
option);
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func2.hlsl", &pLib2,
option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName1 = L"lib1";
RegisterDxcModule(libName1, pLib1, pLinker);
LPCWSTR libName2 = L"lib2";
RegisterDxcModule(libName2, pLib2, pLinker);
LinkCheckMsg(
L"", L"lib_6_3", pLinker, {libName1, libName2},
{"Export name collides with another export: \\01?call_lib2@@YAMXZ"},
{L"-exports", L"call_lib2=call_lib1;call_lib2"});
}
TEST_F(LinkerTest, RunLinkToLibWithUnusedExport) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func1.hlsl", &pLib1,
option);
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func2.hlsl", &pLib2,
option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName1 = L"lib1";
RegisterDxcModule(libName1, pLib1, pLinker);
LPCWSTR libName2 = L"lib2";
RegisterDxcModule(libName2, pLib2, pLinker);
LinkCheckMsg(L"", L"lib_6_3", pLinker, {libName1, libName2},
{"Could not find target for export: call_lib"},
{L"-exports", L"call_lib2=call_lib;call_lib1"});
}
TEST_F(LinkerTest, RunLinkToLibWithNoExports) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug"};
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func1.hlsl", &pLib1,
option);
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_unresolved_func2.hlsl", &pLib2,
option);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName1 = L"lib1";
RegisterDxcModule(libName1, pLib1, pLinker);
LPCWSTR libName2 = L"lib2";
RegisterDxcModule(libName2, pLib2, pLinker);
LinkCheckMsg(L"", L"lib_6_3", pLinker, {libName1, libName2},
{"Library has no functions to export"},
{L"-exports", L"call_lib2=call_lib"});
}
TEST_F(LinkerTest, RunLinkWithPotentialIntrinsicNameCollisions) {
LPCWSTR option[] = {L"-Zi", L"-Qembed_debug", L"-default-linkage",
L"external"};
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\createHandle_multi.hlsl", &pLib1,
option, L"lib_6_3");
CComPtr<IDxcBlob> pLib2;
CompileLib(L"..\\CodeGenHLSL\\linker\\createHandle_multi2.hlsl", &pLib2,
option, L"lib_6_3");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName1 = L"lib1";
RegisterDxcModule(libName1, pLib1, pLinker);
LPCWSTR libName2 = L"lib2";
RegisterDxcModule(libName2, pLib2, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName1, libName2},
{"declare %dx.types.Handle "
"@\"dx.op.createHandleForLib.class.Texture2D<vector<float, 4> >\"(i32, "
"%\"class.Texture2D<vector<float, 4> >\")",
"declare %dx.types.Handle "
"@\"dx.op.createHandleForLib.class.Texture2D<float>\"(i32, "
"%\"class.Texture2D<float>\")"},
{});
}
TEST_F(LinkerTest, RunLinkWithValidatorVersion) {
if (m_ver.SkipDxilVersion(1, 4))
return;
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib, {});
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast2.hlsl", &pLib, {});
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
Link(L"", L"lib_6_3", pLinker, {libName, libName2},
{"!dx.valver = !{(![0-9]+)}.*\n\\1 = !{i32 1, i32 3}"}, {},
{L"-validator-version", L"1.3"}, /*regex*/ true);
}
TEST_F(LinkerTest, RunLinkWithInvalidValidatorVersion) {
if (m_ver.SkipDxilVersion(1, 4))
return;
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_entry2.hlsl", &pEntryLib, {});
CComPtr<IDxcBlob> pLib;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_mat_cast2.hlsl", &pLib, {});
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"ps_main";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libName2 = L"test";
RegisterDxcModule(libName2, pLib, pLinker);
LinkCheckMsg(L"", L"lib_6_3", pLinker, {libName, libName2},
{"Validator version does not support target profile lib_6_3"},
{L"-validator-version", L"1.2"});
}
TEST_F(LinkerTest, RunLinkWithTempReg) {
// TempRegLoad/TempRegStore not normally usable from HLSL.
// This assembly library exposes these through overloaded wrapper functions
// void sreg(uint index, <type> value) to store register, overloaded for uint,
// int, and float uint ureg(uint index) to load register as uint int ireg(int
// index) to load register as int float freg(uint index) to load register as
// float
// This test verifies this scenario works, by assembling this library,
// compiling a library with an entry point that uses sreg/ureg,
// then linking these to a final standard vs_6_0 DXIL shader.
CComPtr<IDxcBlob> pTempRegLib;
AssembleLib(L"..\\HLSLFileCheck\\dxil\\linker\\TempReg.ll", &pTempRegLib);
CComPtr<IDxcBlob> pEntryLib;
CompileLib(L"..\\HLSLFileCheck\\dxil\\linker\\use-TempReg.hlsl", &pEntryLib,
{L"-validator-version", L"1.3"}, L"lib_6_3");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"entry";
RegisterDxcModule(libName, pEntryLib, pLinker);
LPCWSTR libResName = L"TempReg";
RegisterDxcModule(libResName, pTempRegLib, pLinker);
Link(L"main", L"vs_6_0", pLinker, {libResName, libName},
{"call void @dx.op.tempRegStore.i32", "call i32 @dx.op.tempRegLoad.i32"},
{});
}
TEST_F(LinkerTest, RunLinkToLibWithGlobalCtor) {
CComPtr<IDxcBlob> pLib0;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_static_cb_init.hlsl", &pLib0, {});
CComPtr<IDxcBlob> pLib1;
CompileLib(L"..\\CodeGenHLSL\\linker\\lib_use_static_cb_init.hlsl", &pLib1,
{});
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"foo";
RegisterDxcModule(libName, pLib0, pLinker);
LPCWSTR libName2 = L"bar";
RegisterDxcModule(libName2, pLib1, pLinker);
// Make sure global_ctors created for lib to lib.
Link(L"", L"lib_6_3", pLinker, {libName, libName2},
{"@llvm.global_ctors = appending global [1 x { i32, void ()*, i8* }] [{ "
"i32, void ()*, i8* } { i32 65535, void ()* "
"@foo._GLOBAL__sub_I_lib_static_cb_init.hlsl, i8* null }]"},
{}, {});
}
TEST_F(LinkerTest, LinkSm63ToSm66) {
if (m_ver.SkipDxilVersion(1, 6))
return;
CComPtr<IDxcBlob> pLib0;
CompileLib(L"..\\CodeGenHLSL\\linker\\link_to_sm66.hlsl", &pLib0, {},
L"lib_6_3");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"foo";
RegisterDxcModule(libName, pLib0, pLinker);
// Make sure add annotateHandle when link lib_6_3 to ps_6_6.
Link(L"ps_main", L"ps_6_6", pLinker, {libName},
{"call %dx.types.Handle @dx.op.annotateHandle\\(i32 216, "
"%dx.types.Handle "
"%(.*), %dx.types.ResourceProperties { i32 13, i32 4 }\\)"},
{}, {}, true);
}
TEST_F(LinkerTest, RunLinkWithRootSig) {
CComPtr<IDxcBlob> pLib0;
CompileLib(L"..\\CodeGenHLSL\\linker\\link_with_root_sig.hlsl", &pLib0,
{L"-HV", L"2018"}, L"lib_6_x");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
LPCWSTR libName = L"foo";
RegisterDxcModule(libName, pLib0, pLinker);
LPCWSTR pEntryName = L"vs_main";
LPCWSTR pShaderModel = L"vs_6_6";
LPCWSTR libNames[] = {libName};
CComPtr<IDxcOperationResult> pResult;
VERIFY_SUCCEEDED(
pLinker->Link(pEntryName, pShaderModel, libNames, 1, {}, 0, &pResult));
CComPtr<IDxcBlob> pLinkedProgram;
CheckOperationSucceeded(pResult, &pLinkedProgram);
VERIFY_IS_TRUE(pLinkedProgram);
CComPtr<IDxcBlob> pProgram;
Compile(L"..\\CodeGenHLSL\\linker\\link_with_root_sig.hlsl", &pProgram,
{L"-HV", L"2018"}, pEntryName, pShaderModel);
VERIFY_IS_TRUE(pProgram);
const DxilContainerHeader *pLinkedContainer = IsDxilContainerLike(
pLinkedProgram->GetBufferPointer(), pLinkedProgram->GetBufferSize());
VERIFY_IS_TRUE(pLinkedContainer);
const DxilContainerHeader *pContainer = IsDxilContainerLike(
pProgram->GetBufferPointer(), pProgram->GetBufferSize());
VERIFY_IS_TRUE(pContainer);
const DxilPartHeader *pLinkedRSPart =
GetDxilPartByType(pLinkedContainer, DFCC_RootSignature);
VERIFY_IS_TRUE(pLinkedRSPart);
const DxilPartHeader *pRSPart =
GetDxilPartByType(pContainer, DFCC_RootSignature);
VERIFY_IS_TRUE(pRSPart);
VERIFY_IS_TRUE(pRSPart->PartSize == pLinkedRSPart->PartSize);
const uint8_t *pRS = (const uint8_t *)GetDxilPartData(pRSPart);
const uint8_t *pLinkedRS = (const uint8_t *)GetDxilPartData(pLinkedRSPart);
for (unsigned i = 0; i < pLinkedRSPart->PartSize; i++) {
VERIFY_IS_TRUE(pRS[i] == pLinkedRS[i]);
}
}
// Discriminate between the two different forms of outputs
// we handle from IDxcResult outputs.
enum OutputBlobKind {
OUTPUT_IS_RAW_DATA, // Output is raw data.
OUTPUT_IS_CONTAINER, // Output is wrapped in its own dxil container.
};
// Verify that the contents of the IDxcResult matches what is in the
// dxil container. Some of the output data in the IDxcResult is wrapped
// in a dxil container so we can optionally retrieve that data based
// on the `OutputBlobKind` parameter.
static void VerifyPartsMatch(const DxilContainerHeader *pContainer,
hlsl::DxilFourCC DxilPart, IDxcResult *pResult,
DXC_OUT_KIND ResultKind,
OutputBlobKind OutputBlobKind,
LPCWSTR pResultName = nullptr) {
const DxilPartHeader *pPart = GetDxilPartByType(pContainer, DxilPart);
VERIFY_IS_NOT_NULL(pPart);
CComPtr<IDxcBlob> pOutBlob;
CComPtr<IDxcBlobWide> pOutObjName;
VERIFY_IS_TRUE(pResult->HasOutput(ResultKind));
VERIFY_SUCCEEDED(
pResult->GetOutput(ResultKind, IID_PPV_ARGS(&pOutBlob), &pOutObjName));
LPVOID PartData = (LPVOID)GetDxilPartData(pPart);
SIZE_T PartSize = pPart->PartSize;
LPVOID OutData = pOutBlob->GetBufferPointer();
SIZE_T OutSize = pOutBlob->GetBufferSize();
if (OutputBlobKind == OUTPUT_IS_CONTAINER) {
const DxilContainerHeader *pOutContainer =
IsDxilContainerLike(OutData, OutSize);
VERIFY_IS_NOT_NULL(pOutContainer);
const DxilPartHeader *pOutPart = GetDxilPartByType(pOutContainer, DxilPart);
VERIFY_IS_NOT_NULL(pOutPart);
OutData = (LPVOID)GetDxilPartData(pOutPart);
OutSize = pOutPart->PartSize;
}
VERIFY_ARE_EQUAL(OutSize, PartSize);
VERIFY_IS_TRUE(0 == memcmp(OutData, PartData, PartSize));
if (pResultName) {
VERIFY_IS_TRUE(pOutObjName->GetStringLength() == wcslen(pResultName));
VERIFY_IS_TRUE(0 == wcsncmp(pOutObjName->GetStringPointer(), pResultName,
pOutObjName->GetStringLength()));
}
}
// Check that the output exists in the IDxcResult and optionally validate the
// name.
void VerifyHasOutput(IDxcResult *pResult, DXC_OUT_KIND ResultKind, REFIID riid,
LPVOID *ppV, LPCWSTR pResultName = nullptr) {
CComPtr<IDxcBlob> pOutBlob;
CComPtr<IDxcBlobWide> pOutObjName;
VERIFY_IS_TRUE(pResult->HasOutput(ResultKind));
VERIFY_SUCCEEDED(pResult->GetOutput(ResultKind, riid, ppV, &pOutObjName));
if (pResultName) {
VERIFY_IS_TRUE(pOutObjName->GetStringLength() == wcslen(pResultName));
VERIFY_IS_TRUE(0 == wcsncmp(pOutObjName->GetStringPointer(), pResultName,
pOutObjName->GetStringLength()));
}
}
// Test that validates the DxcResult outputs after linking.
//
// Checks for DXC_OUT_OBJECT, DXC_OUT_ROOT_SIGNATURE, DXC_OUT_SHADER_HASH.
//
// Exercises the case that the outputs exist even when they
// are not given an explicit name (e.g. with /Fo).
TEST_F(LinkerTest, RunLinkWithDxcResultOutputs) {
CComPtr<IDxcBlob> pLib;
LPCWSTR LibName = L"MyLib.lib";
CompileLib(L"..\\CodeGenHLSL\\linker\\link_with_root_sig.hlsl", &pLib,
{L"-HV", L"2018", L"/Fo", LibName}, L"lib_6_x");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
RegisterDxcModule(LibName, pLib, pLinker);
CComPtr<IDxcResult> pLinkResult;
Link(L"vs_main", L"vs_6_6", pLinker, {LibName}, {}, {}, {}, false,
&pLinkResult);
// Validate the output contains the DXC_OUT_OBJECT.
CComPtr<IDxcBlob> pBlob;
VerifyHasOutput(pLinkResult, DXC_OUT_OBJECT, IID_PPV_ARGS(&pBlob));
// Get the container header from the output.
const DxilContainerHeader *pContainer =
IsDxilContainerLike(pBlob->GetBufferPointer(), pBlob->GetBufferSize());
VERIFY_IS_NOT_NULL(pContainer);
// Check that the output from the DxcResult matches the data in the container.
VerifyPartsMatch(pContainer, DFCC_RootSignature, pLinkResult,
DXC_OUT_ROOT_SIGNATURE, OUTPUT_IS_CONTAINER);
VerifyPartsMatch(pContainer, DFCC_ShaderHash, pLinkResult,
DXC_OUT_SHADER_HASH, OUTPUT_IS_RAW_DATA);
}
// Test that validates the DxcResult outputs after linking.
//
// Checks for DXC_OUT_OBJECT, DXC_OUT_ROOT_SIGNATURE, DXC_OUT_SHADER_HASH.
//
// Exercises the case that the outputs are retrieved with
// the expected names.
TEST_F(LinkerTest, RunLinkWithDxcResultNames) {
CComPtr<IDxcBlob> pLib;
LPCWSTR LibName = L"MyLib.lib";
CompileLib(L"..\\CodeGenHLSL\\linker\\link_with_root_sig.hlsl", &pLib,
{L"-HV", L"2018", L"/Fo", LibName}, L"lib_6_x");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
RegisterDxcModule(LibName, pLib, pLinker);
LPCWSTR ObjectName = L"MyLib.vso";
LPCWSTR RootSigName = L"Rootsig.bin";
LPCWSTR HashName = L"Hash.bin";
CComPtr<IDxcResult> pLinkResult;
Link(L"vs_main", L"vs_6_6", pLinker, {LibName}, {}, {},
{L"/Fo", ObjectName, L"/Frs", RootSigName, L"/Fsh", HashName}, false,
&pLinkResult);
CComPtr<IDxcBlob> pObjBlob, pRsBlob, pHashBlob;
VerifyHasOutput(pLinkResult, DXC_OUT_OBJECT, IID_PPV_ARGS(&pObjBlob),
ObjectName);
VerifyHasOutput(pLinkResult, DXC_OUT_ROOT_SIGNATURE, IID_PPV_ARGS(&pRsBlob),
RootSigName);
VerifyHasOutput(pLinkResult, DXC_OUT_SHADER_HASH, IID_PPV_ARGS(&pHashBlob),
HashName);
}
// Test that validates the DxcResult outputs after linking.
//
// Checks for DXC_OUT_REFLECTION
//
// This is done as a separate test because the reflection output
// is only available for library targets.
TEST_F(LinkerTest, RunLinkWithDxcResultRdat) {
CComPtr<IDxcBlob> pLib;
LPCWSTR LibName = L"MyLib.lib";
CompileLib(L"..\\CodeGenHLSL\\linker\\createHandle_multi.hlsl", &pLib,
L"lib_6_x");
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
RegisterDxcModule(LibName, pLib, pLinker);
// Test that we get the IDxcResult outputs even without setting the name.
{
CComPtr<IDxcResult> pLinkResult;
Link(L"", L"lib_6_3", pLinker, {LibName}, {}, {}, {}, false, &pLinkResult);
CComPtr<IDxcBlob> pReflBlob;
VerifyHasOutput(pLinkResult, DXC_OUT_REFLECTION, IID_PPV_ARGS(&pReflBlob));
}
// Test that we get the name set in the IDxcResult outputs.
{
LPCWSTR ReflName = L"MyLib.vso";
CComPtr<IDxcResult> pLinkResult;
Link(L"", L"lib_6_3", pLinker, {LibName}, {}, {},
{
L"/Fre",
ReflName,
},
false, &pLinkResult);
CComPtr<IDxcBlob> pReflBlob;
VerifyHasOutput(pLinkResult, DXC_OUT_REFLECTION, IID_PPV_ARGS(&pReflBlob),
ReflName);
}
}
// Test that validates the DxcResult outputs after linking.
//
// Checks for DXC_OUT_ERRORS
//
// This is done as a separate test because we need to generate an error
// message by failing the link job.
TEST_F(LinkerTest, RunLinkWithDxcResultErrors) {
CComPtr<IDxcBlob> pLib;
LPCWSTR LibName = L"MyLib.lib";
CompileLib(L"..\\CodeGenHLSL\\lib_cs_entry.hlsl", &pLib);
CComPtr<IDxcLinker> pLinker;
CreateLinker(&pLinker);
RegisterDxcModule(LibName, pLib, pLinker);
// Test that we get the IDxcResult error outputs without setting the name.
const char *ErrorMessage =
"error: Cannot find definition of function non_existent_entry\n";
{
CComPtr<IDxcResult> pLinkResult;
LinkCheckMsg(L"non_existent_entry", L"cs_6_0", pLinker, {LibName},
{ErrorMessage}, {}, false, &pLinkResult);
CComPtr<IDxcBlobUtf8> pErrorOutput;
VerifyHasOutput(pLinkResult, DXC_OUT_ERRORS, IID_PPV_ARGS(&pErrorOutput));
VERIFY_IS_TRUE(pErrorOutput->GetStringLength() == strlen(ErrorMessage));
VERIFY_IS_TRUE(0 == strncmp(pErrorOutput->GetStringPointer(), ErrorMessage,
pErrorOutput->GetStringLength()));
}
// Test that we get the name set in the IDxcResult error output.
{
LPCWSTR ErrName = L"Errors.txt";
CComPtr<IDxcResult> pLinkResult;
LinkCheckMsg(L"non_existent_entry", L"cs_6_0", pLinker, {LibName},
{ErrorMessage}, {L"/Fe", ErrName}, false, &pLinkResult);
CComPtr<IDxcBlobUtf8> pErrorOutput;
VerifyHasOutput(pLinkResult, DXC_OUT_ERRORS, IID_PPV_ARGS(&pErrorOutput),
ErrName);
VERIFY_IS_TRUE(pErrorOutput->GetStringLength() == strlen(ErrorMessage));
VERIFY_IS_TRUE(0 == strncmp(pErrorOutput->GetStringPointer(), ErrorMessage,
pErrorOutput->GetStringLength()));
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/Objects.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// Objects.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/CompilationResult.h"
#include "dxc/Test/HLSLTestData.h"
#include <stdint.h>
#include "dxc/Test/HlslTestUtils.h"
#include <exception>
#include <set>
///////////////////////////////////////////////////////////////////////////////
// Utilities.
namespace std {
/// Returns the first element of the container.
template <class Container>
auto first(Container &cont) -> decltype(*begin(cont)) {
auto iter = begin(cont);
return *iter;
}
/// Returns the first element of the container or the default value if empty.
template <typename Container, typename ElementType>
ElementType first_or_default(Container &cont, const ElementType &defaultValue) {
auto iter = begin(cont);
auto endIter = end(cont);
if (iter == endIter)
return defaultValue;
return *iter;
}
} // namespace std
template <typename TEnumeration> class EnumFlagsIterator {
private:
unsigned long _value;
public:
using iterator_category = std::input_iterator_tag;
using value_type = TEnumeration;
using difference_type = std::ptrdiff_t;
using pointer = value_type *;
using reference = value_type &;
EnumFlagsIterator(TEnumeration value) : _value(value) {}
TEnumeration operator*() const {
unsigned long l;
_BitScanForward(&l, _value);
return static_cast<TEnumeration>(1 << l);
}
EnumFlagsIterator<TEnumeration> &operator++() {
unsigned long l;
_BitScanForward(&l, _value);
_value = _value & ~(1 << l);
return *this;
}
bool equal(const EnumFlagsIterator<TEnumeration> &other) {
return _value == other._value;
}
bool operator==(const EnumFlagsIterator<TEnumeration> &other) {
return _value == other._value;
}
bool operator!=(const EnumFlagsIterator<TEnumeration> &other) {
return _value != other._value;
}
};
///////////////////////////////////////////////////////////////////////////////
// Shader model test data.
enum ShaderModel { ShaderModel4 = 4, ShaderModel5 = 5 };
enum ShaderType {
/// Vertex shader.
ST_Vertex = 1 << 0,
/// Hull shader.
ST_Hull = 1 << 1,
/// Domain shader.
ST_Domain = 1 << 2,
/// Geometry shader type.
ST_Geometry = 1 << 3,
/// Pixel shader type.
ST_Pixel = 1 << 4,
/// Compute shader type.
ST_Compute = 1 << 5,
/// Hull and geometry shader types.
ST_HullGeometry = ST_Hull | ST_Geometry,
/// Hull and domain shader types.
ST_HullDomain = ST_Hull | ST_Domain,
/// Pixel and compute shader types.
ST_PixelCompute = ST_Pixel | ST_Compute,
/// All shader types.
ST_All = ST_Vertex | ST_Hull | ST_Domain | ST_Geometry | ST_Pixel | ST_Compute
};
typedef EnumFlagsIterator<ShaderType> ShaderTypeIterator;
ShaderTypeIterator begin(ShaderType value) { return ShaderTypeIterator(value); }
ShaderTypeIterator end(ShaderType value) {
return ShaderTypeIterator((ShaderType)0);
}
/// Enumerates types of shader objects like textures or buffers.
enum ShaderObjectKind {
/// Output buffer that appears as a stream the shader may append to.
SOK_AppendStructuredBuffer,
///
SOK_Buffer,
SOK_ByteAddressBuffer,
/// An input buffer that appears as a stream the shader may pull values from.
SOK_ConsumeStructuredBuffer,
/// Represents an array of control points that are available to the hull
/// shader as inputs.
SOK_InputPatch,
/// Represents an array of output control points that are available to the
/// hull shader's patch-constant function as well as the domain shader.
SOK_OutputPatch,
/// A read/write buffer.
SOK_RWBuffer,
/// A read/write buffer that indexes in bytes.
SOK_RWByteAddressBuffer,
/// A read/write buffer that can take a T type that is a structure.
SOK_RWStructuredBuffer,
/// A read/write resource.
SOK_RWTexture1D,
/// A read/write resource.
SOK_RWTexture1DArray,
/// A read/write resource.
SOK_RWTexture2D,
/// A read/write resource.
SOK_RWTexture2DArray,
/// A read/write resource.
SOK_RWTexture3D,
/// A stream-output object is a templated object that streams data out of the
/// geometry-shader stage.
SOK_StreamOutputLine,
/// A stream-output object is a templated object that streams data out of the
/// geometry-shader stage.
SOK_StreamOutputPoint,
/// A stream-output object is a templated object that streams data out of the
/// geometry-shader stage.
SOK_StreamOutputTriangle,
/// A read-only buffer, which can take a T type that is a structure.
SOK_StructuredBuffer,
/// A read-only resource.
SOK_Texture1D,
/// A read-only resource.
SOK_Texture1DArray,
/// A read-only resource.
SOK_Texture2D,
/// A read-only resource.
SOK_Texture2DArray,
/// A read-only resource.
SOK_Texture2DMS,
/// A read-only resource.
SOK_Texture2DArrayMS,
/// A read-only resource.
SOK_Texture3D,
/// A read-only resource.
SOK_TextureCube,
/// A read-only resource.
SOK_TextureCubeArray
};
struct ShaderObjectDataItem {
ShaderObjectKind Kind;
const char *TypeName;
ShaderModel MinShaderModel;
ShaderType ValidShaderTypes;
};
static const ShaderObjectDataItem ShaderObjectData[] = {
{SOK_AppendStructuredBuffer, "AppendStructuredBuffer", ShaderModel5,
ST_PixelCompute},
{SOK_Buffer, "Buffer", ShaderModel5, ST_All},
{SOK_ByteAddressBuffer, "ByteAddressBuffer", ShaderModel5, ST_All},
{SOK_ConsumeStructuredBuffer, "ConsumeStructuredBuffer", ShaderModel5,
ST_PixelCompute},
{SOK_InputPatch, "InputPatch", ShaderModel5, ST_HullGeometry},
{SOK_OutputPatch, "OutputPatch", ShaderModel5, ST_HullDomain},
{SOK_RWBuffer, "RWBuffer", ShaderModel5, ST_PixelCompute},
{SOK_RWByteAddressBuffer, "RWByteAddressBuffer", ShaderModel5,
ST_PixelCompute},
{SOK_RWStructuredBuffer, "RWStructuredBuffer", ShaderModel5,
ST_PixelCompute},
{SOK_RWTexture1D, "RWTexture1D", ShaderModel5, ST_PixelCompute},
{SOK_RWTexture1DArray, "RWTexture1DArray", ShaderModel5, ST_PixelCompute},
{SOK_RWTexture2D, "RWTexture2D", ShaderModel5, ST_PixelCompute},
{SOK_RWTexture2DArray, "RWTexture2DArray", ShaderModel5, ST_PixelCompute},
{SOK_RWTexture3D, "RWTexture3D", ShaderModel5, ST_PixelCompute},
{SOK_StreamOutputLine, "LineStream", ShaderModel4, ST_Geometry},
{SOK_StreamOutputPoint, "PointStream", ShaderModel4, ST_Geometry},
{SOK_StreamOutputTriangle, "TriangleStream", ShaderModel4, ST_Geometry},
{SOK_StructuredBuffer, "StructuredBuffer", ShaderModel5, ST_All},
{SOK_Texture1D, "Texture1D", ShaderModel4, ST_All},
{SOK_Texture1DArray, "Texture1DArray", ShaderModel4, ST_All},
{SOK_Texture2D, "Texture2D", ShaderModel4, ST_All},
{SOK_Texture2DArray, "Texture2DArray", ShaderModel4, ST_All},
{SOK_Texture2DMS, "Texture2DMS", ShaderModel4, ST_All},
{SOK_Texture2DArrayMS, "Texture2DMSArray", ShaderModel4, ST_All},
{SOK_Texture3D, "Texture3D", ShaderModel4, ST_All},
{SOK_TextureCube, "TextureCube", ShaderModel4, ST_All},
{SOK_TextureCubeArray, "TextureCubeArray", ShaderModel4, ST_All}};
/// Enumerates the template shapes.
/// This is a crude simplification of what the type system could do,
/// but it covers all cases without unused generality.
enum ShaderObjectTemplateKind {
/// No parameters.
SOTK_NoParams,
/// Single parameter of type scalar or vector.
SOTK_SingleSVParam,
/// Single parameter of type scalar, vector or struct.
SOTK_SingleSVCParam,
/// Two parameters; a scalar or vector type and a sample count.
SOTK_SVAndSampleCountParams,
/// Two parameters; a scalar or vector type and a control point count (1-32).
SOTK_SVCAndControlPointCountParams
};
struct ShaderObjectTemplateDataItem {
ShaderObjectKind Kind;
ShaderObjectTemplateKind TemplateKind;
bool TemplateParamsOptional;
};
static const bool OptionalTrue = true;
static const bool OptionalFalse = false;
static const ShaderObjectTemplateDataItem ShaderObjectTemplateData[] = {
{SOK_AppendStructuredBuffer, SOTK_SingleSVCParam, OptionalFalse},
{SOK_Buffer, SOTK_SingleSVParam, OptionalFalse},
{SOK_ByteAddressBuffer, SOTK_NoParams, OptionalTrue},
{SOK_ConsumeStructuredBuffer, SOTK_SingleSVCParam, OptionalFalse},
{SOK_InputPatch, SOTK_SVCAndControlPointCountParams, OptionalFalse},
{SOK_OutputPatch, SOTK_SVCAndControlPointCountParams, OptionalFalse},
{SOK_RWBuffer, SOTK_SingleSVParam, OptionalFalse},
{SOK_RWByteAddressBuffer, SOTK_NoParams, OptionalTrue},
{SOK_RWStructuredBuffer, SOTK_SingleSVCParam, OptionalFalse},
{SOK_RWTexture1D, SOTK_SingleSVParam, OptionalFalse},
{SOK_RWTexture1DArray, SOTK_SingleSVParam, OptionalFalse},
{SOK_RWTexture2D, SOTK_SingleSVParam, OptionalFalse},
{SOK_RWTexture2DArray, SOTK_SingleSVParam, OptionalFalse},
{SOK_RWTexture3D, SOTK_SingleSVParam, OptionalFalse},
{SOK_StreamOutputLine, SOTK_SingleSVCParam, OptionalFalse},
{SOK_StreamOutputPoint, SOTK_SingleSVCParam, OptionalFalse},
{SOK_StreamOutputTriangle, SOTK_SingleSVCParam, OptionalFalse},
{SOK_StructuredBuffer, SOTK_SingleSVCParam, OptionalFalse},
{SOK_Texture1D, SOTK_SingleSVParam, OptionalTrue},
{SOK_Texture1DArray, SOTK_SingleSVParam, OptionalTrue},
{SOK_Texture2D, SOTK_SingleSVParam, OptionalTrue},
{SOK_Texture2DArray, SOTK_SingleSVParam, OptionalTrue},
{SOK_Texture2DMS, SOTK_SVAndSampleCountParams, OptionalFalse},
{SOK_Texture2DArrayMS, SOTK_SVAndSampleCountParams, OptionalFalse},
{SOK_Texture3D, SOTK_SingleSVParam, OptionalTrue},
{SOK_TextureCube, SOTK_SingleSVParam, OptionalTrue},
{SOK_TextureCubeArray, SOTK_SingleSVParam, OptionalTrue}};
static const ShaderObjectTemplateDataItem &
GetTemplateData(const ShaderObjectDataItem &sod) {
static_assert(_countof(ShaderObjectTemplateData) ==
_countof(ShaderObjectData),
"otherwise lookup tables have different elements");
struct Unary {
ShaderObjectKind ObjectKind;
Unary(ShaderObjectKind ok) : ObjectKind(ok) {}
bool operator()(const ShaderObjectTemplateDataItem &i) {
return i.Kind == ObjectKind;
}
};
Unary filter(sod.Kind);
auto iter = std::find_if(std::begin(ShaderObjectTemplateData),
std::end(ShaderObjectTemplateData), filter);
assert(iter != std::end(ShaderObjectTemplateData));
return *iter;
}
static int CountOptionalTemplateArguments(
const ShaderObjectTemplateDataItem &templateData) {
if (!templateData.TemplateParamsOptional) {
return 0;
}
switch (templateData.TemplateKind) {
default:
case SOTK_NoParams:
return 0;
case SOTK_SingleSVParam:
return 1;
case SOTK_SingleSVCParam:
return 1;
case SOTK_SVAndSampleCountParams:
return 2;
case SOTK_SVCAndControlPointCountParams:
return 2;
}
}
// - a RWBuffer supports globallycoherent storage class to generate memory
// barriers
// TODO: ByteAddressBuffer is supported on SM4 on compute shaders
// TODO: RWByteAddressBuffer is supported on SM4 on compute shaders
// TODO: RWStructuredBuffer is supported on SM4 on compute shaders
#include "dxc/HlslIntrinsicOp.h"
#include "dxc/dxcapi.internal.h"
#include "gen_intrin_main_tables_15.h"
struct ShaderObjectIntrinsicDataItem {
// Kind of shader object described.
ShaderObjectKind Kind;
// Pointer to first intrinsic in table.
const HLSL_INTRINSIC *Intrinsics;
// Count of elements in intrinsic table.
size_t IntrinsicCount;
};
// The test that requires this is pending complete
// support for primitive types
#if 0
const ShaderObjectIntrinsicDataItem ShaderObjectIntrinsicData[] = {
{ SOK_AppendStructuredBuffer, g_AppendStructuredBufferMethods, _countof(g_AppendStructuredBufferMethods) },
{ SOK_Buffer, g_BufferMethods, _countof(g_BufferMethods) },
{ SOK_ByteAddressBuffer, g_ByteAddressBufferMethods, _countof(g_ByteAddressBufferMethods) },
{ SOK_ConsumeStructuredBuffer, g_ConsumeStructuredBufferMethods, _countof(g_ByteAddressBufferMethods) },
{ SOK_InputPatch, nullptr, 0 },
{ SOK_OutputPatch, nullptr, 0 },
{ SOK_RWBuffer, g_RWBufferMethods, _countof(g_RWBufferMethods) },
{ SOK_RWByteAddressBuffer, g_RWByteAddressBufferMethods, _countof(g_RWByteAddressBufferMethods) },
{ SOK_RWStructuredBuffer, g_RWStructuredBufferMethods, _countof(g_RWStructuredBufferMethods) },
{ SOK_RWTexture1D, g_RWTexture1DMethods, _countof(g_RWTexture1DMethods) },
{ SOK_RWTexture1DArray, g_RWTexture1DArrayMethods, _countof(g_RWTexture1DArrayMethods) },
{ SOK_RWTexture2D, g_RWTexture2DMethods, _countof(g_RWTexture2DMethods) },
{ SOK_RWTexture2DArray, g_RWTexture2DArrayMethods, _countof(g_RWTexture2DArrayMethods) },
{ SOK_RWTexture3D, g_RWTexture3DMethods, _countof(g_RWTexture3DMethods) },
{ SOK_StreamOutputLine, g_StreamMethods, _countof(g_StreamMethods) },
{ SOK_StreamOutputPoint, g_StreamMethods, _countof(g_StreamMethods) },
{ SOK_StreamOutputTriangle, g_StreamMethods, _countof(g_StreamMethods) },
{ SOK_StructuredBuffer, g_StructuredBufferMethods, _countof(g_StructuredBufferMethods) },
{ SOK_Texture1D, g_Texture1DMethods, _countof(g_Texture1DMethods) },
{ SOK_Texture1DArray, g_Texture1DArrayMethods, _countof(g_Texture1DArrayMethods) },
{ SOK_Texture2D, g_Texture2DMethods, _countof(g_Texture2DMethods) },
{ SOK_Texture2DArray, g_Texture2DArrayMethods, _countof(g_Texture2DArrayMethods) },
{ SOK_Texture2DMS, g_Texture2DMSMethods, _countof(g_Texture2DMSMethods) },
{ SOK_Texture2DArrayMS, g_Texture2DArrayMSMethods, _countof(g_Texture2DArrayMSMethods) },
{ SOK_Texture3D, g_Texture3DMethods, _countof(g_Texture3DMethods) },
{ SOK_TextureCube, g_TextureCUBEMethods, _countof(g_TextureCUBEMethods) },
{ SOK_TextureCubeArray, g_TextureCUBEArrayMethods, _countof(g_TextureCUBEArrayMethods) }
};
static
const ShaderObjectIntrinsicDataItem& GetIntrinsicData(const ShaderObjectDataItem& sod)
{
for (unsigned i = 0; i < _countof(ShaderObjectIntrinsicData); i++)
{
if (sod.Kind == ShaderObjectIntrinsicData[i].Kind)
{
return ShaderObjectIntrinsicData[i];
}
}
throw std::runtime_error("cannot find shader object kind");
}
#endif
// The test fixture.
#ifdef _WIN32
class ObjectTest {
#else
class ObjectTest : public ::testing::Test {
#endif
private:
HlslIntellisenseSupport m_isenseSupport;
public:
BEGIN_TEST_CLASS(ObjectTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(ObjectTestSetup);
TEST_METHOD(DeclareLocalObject)
TEST_METHOD(OptionalTemplateArgs)
TEST_METHOD(MissingTemplateArgs)
TEST_METHOD(TooManyTemplateArgs)
TEST_METHOD(PassAsParameter)
TEST_METHOD(AssignVariables)
TEST_METHOD(AssignReturnResult)
TEST_METHOD(PassToInoutArgs)
TEST_METHOD(TemplateArgConstraints)
TEST_METHOD(FunctionInvoke)
void FormatTypeNameAndPreamble(const ShaderObjectDataItem &sod,
char (&typeName)[64],
const char **preambleDecl) {
*preambleDecl = "";
auto templateData = GetTemplateData(sod);
switch (templateData.TemplateKind) {
case SOTK_NoParams:
sprintf_s(typeName, _countof(typeName), "%s", sod.TypeName);
break;
case SOTK_SingleSVParam:
sprintf_s(typeName, _countof(typeName), "%s<float4>", sod.TypeName);
break;
case SOTK_SingleSVCParam:
*preambleDecl = "struct MY_STRUCT { float4 f4; bool b; int3 i3; };\n";
sprintf_s(typeName, _countof(typeName), "%s<MY_STRUCT>", sod.TypeName);
break;
case SOTK_SVAndSampleCountParams:
case SOTK_SVCAndControlPointCountParams:
default:
sprintf_s(typeName, _countof(typeName), "%s<float4, 1>", sod.TypeName);
break;
}
}
std::string BuildDeclarationFunction(const ShaderObjectDataItem &sod) {
return BuildDeclarationFunction(sod, 0, false);
}
std::string BuildDeclarationFunction(const ShaderObjectDataItem &sod,
int missingTemplateCount,
bool collapseEmptyArgs) {
char result[256];
auto templateData = GetTemplateData(sod);
const char StructDecl[] =
"struct MY_STRUCT { float4 f4; bool b; int3 i3; };\n";
const char StructParam[] = "<MY_STRUCT>\n";
const char VectorParam[] = "<float4>\n";
const char VectorAndCountParam[] = "<float4, 4>\n";
const char EmptyTemplateArgs[] = "<>";
const char MissingTemplateArgs[] = "";
// Default setup for a 'SOTK_NoParams' case.
const char *StructDeclFragment = "";
const char *TemplateDeclFragment = MissingTemplateArgs;
if (templateData.TemplateKind == SOTK_SingleSVParam &&
missingTemplateCount == 0) {
TemplateDeclFragment = VectorParam;
} else if (templateData.TemplateKind == SOTK_SingleSVCParam &&
missingTemplateCount == 0) {
StructDeclFragment = StructDecl;
TemplateDeclFragment = StructParam;
} else if ((templateData.TemplateKind == SOTK_SVAndSampleCountParams ||
templateData.TemplateKind ==
SOTK_SVCAndControlPointCountParams)) {
if (missingTemplateCount == 0) {
TemplateDeclFragment = VectorAndCountParam;
} else if (missingTemplateCount == 1) {
TemplateDeclFragment = VectorParam;
}
}
// Allow 'Object<>' to collapse to 'Object' when collapseEmptyArgs is set.
if (templateData.TemplateKind != SOTK_NoParams &&
TemplateDeclFragment == MissingTemplateArgs) {
TemplateDeclFragment =
collapseEmptyArgs ? MissingTemplateArgs : EmptyTemplateArgs;
}
sprintf_s(result, _countof(result),
"%s"
"float ps(float4 color : COLOR) { %s%s localVar; return 0; }",
StructDeclFragment, sod.TypeName, TemplateDeclFragment);
return std::string(result);
}
std::string
BuildDeclarationFunctionTooManyArgs(const ShaderObjectDataItem &sod) {
char result[256];
auto templateData = GetTemplateData(sod);
switch (templateData.TemplateKind) {
case SOTK_NoParams:
sprintf_s(
result, _countof(result),
"float ps(float4 color : COLOR) { %s localVar<float>; return 0; }",
sod.TypeName);
break;
case SOTK_SingleSVParam:
sprintf_s(result, _countof(result),
"float ps(float4 color : COLOR) { %s<float4, 1> localVar; "
"return 0; }",
sod.TypeName);
break;
case SOTK_SingleSVCParam:
sprintf_s(result, _countof(result),
"struct MY_STRUCT { float4 f4; bool b; int3 i3; };\n"
"float ps(float4 color : COLOR) { %s<MY_STRUCT, 1> localVar; "
"return 0; }",
sod.TypeName);
break;
case SOTK_SVAndSampleCountParams:
case SOTK_SVCAndControlPointCountParams:
default:
sprintf_s(result, _countof(result),
"float ps(float4 color : COLOR) { %s<float4, 4, 4> localVar; "
"return 0; }",
sod.TypeName);
break;
}
return std::string(result);
}
std::string BuildPassAsParameter(const ShaderObjectDataItem &sod) {
char result[256];
char typeName[64];
const char *preambleDecl;
FormatTypeNameAndPreamble(sod, typeName, &preambleDecl);
std::string parmType = typeName;
// Stream-output objects must be declared as inout.
switch (sod.Kind) {
case SOK_StreamOutputLine:
case SOK_StreamOutputPoint:
case SOK_StreamOutputTriangle:
parmType = "inout " + parmType;
break;
default:
// Other kinds need no alteration
break;
}
sprintf_s(result, _countof(result),
"%s"
"void f(%s parameter) { }\n"
"float ps(float4 color : COLOR) { %s localVar; f(localVar); "
"return 0; }",
preambleDecl, parmType.c_str(), typeName);
return std::string(result);
}
std::string BuildAssignment(const ShaderObjectDataItem &sod) {
char result[256];
char typeName[64];
const char *preambleDecl;
FormatTypeNameAndPreamble(sod, typeName, &preambleDecl);
sprintf_s(result, _countof(result),
"%s"
"float ps(float4 color : COLOR) { %s lv1; %s lv2; lv1 = lv2; "
"return 0; }",
preambleDecl, typeName, typeName);
return std::string(result);
}
std::string BuildAssignmentFromResult(const ShaderObjectDataItem &sod) {
char result[256];
char typeName[64];
const char *preambleDecl;
FormatTypeNameAndPreamble(sod, typeName, &preambleDecl);
sprintf_s(result, _countof(result),
"%s"
"%s f() { %s local; return local; }\n"
"float ps(float4 color : COLOR) { %s lv1 = f(); return 0; }",
preambleDecl, typeName, typeName, typeName);
return std::string(result);
}
void CheckCompiles(const std::string &text, bool expected) {
CheckCompiles(text.c_str(), text.size(), expected);
}
void CheckCompiles(const char *text, size_t textLen, bool expected) {
CompilationResult result(
CompilationResult::CreateForProgram(text, textLen));
// Uncomment the line to print out the AST unconditionally.
// printf("%s", result.BuildASTString().c_str());
if (expected != result.ParseSucceeded()) {
EXPECT_EQ(expected, result.ParseSucceeded());
// TODO: log this out
//<< "for program " << text << "\n with AST\n" << result.BuildASTString()
//<< "and errors\n" << result.GetTextForErrors();
}
}
};
bool ObjectTest::ObjectTestSetup() {
m_isenseSupport.Initialize();
return m_isenseSupport.IsEnabled();
}
TEST_F(ObjectTest, DeclareLocalObject) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
CheckCompiles(BuildDeclarationFunction(sod), true);
}
}
TEST_F(ObjectTest, OptionalTemplateArgs) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
const ShaderObjectTemplateDataItem &templateData = GetTemplateData(sod);
int argCount = CountOptionalTemplateArguments(templateData);
if (argCount == 0) {
continue;
}
for (int missingCount = 1; missingCount <= argCount; missingCount++) {
CheckCompiles(BuildDeclarationFunction(sod, missingCount, false), true);
}
}
}
TEST_F(ObjectTest, MissingTemplateArgs) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
const ShaderObjectTemplateDataItem &templateData = GetTemplateData(sod);
int argCount = CountOptionalTemplateArguments(templateData);
if (argCount == 0) {
continue;
}
CheckCompiles(BuildDeclarationFunction(sod, argCount, true), true);
}
}
TEST_F(ObjectTest, TooManyTemplateArgs) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
CheckCompiles(BuildDeclarationFunctionTooManyArgs(sod), false);
}
}
TEST_F(ObjectTest, PassAsParameter) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
CheckCompiles(BuildPassAsParameter(sod), true);
}
}
TEST_F(ObjectTest, AssignVariables) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
CheckCompiles(BuildAssignment(sod), true);
}
}
TEST_F(ObjectTest, AssignReturnResult) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
CheckCompiles(BuildAssignmentFromResult(sod), true);
}
}
TEST_F(ObjectTest, PassToInoutArgs) {
for (const auto &sod : ShaderObjectData) {
// Speed up the test by building one large program with all inout parameter
// modifiers per object.
std::stringstream programText;
unsigned uniqueId = 0;
for (const auto &iop : InOutParameterModifierData) {
switch (sod.Kind) {
case SOK_StreamOutputLine:
case SOK_StreamOutputPoint:
case SOK_StreamOutputTriangle:
// Stream-output objects can only be inout. Skip other cases.
if (std::string(iop.Keyword) != "inout")
continue;
break;
default:
// other cases can be what they want
break;
}
char typeName[64];
const char *preambleDecl;
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
FormatTypeNameAndPreamble(sod, typeName, &preambleDecl);
if (uniqueId == 0) { // do this only once
programText << preambleDecl << std::endl;
}
programText << "float ps_" << uniqueId << "(" << iop.Keyword << " "
<< typeName << " o) { return 1.0f; }" << std::endl;
programText << "void caller_" << uniqueId << "() { " << typeName
<< " lv; ps_" << uniqueId << "(lv); }" << std::endl;
programText << std::endl;
uniqueId++;
}
std::string programTextStr(programText.str());
CheckCompiles(programTextStr.c_str(), programTextStr.size(), true);
}
}
class TemplateSampleDataItem {
public:
TemplateSampleDataItem() {}
TemplateSampleDataItem(const TemplateSampleDataItem &other)
: Preamble(other.Preamble), TypeName(other.TypeName),
IsValid(other.IsValid) {}
TemplateSampleDataItem(const char *preamble, const char *typeName,
bool isValid)
: Preamble(preamble), TypeName(typeName), IsValid(isValid) {}
std::string Preamble;
std::string TypeName;
bool IsValid;
};
std::vector<TemplateSampleDataItem>
CreateSampleDataForTemplateArg(const ShaderObjectDataItem &sod,
int templateIndex) {
std::vector<TemplateSampleDataItem> result;
char typeName[64];
auto templateData = GetTemplateData(sod);
assert(templateData.TemplateKind != SOTK_NoParams &&
"shouldn't call CreateSampleDataForTemplateArg");
switch (templateData.TemplateKind) {
case SOTK_NoParams:
assert(!"shouldn't call CreateSampleDataForTemplateArg");
break;
case SOTK_SingleSVParam:
case SOTK_SingleSVCParam:
sprintf_s(typeName, _countof(typeName), "%s<float4>", sod.TypeName);
result.push_back(TemplateSampleDataItem("", typeName, true));
sprintf_s(typeName, _countof(typeName), "%s<SamplerState>", sod.TypeName);
result.push_back(TemplateSampleDataItem("", typeName, false));
break;
case SOTK_SVAndSampleCountParams:
case SOTK_SVCAndControlPointCountParams:
if (templateIndex == 0) {
sprintf_s(typeName, _countof(typeName), "%s<float4, 4>", sod.TypeName);
result.push_back(TemplateSampleDataItem("", typeName, true));
sprintf_s(typeName, _countof(typeName), "%s<SamplerState, 4>",
sod.TypeName);
result.push_back(TemplateSampleDataItem("", typeName, false));
} else {
sprintf_s(typeName, _countof(typeName), "%s<float4, 1>", sod.TypeName);
result.push_back(TemplateSampleDataItem("", typeName, true));
sprintf_s(typeName, _countof(typeName), "%s<float4, 128>", sod.TypeName);
result.push_back(TemplateSampleDataItem("", typeName, true));
// These are deferred to back-end validation for now.
// bool largeNumberValid = sod.Kind == SOK_InputPatch || sod.Kind ==
// SOK_OutputPatch;
sprintf_s(typeName, _countof(typeName), "%s<float4, 129>", sod.TypeName);
result.push_back(TemplateSampleDataItem("", typeName, false));
}
break;
}
return result;
}
TEST_F(ObjectTest, TemplateArgConstraints) {
for (const auto &sod : ShaderObjectData) {
// When shader models are validated, run through all of them.
// for (const auto &st : sod.ValidShaderTypes)
// const auto st = std::first(sod.ValidShaderTypes);
const ShaderObjectTemplateDataItem &templateData = GetTemplateData(sod);
int argCount = CountOptionalTemplateArguments(templateData);
if (argCount == 0) {
continue;
}
for (int i = 0; i < argCount; i++) {
std::vector<TemplateSampleDataItem> sampleData =
CreateSampleDataForTemplateArg(sod, i);
for (auto sampleDataItem : sampleData) {
char result[256];
sprintf_s(result, _countof(result),
"%s"
"float ps(float4 color : COLOR) { %s lv1; %s lv2; lv1 = lv2; "
"return 0; }",
sampleDataItem.Preamble.c_str(),
sampleDataItem.TypeName.c_str(),
sampleDataItem.TypeName.c_str());
CheckCompiles(result, strlen(result), sampleDataItem.IsValid);
}
}
}
}
// The test that requires this function is pending complete
// support for primitive types
#if 0
static
std::string SelectComponentType(BYTE legalTypes)
{
switch ((LEGAL_INTRINSIC_COMPTYPES)legalTypes)
{
case LICOMPTYPE_VOID: return "void";
case LICOMPTYPE_BOOL: return "bool";
case LICOMPTYPE_INT: return "int";
case LICOMPTYPE_UINT: return "uint";
case LICOMPTYPE_ANY_INT: return "int";
case LICOMPTYPE_ANY_INT32: return "int";
case LICOMPTYPE_UINT_ONLY: return "uint";
case LICOMPTYPE_FLOAT: return "float";
case LICOMPTYPE_ANY_FLOAT: return "float";
case LICOMPTYPE_FLOAT_LIKE: return "float";
case LICOMPTYPE_FLOAT_DOUBLE: return "double";
case LICOMPTYPE_DOUBLE: return "double";
case LICOMPTYPE_DOUBLE_ONLY: return "double";
case LICOMPTYPE_NUMERIC: return "int";
case LICOMPTYPE_NUMERIC32: return "float";
case LICOMPTYPE_NUMERIC32_ONLY: return "double";
case LICOMPTYPE_ANY: return "int";
default: return "";
//LICOMPTYPE_SAMPLER1D,
//LICOMPTYPE_SAMPLER2D,
//LICOMPTYPE_SAMPLER3D,
//LICOMPTYPE_SAMPLERCUBE,
//LICOMPTYPE_SAMPLERCMP,
//LICOMPTYPE_SAMPLER,
//LICOMPTYPE_STRING,
}
}
#endif
TEST_F(ObjectTest, FunctionInvoke) {
// This is pending complete support for primitive types - there are many
// instances of uint usage, which isn't currently supported.
#if 0
// Tests for too many or too few arguments are available as lit-based tests.
// Invoke each method, assigning the result of each method invocation as necessary.
uint64_t iteration = 0;
for (const auto &sod : ShaderObjectData) {
const ShaderObjectIntrinsicDataItem& intrinsicData = GetIntrinsicData(sod);
const ShaderObjectTemplateDataItem& templateData = GetTemplateData(sod);
for (size_t i = 0; i < intrinsicData.IntrinsicCount; i++) {
const HLSL_INTRINSIC* intrinsic = &intrinsicData.Intrinsics[i];
++iteration;
// Build a program that will call this intrinsic.
// Select an element type for the class if needed.
std::string objectType;
std::string elementType;
std::string elementParameters;
switch (templateData.TemplateKind)
{
case ShaderObjectTemplateKind::SOTK_NoParams:
break;
case ShaderObjectTemplateKind::SOTK_SingleSVCParam:
case ShaderObjectTemplateKind::SOTK_SingleSVParam:
elementParameters = "<float3>";
elementType = "float3";
break;
case ShaderObjectTemplateKind::SOTK_SVAndSampleCountParams:
case ShaderObjectTemplateKind::SOTK_SVCAndControlPointCountParams:
elementParameters = "<float3, 4>";
elementType = "float3";
break;
}
objectType = sod.TypeName + elementParameters;
// Select types for all arguments.
// This implementation is brain-dead but (a) different from production,
// so it's a sensible oracle, and (b) very straightforward. We simply
// keep instantiating argument types until we finished.
std::string argumentTypes[g_MaxIntrinsicParamCount];
{
bool madeProgress = false;
int argsRemaining = intrinsic->uNumArgs - 1;
do
{
madeProgress = false;
for (int i = 1; i < intrinsic->uNumArgs; i++)
{
if (!argumentTypes[i - 1].empty())
{
continue;
}
// Determine whether we can make an independent selection.
if (intrinsic->pArgs[i].uTemplateId == INTRIN_TEMPLATE_FROM_TYPE)
{
argumentTypes[i - 1] = elementType;
madeProgress = true;
--argsRemaining;
continue;
}
// An independent scalar.
if (intrinsic->pArgs[i].uTemplateId == i && intrinsic->pArgs[i].uComponentTypeId == i &&
intrinsic->pArgs[i].uLegalComponentTypes != LITEMPLATE_ANY &&
intrinsic->pArgs[i].uLegalTemplates == LITEMPLATE_SCALAR)
{
argumentTypes[i - 1] = SelectComponentType(intrinsic->pArgs[i].uLegalComponentTypes);
madeProgress = true;
--argsRemaining;
continue;
}
// An independent vector.
if (intrinsic->pArgs[i].uTemplateId == i && intrinsic->pArgs[i].uComponentTypeId == i &&
intrinsic->pArgs[i].uLegalComponentTypes != LITEMPLATE_ANY &&
intrinsic->pArgs[i].uLegalTemplates == LITEMPLATE_VECTOR)
{
argumentTypes[i - 1] = SelectComponentType(intrinsic->pArgs[i].uLegalComponentTypes) + "2";
madeProgress = true;
--argsRemaining;
continue;
}
// TODO: complete the assignment cases with primitive types
// Determine whether we have all dependencies assigned for a selection.
}
} while (madeProgress && argsRemaining > 0);
EXPECT_EQ(0, argsRemaining) <<
"otherwise we're unable to complete the signature for " << intrinsic->pArgs[0].pName <<
" in iteration " << iteration;
}
// Determine what the result type is.
bool resultIsVoid = intrinsic->pArgs[0].uLegalTemplates == LITEMPLATE_VOID;
std::string resultType;
if (!resultIsVoid) {
}
// Assemble the program as a series of declarations, a method call
// and possibly an assignment if there's a return value.
std::stringstream program;
std::string assignmentLeftHand(resultIsVoid ? "" : (resultType + " result = "));
program << "// iteration " << iteration << "\n"
"void f() {\n"
" " << objectType << " testObject;\n";
for (int i = 1; i < intrinsic->uNumArgs; i++) {
program << argumentTypes[i - 1] << ' ' << intrinsic->pArgs[i].pName << ";\n";
}
program << assignmentLeftHand << "testObject." << intrinsic->pArgs[0].pName << "(";
for (int i = 1; i < intrinsic->uNumArgs; i++) {
program << intrinsic->pArgs[i].pName;
if (i != intrinsic->uNumArgs - 1) {
program << ", ";
}
}
program << ");\n}";
// Verify it runs.
CheckCompiles(program.str(), true);
}
}
#endif
}
// TODO: force type promotion to occur for arguments.
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/AllocatorTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// AllocatorTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/HLSL/DxilSpanAllocator.h"
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <map>
#include <random>
#include <set>
#include <vector>
using namespace hlsl;
/* Test Case Breakdown:
Dimensions:
1. Allocator (min, max)
Success cases
- 0, 10
- 0, 0
- 0, UINT_MAX
- UINT_MAX, UINT_MAX
Failure cases
- 10, 9
- 1, 0
- UINT_MAX, 0
- UINT_MAX, UINT_MAX - 1
2. Span scenarios
Generate some legal spans first:
- randomly choose whether to reserve space at end for unbounded, reduce
range by this value
- few:
set num = 5;
add spans in order with random offsets from previous begin/end until
full or num reached: offset = rand(1, space left)
- lots:
set num = min(range, 1000)
add spans in order with random offsets from previous begin/end until
full or num reached: offset = rand(1, min(space left, max(1, range / num))) Copy
and shuffle spans Add spans to allocator, expect all success
- randomly choose whether to attempt to add unbounded
Should pass if space avail, fail if space filled
Select starting and ending spans (one and two):
- gather unique span cases:
one = two = first
one = two = second
one = two = random
one = two = last - 1
one = two = last
- add these if one < two:
one = first, two = second
one = first, two = last-1
one = first, two = last
one = first, two = random
one = random, two = random
one = random, two = last
one = second, two = last-1
one = second, two = last
Add overlapping span, with start and end scenarios as follows:
should have (one <= conflict && conflict <= two)
for start:
if prev = span before one:
- prev.end < start, start < one.start
else:
- Min <= start, start < one.start
- start == one.start
- start > one.start, start < one.end
- start == one.end
for end (when start <= end, and unique from other cases):
- end == max(start, two.start)
- end > two.start, end < two.end
- end == two.end
if next = span after two:
- end > two.end, end < next.start
else:
- end > two.end, end <= Max
*/
// Modifies input pos and returns false on overflow, or exceeds max
bool Align(unsigned &pos, unsigned end, unsigned align) {
if (end < pos)
return false;
unsigned original = pos;
unsigned rem = (1 < align) ? pos % align : 0;
pos = rem ? pos + (align - rem) : pos;
return original <= pos && pos <= end;
}
struct Element {
Element() = default;
Element(const Element &) = default;
Element &operator=(const Element &) = default;
Element(unsigned id, unsigned start, unsigned end)
: id(id), start(start), end(end) {}
bool operator<(const Element &other) { return id < other.id; }
unsigned id; // index in original ordered vector
unsigned start, end;
};
typedef std::vector<Element> ElementVector;
typedef SpanAllocator<unsigned, Element> Allocator;
struct IntersectionTestCase {
IntersectionTestCase(unsigned one, unsigned two, unsigned start, unsigned end)
: idOne(one), idTwo(two), element(UINT_MAX, start, end) {
DXASSERT_NOMSG(one <= two && start <= end);
}
unsigned idOne, idTwo;
Element element;
bool operator<(const IntersectionTestCase &other) const {
if (element.start < other.element.start)
return true;
else if (other.element.start < element.start)
return false;
if (element.end < other.element.end)
return true;
else if (other.element.end < element.end)
return false;
return false;
}
};
typedef std::set<IntersectionTestCase> IntersectionSet;
struct Gap {
Gap(unsigned start, unsigned end, const Element *eBefore,
const Element *eAfter)
: start(start), end(end), sizeLess1(end - start), eBefore(eBefore),
eAfter(eAfter) {}
unsigned start, end;
unsigned sizeLess1;
const Element *eBefore = nullptr;
const Element *eAfter = nullptr;
};
typedef std::vector<Gap> GapVector;
const Gap *GetGapBeforeFirst(const GapVector &G) {
if (!G.empty() && !G.front().eBefore)
return &G.front();
return nullptr;
}
const Gap *GetGapBetweenFirstAndSecond(const GapVector &G) {
for (auto &gap : G) {
if (gap.eBefore) {
if (gap.eAfter)
return ⪆
break;
}
}
return nullptr;
}
const Gap *GetGapBetweenLastAndSecondLast(const GapVector &G) {
if (!G.empty()) {
auto it = G.end();
for (--it; it != G.begin(); --it) {
const Gap &gap = *it;
if (gap.eAfter) {
if (gap.eBefore)
return ⪆
break;
}
}
}
return nullptr;
}
const Gap *GetGapAfterLast(const GapVector &G) {
if (!G.empty() && !G.back().eAfter)
return &G.back();
return nullptr;
}
void GatherGaps(GapVector &gaps, const ElementVector &spans, unsigned Min,
unsigned Max, unsigned alignment = 1) {
unsigned start, end;
const Element *eBefore = nullptr;
const Element *eAfter = nullptr;
// Gather gaps
eBefore = nullptr;
for (auto &&span : spans) {
eAfter = &span;
if (!eBefore) {
start = Min;
if (start < span.start) {
end = span.start -
1; // can underflow, this is the first span, so guarded by if
if (Align(start, end, alignment))
gaps.emplace_back(start, end, eBefore, eAfter);
}
} else {
start = eBefore->end + 1;
end = span.start - 1; // can't underflow, this is the second span
if (Align(start, end, alignment))
gaps.emplace_back(start, end, eBefore, eAfter);
}
eBefore = &span;
}
eAfter = nullptr;
if (!eBefore) {
// No spans
start = Min;
end = Max;
if (Align(start, end, alignment))
gaps.emplace_back(start, end, eBefore, eAfter);
} else if (eBefore->end < Max) {
// gap at end
start = eBefore->end + 1;
end = Max;
if (start <= end) {
if (Align(start, end, alignment))
gaps.emplace_back(start, end, eBefore, eAfter);
}
}
}
void GetGapExtremes(const GapVector &gaps, const Gap *&largest,
const Gap *&smallest) {
largest = nullptr;
smallest = nullptr;
for (auto &gap : gaps) {
if (!largest || largest->sizeLess1 < gap.sizeLess1) {
largest = ⪆
}
if (!smallest || smallest->sizeLess1 > gap.sizeLess1) {
smallest = ⪆
}
}
}
const Gap *FindGap(const GapVector &gaps, unsigned sizeLess1) {
if (sizeLess1 == UINT_MAX) {
return GetGapAfterLast(gaps);
} else {
for (auto &gap : gaps) {
if (gap.sizeLess1 >= sizeLess1)
return ⪆
}
}
return nullptr;
}
const Gap *NextGap(const GapVector &gaps, unsigned pos) {
for (auto &gap : gaps) {
if (gap.end < pos)
continue;
return ⪆
}
return nullptr;
}
// if rand() only uses 15 bits:
// unsigned rand32() { return (rand() << 30) ^ (rand() << 15) ^ rand(); }
struct Scenario {
Scenario(unsigned Min, unsigned Max, unsigned MaxSpans, bool SpaceAtEnd,
unsigned Seed)
: Min(Min), Max(Max), randGen(Seed) {
if (!MaxSpans || (SpaceAtEnd && Min == Max))
return;
spans.reserve(MaxSpans);
{
unsigned last = SpaceAtEnd ? Max - 1 : Max;
unsigned next = Min;
unsigned max_size = std::max(
(unsigned)(((int64_t)(last - next) + 1) / MaxSpans), (unsigned)1);
unsigned offset;
while (spans.size() < MaxSpans && next <= last) {
if ((randGen() & 3) == 3) // 1 in 4 chance for adjacent span
offset = 0;
else
offset = randGen() % max_size;
unsigned start = next + offset;
if (start > last || start < next) // overflow
start = last;
if ((randGen() & 3) == 3) // 1 in 4 chance for size 1 (start == end)
offset = 0;
else
offset = randGen() % max_size;
unsigned end = start + offset;
if (end >= last || end < start) // overflow
end = next = last;
else
next = end + 1;
spans.emplace_back(spans.size(), start, end);
if (end == last)
break;
}
}
if (spans.empty())
return;
shuffledSpans = spans;
std::shuffle(shuffledSpans.begin(), shuffledSpans.end(), randGen);
// Create conflict spans
typedef std::pair<unsigned, unsigned> Test;
// These are pairs of element indexes to construct intersecting spans from
std::set<Test> pairs;
unsigned maxIdx = spans.size() - 1;
// - gather unique span cases:
// one = two = first
pairs.insert(Test(0, 0));
// one = two = second
if (maxIdx > 0) {
pairs.insert(Test(1, 1));
}
// one = two = random
if (maxIdx > 2) {
unsigned randIdx = 1 + (randGen() % (maxIdx - 2));
unsigned one = std::min(randIdx, maxIdx);
pairs.insert(Test(one, one));
}
// one = two = last - 1
if (maxIdx > 1) {
pairs.insert(Test(maxIdx - 1, maxIdx - 1));
}
// one = two = last
pairs.insert(Test(maxIdx, maxIdx));
// - add these if one < two:
// one = first, two = second
if (maxIdx > 0) {
pairs.insert(Test(0, 1));
}
// one = first, two = last-1
if (maxIdx > 1) {
pairs.insert(Test(0, maxIdx - 1));
}
// one = first, two = last
if (maxIdx > 1) {
pairs.insert(Test(0, maxIdx));
}
// one = first, two = random
if (maxIdx > 3) {
unsigned randIdx = 1 + (randGen() % (maxIdx - 2));
unsigned two = std::min(randIdx, maxIdx);
pairs.insert(Test(0, two));
}
// one = random, two = random
if (maxIdx > 4) {
unsigned randIdx = 1 + (randGen() % (maxIdx - 3));
unsigned one = std::min(randIdx, maxIdx);
randIdx = one + 1 + (randGen() % (maxIdx - (one + 1)));
unsigned two = std::min(randIdx, maxIdx);
pairs.insert(Test(one, two));
}
// one = random, two = last
if (maxIdx > 3) {
unsigned randIdx = 1 + (randGen() % (maxIdx - 2));
unsigned one = std::min(randIdx, maxIdx);
pairs.insert(Test(one, maxIdx));
}
// one = second, two = last-1
if (maxIdx > 1) {
pairs.insert(Test(1, maxIdx - 1));
}
// one = second, two = last
if (maxIdx > 1) {
pairs.insert(Test(1, maxIdx));
}
// These are start/end pairs that represent the intersecting spans that we
// will construct
for (auto &&test : pairs) {
// prev -> one -> ... -> two -> next
// Where one and two are indexes into spans where one <= two
// Where prev and next are only set if they exist
const Element *prev = test.first ? &spans[test.first - 1] : nullptr;
const Element *one = &spans[test.first];
const Element *two = &spans[test.second];
const Element *next =
(test.second < spans.size() - 1) ? &spans[test.second + 1] : nullptr;
unsigned start = 0;
unsigned space = 0;
// Function to add intersection tests, given start
auto AddEnds = [&]() {
// for end (when start <= end, and unique from other cases):
// - end == max(start, two.start)
unsigned end = std::max(start, two->start);
intersectionTests.emplace(test.first, test.second, start, end);
// - end > two.start, end < two.end
if (end < two->end) {
++end;
space = two->end - end;
if (space > 1)
end += randGen() % space;
if (start <= end)
intersectionTests.emplace(test.first, test.second, start, end);
}
// - end == two.end
end = two->end;
if (start <= end)
intersectionTests.emplace(test.first, test.second, start, end);
// if next = span after two:
// - end > two.end, end < next.start
// else:
// - end > two.end, end <= Max
space = (next ? next->start - 1 : Max) - two->end;
if (space) {
end = two->end + 1 + randGen() % space;
if (start <= end)
intersectionTests.emplace(test.first, test.second, start, end);
}
};
// Add overlapping span, with start and end scenarios as follows:
// should have (one <= conflict && conflict <= two)
// for start:
// if prev = span before one:
// - prev.end < start, start < one.start
// else:
// - Min <= start, start < one.start
if (prev)
start = prev->end + 1;
else
start = Min;
if (start < one->start) {
space = one->start - start;
if (space > 1)
start += randGen() % space;
AddEnds();
}
// - start == one.start
start = one->start;
AddEnds();
// - start > one.start, start < one.end
if (one->start < Max && one->start + 1 < one->end) {
start = one->start + 1;
AddEnds();
}
// - start == one.end
start = one->end;
AddEnds();
}
}
void CreateGaps() {
GatherGaps(gaps[1], spans, Min, Max, 1);
GetGapExtremes(gaps[1], gapLargest[1], gapSmallest[1]);
GatherGaps(gaps[4], spans, Min, Max, 4);
GetGapExtremes(gaps[4], gapLargest[4], gapSmallest[4]);
}
bool InsertSpans(Allocator &alloc) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (auto &it : shuffledSpans) {
const Element *e = ⁢
const Element *conflict = alloc.Insert(e, e->start, e->end);
VERIFY_ARE_EQUAL(conflict, nullptr);
}
return true;
}
bool VerifySpans(Allocator &alloc) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
unsigned index = 0;
unsigned last = Min;
bool first = true;
bool full = !alloc.GetSpans().empty();
unsigned firstFree = Min;
for (auto &span : alloc.GetSpans()) {
VERIFY_IS_TRUE(Min <= span.start && span.start <= span.end &&
span.end <= Max);
if (!first)
++last;
VERIFY_IS_TRUE(last <= span.start);
if (full && last < span.start) {
full = false;
firstFree = last;
}
// id == index in spans for original inserted elements only,
// so skip test elements with UINT_MAX id
if (span.element->id != UINT_MAX) {
VERIFY_IS_TRUE(index == span.element->id);
++index;
}
VERIFY_IS_TRUE(span.start == span.element->start);
VERIFY_IS_TRUE(span.end == span.element->end);
last = span.end;
first = false;
}
if (full && last < Max) {
full = false;
firstFree = last + 1;
}
if (full) {
VERIFY_IS_TRUE(alloc.IsFull());
} else {
VERIFY_IS_FALSE(alloc.IsFull());
VERIFY_IS_TRUE(alloc.GetFirstFree() == firstFree);
}
return true;
}
unsigned Min, Max;
ElementVector spans;
ElementVector shuffledSpans;
IntersectionSet intersectionTests;
// Gaps by alignment
std::map<unsigned, GapVector> gaps;
// Smallest gap by alignment
std::map<unsigned, const Gap *> gapSmallest;
// Largest gap by alignment
std::map<unsigned, const Gap *> gapLargest;
std::mt19937 randGen;
};
// The test fixture.
#ifdef _WIN32
class AllocatorTest {
#else
class AllocatorTest : public ::testing::Test {
protected:
#endif
std::vector<Scenario> m_Scenarios;
public:
BEGIN_TEST_CLASS(AllocatorTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(AllocatorTestSetup);
TEST_METHOD(Intersections)
TEST_METHOD(GapFilling)
TEST_METHOD(Allocate)
void InitScenarios() {
struct P {
unsigned Min, Max, MaxSpans;
bool SpaceAtEnd;
unsigned SeedOffset;
};
static const P params[] = {
// Min, Max, MaxSpans, SpaceAtEnd, Seed
// - 0, 0
{0, 0, 1, false, 0},
{0, 0, 1, true, 0},
// - UINT_MAX, UINT_MAX
{UINT_MAX, UINT_MAX, 1, false, 0},
{UINT_MAX, UINT_MAX, 1, true, 0},
// - small, small
{0, 20, 5, false, 0},
{0, 20, 5, true, 0},
{21, 96, 5, false, 0},
{21, 96, 5, true, 0},
// - 0, UINT_MAX
{0, UINT_MAX, 0, false, 0},
{0, UINT_MAX, 10, false, 0},
{0, UINT_MAX, 10, true, 0},
{0, UINT_MAX, 100, false, 0},
{0, UINT_MAX, 100, true, 0},
};
static const unsigned count = _countof(params);
m_Scenarios.reserve(count);
for (unsigned i = 0; i < count; ++i) {
const P &p = params[i];
m_Scenarios.emplace_back(p.Min, p.Max, p.MaxSpans, p.SpaceAtEnd,
i + p.SeedOffset);
m_Scenarios.back().CreateGaps();
}
}
};
bool AllocatorTest::AllocatorTestSetup() {
InitScenarios();
return true;
}
TEST_F(AllocatorTest, Intersections) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (auto &&scenario : m_Scenarios) {
Allocator alloc(scenario.Min, scenario.Max);
VERIFY_IS_TRUE(scenario.InsertSpans(alloc));
for (auto &&test : scenario.intersectionTests) {
const Element &e = test.element;
const Element *conflict = alloc.Insert(&e, e.start, e.end);
VERIFY_IS_TRUE(conflict != nullptr);
if (conflict) {
VERIFY_IS_TRUE(conflict->id >= test.idOne);
VERIFY_IS_TRUE(conflict->id <= test.idTwo);
}
}
VERIFY_IS_TRUE(scenario.VerifySpans(alloc));
}
}
TEST_F(AllocatorTest, GapFilling) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (auto &&scenario : m_Scenarios) {
// Fill all gaps with Insert, no alignment, verify first free advances and
// container is full at the end
{
// WEX::TestExecution::SetVerifyOutput
// verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
Allocator alloc(scenario.Min, scenario.Max);
VERIFY_IS_TRUE(scenario.InsertSpans(alloc));
GapVector &gaps = scenario.gaps[1];
for (auto &gap : gaps) {
VERIFY_IS_FALSE(alloc.IsFull());
VERIFY_ARE_EQUAL(alloc.GetFirstFree(), gap.start);
Element e(UINT_MAX, gap.start, gap.end);
VERIFY_IS_NULL(alloc.Insert(&e, gap.start, gap.end));
}
VERIFY_IS_TRUE(alloc.IsFull());
}
bool InsertSucceeded = true;
VERIFY_IS_TRUE(InsertSucceeded);
// Fill all gaps with Allocate, no alignment, verify first free advances and
// container is full at the end
{
// WEX::TestExecution::SetVerifyOutput
// verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
Allocator alloc(scenario.Min, scenario.Max);
VERIFY_IS_TRUE(scenario.InsertSpans(alloc));
GapVector &gaps = scenario.gaps[1];
for (auto &gap : gaps) {
unsigned start = gap.start;
unsigned end = gap.end;
VERIFY_IS_FALSE(alloc.IsFull());
VERIFY_ARE_EQUAL(alloc.GetFirstFree(), start);
Element e(UINT_MAX, start, end);
unsigned pos = 0xFEFEFEFE;
if (gap.sizeLess1 < UINT_MAX) {
VERIFY_IS_TRUE(alloc.Allocate(&e, gap.sizeLess1 + 1, pos));
} else {
const Element *unbounded = &e;
VERIFY_IS_TRUE(alloc.AllocateUnbounded(unbounded, pos));
VERIFY_ARE_EQUAL(alloc.GetUnbounded(), unbounded);
}
VERIFY_ARE_EQUAL(start, pos);
}
VERIFY_IS_TRUE(alloc.IsFull());
}
bool AllocSucceeded = true;
VERIFY_IS_TRUE(AllocSucceeded);
}
}
TEST_F(AllocatorTest, Allocate) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (auto &scenario : m_Scenarios) {
// Test for alignment 1 (no alignment), then alignment 4
unsigned alignment = 1;
const GapVector *pGaps = &scenario.gaps[alignment];
const Gap *largestGap = scenario.gapLargest[alignment];
const Gap *smallestGap = scenario.gapSmallest[alignment];
// Test a particular allocation size with some alignment
auto TestFn = [&](unsigned sizeLess1) {
DXASSERT_NOMSG(pGaps);
const Gap *pEndGap = GetGapAfterLast(*pGaps);
Allocator alloc(scenario.Min, scenario.Max);
VERIFY_IS_TRUE(scenario.InsertSpans(alloc));
// This needs to be allocated outside the control flow because we need the
// stack allocation to remain valid until the spans are verified.
Element e;
if (!largestGap || // no gaps
(sizeLess1 < UINT_MAX &&
sizeLess1 >
largestGap->sizeLess1) || // not unbounded and size too large
(sizeLess1 == UINT_MAX && !pEndGap)) { // unbounded and no end gap
// no large enough gap, should fail to allocate
e = Element(UINT_MAX, 0, 0);
unsigned pos = 0xFEFEFEFE;
if (sizeLess1 == UINT_MAX) {
VERIFY_IS_FALSE(alloc.AllocateUnbounded(&e, pos, alignment));
} else {
VERIFY_IS_FALSE(alloc.Allocate(&e, sizeLess1 + 1, pos, alignment));
}
} else {
// large enough gap to allocate, verify:
// - allocation occurs where expected
// - firstFree is advanced if necessary
// - container is marked full if necessary (VerifySpans should do this)
unsigned firstFree = alloc.GetFirstFree();
const Gap *expectedGap = FindGap(*pGaps, sizeLess1);
DXASSERT_NOMSG(expectedGap);
unsigned start = expectedGap->start;
unsigned end = expectedGap->start + sizeLess1;
e = Element(UINT_MAX, start, end);
unsigned pos = 0xFEFEFEFE;
if (sizeLess1 == UINT_MAX) {
e.end = expectedGap->end;
VERIFY_IS_TRUE(alloc.AllocateUnbounded(&e, pos, alignment));
} else {
VERIFY_IS_TRUE(alloc.Allocate(&e, sizeLess1 + 1, pos, alignment));
}
VERIFY_IS_TRUE(pos == start);
if (start <= firstFree && firstFree <= end) {
if (end < expectedGap->end) {
VERIFY_IS_FALSE(alloc.IsFull());
VERIFY_IS_TRUE(alloc.GetFirstFree() == end + 1);
}
}
}
VERIFY_IS_TRUE(scenario.VerifySpans(alloc));
};
auto TestSizesFn = [&] {
DXASSERT_NOMSG(pGaps);
const Gap *pStartGap = GetGapBeforeFirst(*pGaps);
const Gap *pGap1 = GetGapBetweenFirstAndSecond(*pGaps);
// pass/fail based on fit
// allocate different sizes (in sizeLess1, UINT_MAX means unbounded):
std::set<unsigned> sizes;
// - size 1
sizes.insert(0);
// - size 2
sizes.insert(1);
// - Unbounded
sizes.insert(UINT_MAX);
// - size == smallest gap
if (smallestGap)
sizes.insert(smallestGap->sizeLess1);
// - size == largest gap
if (largestGap && largestGap->sizeLess1 < UINT_MAX)
sizes.insert(largestGap->sizeLess1);
// - size == largest gap + 1
if (largestGap && largestGap->sizeLess1 < UINT_MAX - 1)
sizes.insert(largestGap->sizeLess1 + 1);
// - size > gap before first span if largest gap is large enough
if (pStartGap && pStartGap->sizeLess1 < largestGap->sizeLess1)
sizes.insert(pStartGap->sizeLess1 + 1);
// - size > gap before first span and size > first gap between spans if
// largest gap is large enough
if (pStartGap && pStartGap->sizeLess1 < largestGap->sizeLess1 && pGap1 &&
pGap1->sizeLess1 < largestGap->sizeLess1)
sizes.insert(std::max(pStartGap->sizeLess1, pGap1->sizeLess1) + 1);
for (auto &size : sizes) {
TestFn(size);
}
};
// Test without alignment
TestSizesFn();
// again with alignment
alignment = 4;
pGaps = &scenario.gaps[alignment];
largestGap = scenario.gapLargest[alignment];
smallestGap = scenario.gapSmallest[alignment];
TestSizesFn();
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/HLSLTestOptions.h
|
//===- unittests/HLSL/HLSLTestOptions.h ----- Command Line Options ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the command line options that can be passed to HLSL
// gtests. This file should be included in any test file that intends to use any
// options.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_UNITTESTS_HLSL_TEST_OPTIONS_H
#define LLVM_CLANG_UNITTESTS_HLSL_TEST_OPTIONS_H
#include <string>
namespace clang {
namespace hlsl {
/// \brief Includes any command line options that may be passed to gtest for
/// running the SPIR-V tests. New options should be added in this namespace.
namespace testOptions {
/// \brief Command line option that specifies the path to the directory that
/// contains files that have the HLSL source code (used for the CodeGen test
/// flow).
#define ARG_DECLARE(argname) extern std::string argname;
#define ARG_LIST(ARGOP) \
ARGOP(HlslDataDir) \
ARGOP(TestName) \
ARGOP(DXBC) \
ARGOP(SaveImages) \
ARGOP(ExperimentalShaders) \
ARGOP(DebugLayer) \
ARGOP(SuitePath) \
ARGOP(InputPath)
ARG_LIST(ARG_DECLARE)
} // namespace testOptions
} // namespace hlsl
} // namespace clang
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/PixDiaTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// PixDiaTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for the PIX-specific components related to dia //
// //
///////////////////////////////////////////////////////////////////////////////
// This whole file is win32-only
#ifdef _WIN32
#include <array>
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HLSLTestData.h"
#include "dxc/Test/HlslTestUtils.h"
#include "llvm/Support/raw_os_ostream.h"
#include <../lib/DxilDia/DxilDiaSession.h>
#include "PixTestUtils.h"
using namespace std;
using namespace hlsl;
using namespace hlsl_test;
using namespace pix_test;
// Aligned to SymTagEnum.
const char *SymTagEnumText[] = {
"Null", // SymTagNull
"Exe", // SymTagExe
"Compiland", // SymTagCompiland
"CompilandDetails", // SymTagCompilandDetails
"CompilandEnv", // SymTagCompilandEnv
"Function", // SymTagFunction
"Block", // SymTagBlock
"Data", // SymTagData
"Annotation", // SymTagAnnotation
"Label", // SymTagLabel
"PublicSymbol", // SymTagPublicSymbol
"UDT", // SymTagUDT
"Enum", // SymTagEnum
"FunctionType", // SymTagFunctionType
"PointerType", // SymTagPointerType
"ArrayType", // SymTagArrayType
"BaseType", // SymTagBaseType
"Typedef", // SymTagTypedef
"BaseClass", // SymTagBaseClass
"Friend", // SymTagFriend
"FunctionArgType", // SymTagFunctionArgType
"FuncDebugStart", // SymTagFuncDebugStart
"FuncDebugEnd", // SymTagFuncDebugEnd
"UsingNamespace", // SymTagUsingNamespace
"VTableShape", // SymTagVTableShape
"VTable", // SymTagVTable
"Custom", // SymTagCustom
"Thunk", // SymTagThunk
"CustomType", // SymTagCustomType
"ManagedType", // SymTagManagedType
"Dimension", // SymTagDimension
"CallSite", // SymTagCallSite
"InlineSite", // SymTagInlineSite
"BaseInterface", // SymTagBaseInterface
"VectorType", // SymTagVectorType
"MatrixType", // SymTagMatrixType
"HLSLType", // SymTagHLSLType
"Caller", // SymTagCaller
"Callee", // SymTagCallee
"Export", // SymTagExport
"HeapAllocationSite", // SymTagHeapAllocationSite
"CoffGroup", // SymTagCoffGroup
};
// Aligned to DataKind.
const char *DataKindText[] = {
"Unknown", "Local", "StaticLocal", "Param", "ObjectPtr",
"FileStatic", "Global", "Member", "StaticMember", "Constant",
};
static void CompileAndGetDebugPart(dxc::DxcDllSupport &dllSupport,
const char *source, const wchar_t *profile,
IDxcBlob **ppDebugPart) {
CComPtr<IDxcBlob> pContainer;
CComPtr<IDxcLibrary> pLib;
CComPtr<IDxcContainerReflection> pReflection;
UINT32 index;
std::vector<LPCWSTR> args;
args.push_back(L"/Zi");
args.push_back(L"/Qembed_debug");
VerifyCompileOK(dllSupport, source, profile, args, &pContainer);
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
VERIFY_SUCCEEDED(
dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(pReflection->Load(pContainer));
VERIFY_SUCCEEDED(
pReflection->FindFirstPartKind(hlsl::DFCC_ShaderDebugInfoDXIL, &index));
VERIFY_SUCCEEDED(pReflection->GetPartContent(index, ppDebugPart));
}
static LPCWSTR defaultFilename = L"source.hlsl";
static HRESULT UnAliasType(IDxcPixType *MaybeAlias,
IDxcPixType **OriginalType) {
*OriginalType = nullptr;
CComPtr<IDxcPixType> Tmp(MaybeAlias);
do {
HRESULT hr;
CComPtr<IDxcPixType> Alias;
hr = Tmp->UnAlias(&Alias);
if (FAILED(hr)) {
return hr;
}
if (hr == S_FALSE) {
break;
}
Tmp = Alias;
} while (true);
*OriginalType = Tmp.Detach();
return S_OK;
}
class PixDiaTest {
public:
BEGIN_TEST_CLASS(PixDiaTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
TEST_METHOD(CompileWhenDebugThenDIPresent)
TEST_METHOD(CompileDebugPDB)
TEST_METHOD(DiaLoadBadBitcodeThenFail)
TEST_METHOD(DiaLoadDebugThenOK)
TEST_METHOD(DiaTableIndexThenOK)
TEST_METHOD(DiaLoadDebugSubrangeNegativeThenOK)
TEST_METHOD(DiaLoadRelocatedBitcode)
TEST_METHOD(DiaLoadBitcodePlusExtraData)
TEST_METHOD(DiaCompileArgs)
TEST_METHOD(PixTypeManager_InheritancePointerStruct)
TEST_METHOD(PixTypeManager_InheritancePointerTypedef)
TEST_METHOD(PixTypeManager_MatricesInBase)
TEST_METHOD(PixTypeManager_SamplersAndResources)
TEST_METHOD(PixTypeManager_XBoxDiaAssert)
TEST_METHOD(PixDebugCompileInfo)
TEST_METHOD(SymbolManager_Embedded2DArray)
TEST_METHOD(
DxcPixDxilDebugInfo_GlobalBackedGlobalStaticEmbeddedArrays_NoDbgValue)
TEST_METHOD(
DxcPixDxilDebugInfo_GlobalBackedGlobalStaticEmbeddedArrays_WithDbgValue)
TEST_METHOD(
DxcPixDxilDebugInfo_GlobalBackedGlobalStaticEmbeddedArrays_ArrayInValues)
TEST_METHOD(DxcPixDxilDebugInfo_InstructionOffsets)
TEST_METHOD(DxcPixDxilDebugInfo_InstructionOffsetsInClassMethods)
TEST_METHOD(DxcPixDxilDebugInfo_DuplicateGlobals)
TEST_METHOD(DxcPixDxilDebugInfo_StructInheritance)
TEST_METHOD(DxcPixDxilDebugInfo_StructContainedResource)
TEST_METHOD(DxcPixDxilDebugInfo_StructStaticInit)
TEST_METHOD(DxcPixDxilDebugInfo_StructMemberFnFirst)
TEST_METHOD(DxcPixDxilDebugInfo_UnnamedConstStruct)
TEST_METHOD(DxcPixDxilDebugInfo_UnnamedStruct)
TEST_METHOD(DxcPixDxilDebugInfo_UnnamedArray)
TEST_METHOD(DxcPixDxilDebugInfo_UnnamedField)
TEST_METHOD(DxcPixDxilDebugInfo_SubProgramsInNamespaces)
TEST_METHOD(DxcPixDxilDebugInfo_SubPrograms)
TEST_METHOD(DxcPixDxilDebugInfo_Alignment_ConstInt)
TEST_METHOD(DxcPixDxilDebugInfo_QIOldFieldInterface)
TEST_METHOD(DxcPixDxilDebugInfo_BitFields_Simple)
TEST_METHOD(DxcPixDxilDebugInfo_BitFields_Derived)
TEST_METHOD(DxcPixDxilDebugInfo_BitFields_Bool)
TEST_METHOD(DxcPixDxilDebugInfo_BitFields_Overlap)
TEST_METHOD(DxcPixDxilDebugInfo_Min16SizesAndOffsets_Enabled)
TEST_METHOD(DxcPixDxilDebugInfo_Min16SizesAndOffsets_Disabled)
TEST_METHOD(DxcPixDxilDebugInfo_Min16VectorOffsets_Enabled)
TEST_METHOD(DxcPixDxilDebugInfo_Min16VectorOffsets_Disabled)
TEST_METHOD(
DxcPixDxilDebugInfo_VariableScopes_InlinedFunctions_TwiceInlinedFunctions)
TEST_METHOD(
DxcPixDxilDebugInfo_VariableScopes_InlinedFunctions_CalledTwiceInSameCaller)
TEST_METHOD(DxcPixDxilDebugInfo_VariableScopes_ForScopes)
TEST_METHOD(DxcPixDxilDebugInfo_VariableScopes_ScopeBraces)
TEST_METHOD(DxcPixDxilDebugInfo_VariableScopes_Function)
TEST_METHOD(DxcPixDxilDebugInfo_VariableScopes_Member)
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
void RunSubProgramsCase(const char *hlsl);
void TestUnnamedTypeCase(const char *hlsl, const wchar_t *expectedTypeName);
template <typename T, typename TDefault, typename TIface>
void WriteIfValue(TIface *pSymbol, std::wstringstream &o,
TDefault defaultValue, LPCWSTR valueLabel,
HRESULT (__stdcall TIface::*pFn)(T *)) {
T value;
HRESULT hr = (pSymbol->*(pFn))(&value);
if (SUCCEEDED(hr) && value != (T)defaultValue) {
o << L", " << valueLabel << L": " << value;
}
}
template <typename TIface>
void WriteIfValue(TIface *pSymbol, std::wstringstream &o, LPCWSTR valueLabel,
HRESULT (__stdcall TIface::*pFn)(BSTR *)) {
CComBSTR value;
HRESULT hr = (pSymbol->*(pFn))(&value);
if (SUCCEEDED(hr) && value.Length()) {
o << L", " << valueLabel << L": " << (LPCWSTR)value;
}
}
template <typename TIface>
void WriteIfValue(TIface *pSymbol, std::wstringstream &o, LPCWSTR valueLabel,
HRESULT (__stdcall TIface::*pFn)(VARIANT *)) {
CComVariant value;
HRESULT hr = (pSymbol->*(pFn))(&value);
if (SUCCEEDED(hr) && value.vt != VT_NULL && value.vt != VT_EMPTY) {
if (SUCCEEDED(value.ChangeType(VT_BSTR))) {
o << L", " << valueLabel << L": " << (LPCWSTR)value.bstrVal;
}
}
}
template <typename TIface>
void WriteIfValue(TIface *pSymbol, std::wstringstream &o, LPCWSTR valueLabel,
HRESULT (__stdcall TIface::*pFn)(IDiaSymbol **)) {
CComPtr<IDiaSymbol> value;
HRESULT hr = (pSymbol->*(pFn))(&value);
if (SUCCEEDED(hr) && value.p != nullptr) {
DWORD symId;
value->get_symIndexId(&symId);
o << L", " << valueLabel << L": id=" << symId;
}
}
std::wstring GetDebugInfoAsText(IDiaDataSource *pDataSource) {
CComPtr<IDiaSession> pSession;
CComPtr<IDiaTable> pTable;
CComPtr<IDiaEnumTables> pEnumTables;
std::wstringstream o;
VERIFY_SUCCEEDED(pDataSource->openSession(&pSession));
VERIFY_SUCCEEDED(pSession->getEnumTables(&pEnumTables));
LONG count;
VERIFY_SUCCEEDED(pEnumTables->get_Count(&count));
for (LONG i = 0; i < count; ++i) {
pTable.Release();
ULONG fetched;
VERIFY_SUCCEEDED(pEnumTables->Next(1, &pTable, &fetched));
VERIFY_ARE_EQUAL(fetched, 1u);
CComBSTR tableName;
VERIFY_SUCCEEDED(pTable->get_name(&tableName));
o << L"Table: " << (LPWSTR)tableName << std::endl;
LONG rowCount;
IFT(pTable->get_Count(&rowCount));
o << L" Row count: " << rowCount << std::endl;
for (LONG rowIndex = 0; rowIndex < rowCount; ++rowIndex) {
CComPtr<IUnknown> item;
o << L'#' << rowIndex;
IFT(pTable->Item(rowIndex, &item));
CComPtr<IDiaSymbol> pSymbol;
if (SUCCEEDED(item.QueryInterface(&pSymbol))) {
DWORD symTag;
DWORD dataKind;
DWORD locationType;
DWORD registerId;
pSymbol->get_symTag(&symTag);
pSymbol->get_dataKind(&dataKind);
pSymbol->get_locationType(&locationType);
pSymbol->get_registerId(®isterId);
// pSymbol->get_value(&value);
WriteIfValue(pSymbol.p, o, 0, L"symIndexId",
&IDiaSymbol::get_symIndexId);
o << L", " << SymTagEnumText[symTag];
if (dataKind != 0)
o << L", " << DataKindText[dataKind];
WriteIfValue(pSymbol.p, o, L"name", &IDiaSymbol::get_name);
WriteIfValue(pSymbol.p, o, L"lexicalParent",
&IDiaSymbol::get_lexicalParent);
WriteIfValue(pSymbol.p, o, L"type", &IDiaSymbol::get_type);
WriteIfValue(pSymbol.p, o, 0, L"slot", &IDiaSymbol::get_slot);
WriteIfValue(pSymbol.p, o, 0, L"platform", &IDiaSymbol::get_platform);
WriteIfValue(pSymbol.p, o, 0, L"language", &IDiaSymbol::get_language);
WriteIfValue(pSymbol.p, o, 0, L"frontEndMajor",
&IDiaSymbol::get_frontEndMajor);
WriteIfValue(pSymbol.p, o, 0, L"frontEndMinor",
&IDiaSymbol::get_frontEndMinor);
WriteIfValue(pSymbol.p, o, 0, L"token", &IDiaSymbol::get_token);
WriteIfValue(pSymbol.p, o, L"value", &IDiaSymbol::get_value);
WriteIfValue(pSymbol.p, o, 0, L"code", &IDiaSymbol::get_code);
WriteIfValue(pSymbol.p, o, 0, L"function", &IDiaSymbol::get_function);
WriteIfValue(pSymbol.p, o, 0, L"udtKind", &IDiaSymbol::get_udtKind);
WriteIfValue(pSymbol.p, o, 0, L"hasDebugInfo",
&IDiaSymbol::get_hasDebugInfo);
WriteIfValue(pSymbol.p, o, L"compilerName",
&IDiaSymbol::get_compilerName);
WriteIfValue(pSymbol.p, o, 0, L"isLocationControlFlowDependent",
&IDiaSymbol::get_isLocationControlFlowDependent);
WriteIfValue(pSymbol.p, o, 0, L"numberOfRows",
&IDiaSymbol::get_numberOfRows);
WriteIfValue(pSymbol.p, o, 0, L"numberOfColumns",
&IDiaSymbol::get_numberOfColumns);
WriteIfValue(pSymbol.p, o, 0, L"length", &IDiaSymbol::get_length);
WriteIfValue(pSymbol.p, o, 0, L"isMatrixRowMajor",
&IDiaSymbol::get_isMatrixRowMajor);
WriteIfValue(pSymbol.p, o, 0, L"builtInKind",
&IDiaSymbol::get_builtInKind);
WriteIfValue(pSymbol.p, o, 0, L"textureSlot",
&IDiaSymbol::get_textureSlot);
WriteIfValue(pSymbol.p, o, 0, L"memorySpaceKind",
&IDiaSymbol::get_memorySpaceKind);
WriteIfValue(pSymbol.p, o, 0, L"isHLSLData",
&IDiaSymbol::get_isHLSLData);
}
CComPtr<IDiaSourceFile> pSourceFile;
if (SUCCEEDED(item.QueryInterface(&pSourceFile))) {
WriteIfValue(pSourceFile.p, o, 0, L"uniqueId",
&IDiaSourceFile::get_uniqueId);
WriteIfValue(pSourceFile.p, o, L"fileName",
&IDiaSourceFile::get_fileName);
}
CComPtr<IDiaLineNumber> pLineNumber;
if (SUCCEEDED(item.QueryInterface(&pLineNumber))) {
WriteIfValue(pLineNumber.p, o, L"compiland",
&IDiaLineNumber::get_compiland);
// WriteIfValue(pLineNumber.p, o, L"sourceFile",
// &IDiaLineNumber::get_sourceFile);
WriteIfValue(pLineNumber.p, o, 0, L"lineNumber",
&IDiaLineNumber::get_lineNumber);
WriteIfValue(pLineNumber.p, o, 0, L"lineNumberEnd",
&IDiaLineNumber::get_lineNumberEnd);
WriteIfValue(pLineNumber.p, o, 0, L"columnNumber",
&IDiaLineNumber::get_columnNumber);
WriteIfValue(pLineNumber.p, o, 0, L"columnNumberEnd",
&IDiaLineNumber::get_columnNumberEnd);
WriteIfValue(pLineNumber.p, o, 0, L"addressSection",
&IDiaLineNumber::get_addressSection);
WriteIfValue(pLineNumber.p, o, 0, L"addressOffset",
&IDiaLineNumber::get_addressOffset);
WriteIfValue(pLineNumber.p, o, 0, L"relativeVirtualAddress",
&IDiaLineNumber::get_relativeVirtualAddress);
WriteIfValue(pLineNumber.p, o, 0, L"virtualAddress",
&IDiaLineNumber::get_virtualAddress);
WriteIfValue(pLineNumber.p, o, 0, L"length",
&IDiaLineNumber::get_length);
WriteIfValue(pLineNumber.p, o, 0, L"sourceFileId",
&IDiaLineNumber::get_sourceFileId);
WriteIfValue(pLineNumber.p, o, 0, L"statement",
&IDiaLineNumber::get_statement);
WriteIfValue(pLineNumber.p, o, 0, L"compilandId",
&IDiaLineNumber::get_compilandId);
}
CComPtr<IDiaSectionContrib> pSectionContrib;
if (SUCCEEDED(item.QueryInterface(&pSectionContrib))) {
WriteIfValue(pSectionContrib.p, o, L"compiland",
&IDiaSectionContrib::get_compiland);
WriteIfValue(pSectionContrib.p, o, 0, L"addressSection",
&IDiaSectionContrib::get_addressSection);
WriteIfValue(pSectionContrib.p, o, 0, L"addressOffset",
&IDiaSectionContrib::get_addressOffset);
WriteIfValue(pSectionContrib.p, o, 0, L"relativeVirtualAddress",
&IDiaSectionContrib::get_relativeVirtualAddress);
WriteIfValue(pSectionContrib.p, o, 0, L"virtualAddress",
&IDiaSectionContrib::get_virtualAddress);
WriteIfValue(pSectionContrib.p, o, 0, L"length",
&IDiaSectionContrib::get_length);
WriteIfValue(pSectionContrib.p, o, 0, L"notPaged",
&IDiaSectionContrib::get_notPaged);
WriteIfValue(pSectionContrib.p, o, 0, L"code",
&IDiaSectionContrib::get_code);
WriteIfValue(pSectionContrib.p, o, 0, L"initializedData",
&IDiaSectionContrib::get_initializedData);
WriteIfValue(pSectionContrib.p, o, 0, L"uninitializedData",
&IDiaSectionContrib::get_uninitializedData);
WriteIfValue(pSectionContrib.p, o, 0, L"remove",
&IDiaSectionContrib::get_remove);
WriteIfValue(pSectionContrib.p, o, 0, L"comdat",
&IDiaSectionContrib::get_comdat);
WriteIfValue(pSectionContrib.p, o, 0, L"discardable",
&IDiaSectionContrib::get_discardable);
WriteIfValue(pSectionContrib.p, o, 0, L"notCached",
&IDiaSectionContrib::get_notCached);
WriteIfValue(pSectionContrib.p, o, 0, L"share",
&IDiaSectionContrib::get_share);
WriteIfValue(pSectionContrib.p, o, 0, L"execute",
&IDiaSectionContrib::get_execute);
WriteIfValue(pSectionContrib.p, o, 0, L"read",
&IDiaSectionContrib::get_read);
WriteIfValue(pSectionContrib.p, o, 0, L"write",
&IDiaSectionContrib::get_write);
WriteIfValue(pSectionContrib.p, o, 0, L"dataCrc",
&IDiaSectionContrib::get_dataCrc);
WriteIfValue(pSectionContrib.p, o, 0, L"relocationsCrc",
&IDiaSectionContrib::get_relocationsCrc);
WriteIfValue(pSectionContrib.p, o, 0, L"compilandId",
&IDiaSectionContrib::get_compilandId);
}
CComPtr<IDiaSegment> pSegment;
if (SUCCEEDED(item.QueryInterface(&pSegment))) {
WriteIfValue(pSegment.p, o, 0, L"frame", &IDiaSegment::get_frame);
WriteIfValue(pSegment.p, o, 0, L"offset", &IDiaSegment::get_offset);
WriteIfValue(pSegment.p, o, 0, L"length", &IDiaSegment::get_length);
WriteIfValue(pSegment.p, o, 0, L"read", &IDiaSegment::get_read);
WriteIfValue(pSegment.p, o, 0, L"write", &IDiaSegment::get_write);
WriteIfValue(pSegment.p, o, 0, L"execute", &IDiaSegment::get_execute);
WriteIfValue(pSegment.p, o, 0, L"addressSection",
&IDiaSegment::get_addressSection);
WriteIfValue(pSegment.p, o, 0, L"relativeVirtualAddress",
&IDiaSegment::get_relativeVirtualAddress);
WriteIfValue(pSegment.p, o, 0, L"virtualAddress",
&IDiaSegment::get_virtualAddress);
}
CComPtr<IDiaInjectedSource> pInjectedSource;
if (SUCCEEDED(item.QueryInterface(&pInjectedSource))) {
WriteIfValue(pInjectedSource.p, o, 0, L"crc",
&IDiaInjectedSource::get_crc);
WriteIfValue(pInjectedSource.p, o, 0, L"length",
&IDiaInjectedSource::get_length);
WriteIfValue(pInjectedSource.p, o, L"filename",
&IDiaInjectedSource::get_filename);
WriteIfValue(pInjectedSource.p, o, L"objectFilename",
&IDiaInjectedSource::get_objectFilename);
WriteIfValue(pInjectedSource.p, o, L"virtualFilename",
&IDiaInjectedSource::get_virtualFilename);
WriteIfValue(pInjectedSource.p, o, 0, L"sourceCompression",
&IDiaInjectedSource::get_sourceCompression);
// get_source is also available
}
CComPtr<IDiaFrameData> pFrameData;
if (SUCCEEDED(item.QueryInterface(&pFrameData))) {
}
o << std::endl;
}
}
return o.str();
}
std::wstring GetDebugFileContent(IDiaDataSource *pDataSource) {
CComPtr<IDiaSession> pSession;
CComPtr<IDiaTable> pTable;
CComPtr<IDiaTable> pSourcesTable;
CComPtr<IDiaEnumTables> pEnumTables;
std::wstringstream o;
VERIFY_SUCCEEDED(pDataSource->openSession(&pSession));
VERIFY_SUCCEEDED(pSession->getEnumTables(&pEnumTables));
ULONG fetched = 0;
while (pEnumTables->Next(1, &pTable, &fetched) == S_OK && fetched == 1) {
CComBSTR name;
IFT(pTable->get_name(&name));
if (wcscmp(name, L"SourceFiles") == 0) {
pSourcesTable = pTable.Detach();
continue;
}
pTable.Release();
}
if (!pSourcesTable) {
return L"cannot find source";
}
// Get source file contents.
// NOTE: "SourceFiles" has the root file first while "InjectedSources" is in
// alphabetical order.
// It is important to keep the root file first for recompilation, so
// iterate "SourceFiles" and look up the corresponding injected
// source.
LONG count;
IFT(pSourcesTable->get_Count(&count));
CComPtr<IDiaSourceFile> pSourceFile;
CComBSTR pName;
CComPtr<IUnknown> pSymbolUnk;
CComPtr<IDiaEnumInjectedSources> pEnumInjectedSources;
CComPtr<IDiaInjectedSource> pInjectedSource;
std::wstring sourceText, sourceFilename;
while (SUCCEEDED(pSourcesTable->Next(1, &pSymbolUnk, &fetched)) &&
fetched == 1) {
sourceText = sourceFilename = L"";
IFT(pSymbolUnk->QueryInterface(&pSourceFile));
IFT(pSourceFile->get_fileName(&pName));
IFT(pSession->findInjectedSource(pName, &pEnumInjectedSources));
if (SUCCEEDED(pEnumInjectedSources->get_Count(&count)) && count == 1) {
IFT(pEnumInjectedSources->Item(0, &pInjectedSource));
DWORD cbData = 0;
std::string tempString;
CComBSTR bstr;
IFT(pInjectedSource->get_filename(&bstr));
IFT(pInjectedSource->get_source(0, &cbData, nullptr));
tempString.resize(cbData);
IFT(pInjectedSource->get_source(
cbData, &cbData, reinterpret_cast<BYTE *>(&tempString[0])));
CA2W tempWString(tempString.data());
o << tempWString.m_psz;
}
pSymbolUnk.Release();
}
return o.str();
}
struct LineNumber {
DWORD line;
DWORD rva;
};
std::vector<LineNumber>
ReadLineNumbers(IDiaEnumLineNumbers *pEnumLineNumbers) {
std::vector<LineNumber> lines;
CComPtr<IDiaLineNumber> pLineNumber;
DWORD lineCount;
while (SUCCEEDED(pEnumLineNumbers->Next(1, &pLineNumber, &lineCount)) &&
lineCount == 1) {
DWORD line;
DWORD rva;
VERIFY_SUCCEEDED(pLineNumber->get_lineNumber(&line));
VERIFY_SUCCEEDED(pLineNumber->get_relativeVirtualAddress(&rva));
lines.push_back({line, rva});
pLineNumber.Release();
}
return lines;
}
HRESULT CreateDiaSourceForCompile(const char *hlsl,
IDiaDataSource **ppDiaSource) {
if (!ppDiaSource)
return E_POINTER;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
VERIFY_SUCCEEDED(CreateCompiler(m_dllSupport, &pCompiler));
CreateBlobFromText(m_dllSupport, hlsl, &pSource);
LPCWSTR args[] = {L"/Zi", L"/Qembed_debug", L"/Od"};
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"source.hlsl", L"main",
L"ps_6_0", args, _countof(args),
nullptr, 0, nullptr, &pResult));
HRESULT compilationStatus;
VERIFY_SUCCEEDED(pResult->GetStatus(&compilationStatus));
if (FAILED(compilationStatus)) {
CComPtr<IDxcBlobEncoding> pErrros;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&pErrros));
CA2W errorTextW(static_cast<const char *>(pErrros->GetBufferPointer()),
CP_UTF8);
WEX::Logging::Log::Error(errorTextW);
}
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
// Disassemble the compiled (stripped) program.
{
CComPtr<IDxcBlobEncoding> pDisassembly;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembly));
std::string disText = BlobToUtf8(pDisassembly);
CA2W disTextW(disText.c_str());
// WEX::Logging::Log::Comment(disTextW);
}
auto annotated = WrapInNewContainer(
m_dllSupport, RunAnnotationPasses(m_dllSupport, pProgram).blob);
// CONSIDER: have the dia data source look for the part if passed a whole
// container.
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pProgramStream;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
const hlsl::DxilContainerHeader *pContainer = hlsl::IsDxilContainerLike(
annotated->GetBufferPointer(), annotated->GetBufferSize());
VERIFY_IS_NOT_NULL(pContainer);
hlsl::DxilPartIterator partIter =
std::find_if(hlsl::begin(pContainer), hlsl::end(pContainer),
hlsl::DxilPartIsType(hlsl::DFCC_ShaderDebugInfoDXIL));
const hlsl::DxilProgramHeader *pProgramHeader =
(const hlsl::DxilProgramHeader *)hlsl::GetDxilPartData(*partIter);
uint32_t bitcodeLength;
const char *pBitcode;
CComPtr<IDxcBlob> pProgramPdb;
hlsl::GetDxilProgramBitcode(pProgramHeader, &pBitcode, &bitcodeLength);
VERIFY_SUCCEEDED(pLib->CreateBlobFromBlob(
annotated, pBitcode - (char *)annotated->GetBufferPointer(),
bitcodeLength, &pProgramPdb));
// Disassemble the program with debug information.
{
CComPtr<IDxcBlobEncoding> pDbgDisassembly;
VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgramPdb, &pDbgDisassembly));
std::string disText = BlobToUtf8(pDbgDisassembly);
CA2W disTextW(disText.c_str());
// WEX::Logging::Log::Comment(disTextW);
}
// Create a short text dump of debug information.
VERIFY_SUCCEEDED(
pLib->CreateStreamFromBlobReadOnly(pProgramPdb, &pProgramStream));
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaSource));
VERIFY_SUCCEEDED(pDiaSource->loadDataFromIStream(pProgramStream));
*ppDiaSource = pDiaSource.Detach();
return S_OK;
}
void CompileAndRunAnnotationAndGetDebugPart(
dxc::DxcDllSupport &dllSupport, const char *source,
const wchar_t *profile, IDxcIncludeHandler *includer,
IDxcBlob **ppDebugPart,
std::vector<const wchar_t *> extraArgs = {L"-Od"});
void CompileAndRunAnnotationAndLoadDiaSource(
dxc::DxcDllSupport &dllSupport, const char *source,
const wchar_t *profile, IDxcIncludeHandler *includer,
IDiaDataSource **ppDataSource,
std::vector<const wchar_t *> extraArgs = {L"-Od"});
struct VariableComponentInfo {
std::wstring Name;
std::wstring Type;
};
void TestGlobalStaticCase(
const char *hlsl, const wchar_t *profile,
const char *lineAtWhichToExamineVariables,
std::vector<VariableComponentInfo> const &ExpectedVariables);
void RunSizeAndOffsetTestCase(const char *hlsl,
std::array<DWORD, 4> const &memberOffsets,
std::array<DWORD, 4> const &memberSizes,
std::vector<const wchar_t *> extraArgs = {
L"-Od"});
void RunVectorSizeAndOffsetTestCase(const char *hlsl,
std::array<DWORD, 4> const &memberOffsets,
std::vector<const wchar_t *> extraArgs = {
L"-Od"});
DebuggerInterfaces
CompileAndCreateDxcDebug(const char *hlsl, const wchar_t *profile,
IDxcIncludeHandler *includer = nullptr,
std::vector<const wchar_t *> extraArgs = {L"-Od"});
CComPtr<IDxcPixDxilLiveVariables>
GetLiveVariablesAt(const char *hlsl,
const char *lineAtWhichToExamineVariables,
IDxcPixDxilDebugInfo *dxilDebugger);
};
static bool AddStorageComponents(
IDxcPixDxilStorage *pStorage, std::wstring Name,
std::vector<PixDiaTest::VariableComponentInfo> &VariableComponents) {
CComPtr<IDxcPixType> StorageType;
if (FAILED(pStorage->GetType(&StorageType))) {
return false;
}
CComPtr<IDxcPixType> UnAliasedType;
if (FAILED(UnAliasType(StorageType, &UnAliasedType))) {
return false;
}
CComPtr<IDxcPixArrayType> ArrayType;
CComPtr<IDxcPixScalarType> ScalarType;
CComPtr<IDxcPixStructType2> StructType;
if (!FAILED(UnAliasedType->QueryInterface(&ScalarType))) {
CComBSTR TypeName;
// StorageType is the type that the storage was defined in HLSL, i.e.,
// it could be a typedef, const etc.
if (FAILED(StorageType->GetName(&TypeName))) {
return false;
}
VariableComponents.emplace_back(PixDiaTest::VariableComponentInfo{
std::move(Name), std::wstring(TypeName)});
return true;
} else if (!FAILED(UnAliasedType->QueryInterface(&ArrayType))) {
DWORD NumElements;
if (FAILED(ArrayType->GetNumElements(&NumElements))) {
return false;
}
std::wstring BaseName = Name + L'[';
for (DWORD i = 0; i < NumElements; ++i) {
CComPtr<IDxcPixDxilStorage> EntryStorage;
if (FAILED(pStorage->Index(i, &EntryStorage))) {
return false;
}
if (!AddStorageComponents(EntryStorage,
BaseName + std::to_wstring(i) + L"]",
VariableComponents)) {
return false;
}
}
} else if (!FAILED(UnAliasedType->QueryInterface(&StructType))) {
DWORD NumFields;
if (FAILED(StructType->GetNumFields(&NumFields))) {
return false;
}
std::wstring BaseName = Name + L'.';
for (DWORD i = 0; i < NumFields; ++i) {
CComPtr<IDxcPixStructField> Field;
if (FAILED(StructType->GetFieldByIndex(i, &Field))) {
return false;
}
CComBSTR FieldName;
if (FAILED(Field->GetName(&FieldName))) {
return false;
}
CComPtr<IDxcPixDxilStorage> FieldStorage;
if (FAILED(pStorage->AccessField(FieldName, &FieldStorage))) {
return false;
}
if (!AddStorageComponents(FieldStorage,
BaseName + std::wstring(FieldName),
VariableComponents)) {
return false;
}
}
CComPtr<IDxcPixType> BaseType;
if (SUCCEEDED(StructType->GetBaseType(&BaseType))) {
CComPtr<IDxcPixDxilStorage> BaseStorage;
if (FAILED(pStorage->AccessField(L"", &BaseStorage))) {
return false;
}
if (!AddStorageComponents(BaseStorage, Name, VariableComponents)) {
return false;
}
}
}
return true;
}
bool PixDiaTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
void PixDiaTest::CompileAndRunAnnotationAndGetDebugPart(
dxc::DxcDllSupport &dllSupport, const char *source, const wchar_t *profile,
IDxcIncludeHandler *includer, IDxcBlob **ppDebugPart,
std::vector<const wchar_t *> extraArgs) {
CComPtr<IDxcBlob> pContainer;
std::vector<LPCWSTR> args;
args.push_back(L"/Zi");
args.push_back(L"/Qembed_debug");
args.insert(args.end(), extraArgs.begin(), extraArgs.end());
CompileAndLogErrors(dllSupport, source, profile, args, includer, &pContainer);
auto annotated = RunAnnotationPasses(m_dllSupport, pContainer);
CComPtr<IDxcBlob> pNewContainer =
WrapInNewContainer(m_dllSupport, annotated.blob);
*ppDebugPart = GetDebugPart(dllSupport, pNewContainer).Detach();
}
DebuggerInterfaces
PixDiaTest::CompileAndCreateDxcDebug(const char *hlsl, const wchar_t *profile,
IDxcIncludeHandler *includer,
std::vector<const wchar_t *> extraArgs) {
CComPtr<IDiaDataSource> pDiaDataSource;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, profile, includer,
&pDiaDataSource, extraArgs);
CComPtr<IDiaSession> session;
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&session));
CComPtr<IDxcPixDxilDebugInfoFactory> Factory;
VERIFY_SUCCEEDED(session->QueryInterface(IID_PPV_ARGS(&Factory)));
DebuggerInterfaces ret;
VERIFY_SUCCEEDED(Factory->NewDxcPixDxilDebugInfo(&ret.debugInfo));
VERIFY_SUCCEEDED(Factory->NewDxcPixCompilationInfo(&ret.compilationInfo));
return ret;
}
CComPtr<IDxcPixDxilLiveVariables>
PixDiaTest::GetLiveVariablesAt(const char *hlsl,
const char *lineAtWhichToExamineVariables,
IDxcPixDxilDebugInfo *dxilDebugger) {
auto lines = SplitAndPreserveEmptyLines(std::string(hlsl), '\n');
auto FindInterestingLine = std::find_if(
lines.begin(), lines.end(),
[&lineAtWhichToExamineVariables](std::string const &line) {
return line.find(lineAtWhichToExamineVariables) != std::string::npos;
});
auto InterestingLine =
static_cast<DWORD>(FindInterestingLine - lines.begin()) + 1;
CComPtr<IDxcPixDxilLiveVariables> liveVariables;
for (; InterestingLine <= static_cast<DWORD>(lines.size());
++InterestingLine) {
CComPtr<IDxcPixDxilInstructionOffsets> instructionOffsets;
if (SUCCEEDED(dxilDebugger->InstructionOffsetsFromSourceLocation(
defaultFilename, InterestingLine, 0, &instructionOffsets))) {
if (instructionOffsets->GetCount() > 0) {
auto instructionOffset = instructionOffsets->GetOffsetByIndex(0);
if (SUCCEEDED(dxilDebugger->GetLiveVariablesAt(instructionOffset,
&liveVariables))) {
break;
}
}
}
}
VERIFY_IS_TRUE(liveVariables != nullptr);
return liveVariables;
}
static bool
ContainedBy(std::vector<PixDiaTest::VariableComponentInfo> const &v1,
std::vector<PixDiaTest::VariableComponentInfo> const &v2) {
for (auto const &c1 : v1) {
bool FoundThis = false;
for (auto const &c2 : v2) {
if (c1.Name == c2.Name && c1.Type == c2.Type) {
FoundThis = true;
break;
}
}
if (!FoundThis) {
return false;
}
}
return true;
}
void PixDiaTest::TestGlobalStaticCase(
const char *hlsl, const wchar_t *profile,
const char *lineAtWhichToExamineVariables,
std::vector<VariableComponentInfo> const &ExpectedVariables) {
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, profile).debugInfo;
auto liveVariables =
GetLiveVariablesAt(hlsl, lineAtWhichToExamineVariables, dxilDebugger);
DWORD count;
VERIFY_SUCCEEDED(liveVariables->GetCount(&count));
bool FoundGlobal = false;
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &variable));
CComBSTR name;
variable->GetName(&name);
if (0 == wcscmp(name, L"global.globalStruct")) {
FoundGlobal = true;
CComPtr<IDxcPixDxilStorage> storage;
VERIFY_SUCCEEDED(variable->GetStorage(&storage));
std::vector<VariableComponentInfo> ActualVariableComponents;
VERIFY_IS_TRUE(AddStorageComponents(storage, L"global.globalStruct",
ActualVariableComponents));
VERIFY_IS_TRUE(ContainedBy(ActualVariableComponents, ExpectedVariables));
break;
}
}
VERIFY_IS_TRUE(FoundGlobal);
}
TEST_F(PixDiaTest, CompileWhenDebugThenDIPresent) {
// BUG: the first test written was of this form:
// float4 local = 0; return local;
//
// However we get no numbers because of the _wrapper form
// that exports the zero initialization from main into
// a global can't be attributed to any particular location
// within main, and everything in main is eventually folded away.
//
// Making the function do a bit more work by calling an intrinsic
// helps this case.
CComPtr<IDiaDataSource> pDiaSource;
VERIFY_SUCCEEDED(CreateDiaSourceForCompile(
"float4 main(float4 pos : SV_Position) : SV_Target {\r\n"
" float4 local = abs(pos);\r\n"
" return local;\r\n"
"}",
&pDiaSource));
std::wstring diaDump = GetDebugInfoAsText(pDiaSource).c_str();
// WEX::Logging::Log::Comment(GetDebugInfoAsText(pDiaSource).c_str());
// Very basic tests - we have basic symbols, line numbers, and files with
// sources.
VERIFY_IS_NOT_NULL(wcsstr(diaDump.c_str(),
L"symIndexId: 5, CompilandEnv, name: hlslTarget, "
L"lexicalParent: id=2, value: ps_6_0"));
VERIFY_IS_NOT_NULL(wcsstr(diaDump.c_str(), L"lineNumber: 2"));
VERIFY_IS_NOT_NULL(
wcsstr(diaDump.c_str(), L"length: 99, filename: source.hlsl"));
std::wstring diaFileContent = GetDebugFileContent(pDiaSource).c_str();
VERIFY_IS_NOT_NULL(
wcsstr(diaFileContent.c_str(),
L"loat4 main(float4 pos : SV_Position) : SV_Target"));
#if SUPPORT_FXC_PDB
// Now, fake it by loading from a .pdb!
VERIFY_SUCCEEDED(CoInitializeEx(0, COINITBASE_MULTITHREADED));
const wchar_t path[] = L"path-to-fxc-blob.bin";
pDiaSource.Release();
pProgramStream.Release();
CComPtr<IDxcBlobEncoding> fxcBlob;
CComPtr<IDxcBlob> pdbBlob;
VERIFY_SUCCEEDED(pLib->CreateBlobFromFile(path, nullptr, &fxcBlob));
std::string s = DumpParts(fxcBlob);
CA2W sW(s.c_str());
WEX::Logging::Log::Comment(sW);
VERIFY_SUCCEEDED(CreateDiaSourceFromDxbcBlob(pLib, fxcBlob, &pDiaSource));
WEX::Logging::Log::Comment(GetDebugInfoAsText(pDiaSource).c_str());
#endif
}
// Test that the new PDB format still works with Dia
TEST_F(PixDiaTest, CompileDebugPDB) {
const char *hlsl = R"(
[RootSignature("")]
float main(float pos : A) : SV_Target {
float x = abs(pos);
float y = sin(pos);
float z = x + y;
return z;
}
)";
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcCompiler2> pCompiler2;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
CComPtr<IDxcBlob> pProgram;
CComPtr<IDxcBlob> pPdbBlob;
CComHeapPtr<WCHAR> pDebugName;
VERIFY_SUCCEEDED(CreateCompiler(m_dllSupport, &pCompiler));
VERIFY_SUCCEEDED(pCompiler.QueryInterface(&pCompiler2));
CreateBlobFromText(m_dllSupport, hlsl, &pSource);
LPCWSTR args[] = {L"/Zi", L"/Qembed_debug"};
VERIFY_SUCCEEDED(pCompiler2->CompileWithDebug(
pSource, L"source.hlsl", L"main", L"ps_6_0", args, _countof(args),
nullptr, 0, nullptr, &pResult, &pDebugName, &pPdbBlob));
VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pProgramStream;
VERIFY_SUCCEEDED(
pLib->CreateStreamFromBlobReadOnly(pPdbBlob, &pProgramStream));
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaSource));
VERIFY_SUCCEEDED(pDiaSource->loadDataFromIStream(pProgramStream));
// Test that IDxcContainerReflection can consume a PDB container
CComPtr<IDxcContainerReflection> pReflection;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(pReflection->Load(pPdbBlob));
UINT32 uDebugInfoIndex = 0;
VERIFY_SUCCEEDED(pReflection->FindFirstPartKind(
hlsl::DFCC_ShaderDebugInfoDXIL, &uDebugInfoIndex));
}
TEST_F(PixDiaTest, DiaLoadBadBitcodeThenFail) {
CComPtr<IDxcBlob> pBadBitcode;
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pStream;
CComPtr<IDxcLibrary> pLib;
Utf8ToBlob(m_dllSupport, "badcode", &pBadBitcode);
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
VERIFY_SUCCEEDED(pLib->CreateStreamFromBlobReadOnly(pBadBitcode, &pStream));
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaSource));
VERIFY_FAILED(pDiaSource->loadDataFromIStream(pStream));
}
static void CompileTestAndLoadDiaSource(dxc::DxcDllSupport &dllSupport,
const char *source,
const wchar_t *profile,
IDiaDataSource **ppDataSource) {
CComPtr<IDxcBlob> pDebugContent;
CComPtr<IStream> pStream;
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CompileAndGetDebugPart(dllSupport, source, profile, &pDebugContent);
VERIFY_SUCCEEDED(pLib->CreateStreamFromBlobReadOnly(pDebugContent, &pStream));
VERIFY_SUCCEEDED(
dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaSource));
VERIFY_SUCCEEDED(pDiaSource->loadDataFromIStream(pStream));
if (ppDataSource) {
*ppDataSource = pDiaSource.Detach();
}
}
static void CompileTestAndLoadDia(dxc::DxcDllSupport &dllSupport,
IDiaDataSource **ppDataSource) {
CompileTestAndLoadDiaSource(dllSupport, "[numthreads(8,8,1)] void main() { }",
L"cs_6_0", ppDataSource);
}
TEST_F(PixDiaTest, DiaLoadDebugSubrangeNegativeThenOK) {
static const char source[] = R"(
SamplerState samp0 : register(s0);
Texture2DArray tex0 : register(t0);
float4 foo(Texture2DArray textures[], int idx, SamplerState samplerState, float3 uvw) {
return textures[NonUniformResourceIndex(idx)].Sample(samplerState, uvw);
}
[RootSignature( "DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)) " )]
float4 main(int index : INDEX, float3 uvw : TEXCOORD) : SV_Target {
Texture2DArray textures[] = {
tex0,
};
return foo(textures, index, samp0, uvw);
}
)";
CComPtr<IDiaDataSource> pDiaDataSource;
CComPtr<IDiaSession> pDiaSession;
CompileTestAndLoadDiaSource(m_dllSupport, source, L"ps_6_0", &pDiaDataSource);
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pDiaSession));
}
TEST_F(PixDiaTest, DiaLoadRelocatedBitcode) {
static const char source[] = R"(
SamplerState samp0 : register(s0);
Texture2DArray tex0 : register(t0);
float4 foo(Texture2DArray textures[], int idx, SamplerState samplerState, float3 uvw) {
return textures[NonUniformResourceIndex(idx)].Sample(samplerState, uvw);
}
[RootSignature( "DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)) " )]
float4 main(int index : INDEX, float3 uvw : TEXCOORD) : SV_Target {
Texture2DArray textures[] = {
tex0,
};
return foo(textures, index, samp0, uvw);
}
)";
CComPtr<IDxcBlob> pPart;
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pStream;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CompileAndGetDebugPart(m_dllSupport, source, L"ps_6_0", &pPart);
const char *pPartData = (char *)pPart->GetBufferPointer();
// Get program header
const hlsl::DxilProgramHeader *programHeader =
(const hlsl::DxilProgramHeader *)pPartData;
const char *pBitcode = nullptr;
uint32_t uBitcodeSize = 0;
hlsl::GetDxilProgramBitcode(programHeader, &pBitcode, &uBitcodeSize);
VERIFY_IS_TRUE(uBitcodeSize % sizeof(UINT32) == 0);
size_t uNewGapSize =
4 * 10; // Size of some bytes between program header and bitcode
size_t uNewSuffixeBytes =
4 * 10; // Size of some random bytes after the program
hlsl::DxilProgramHeader newProgramHeader = {};
memcpy(&newProgramHeader, programHeader, sizeof(newProgramHeader));
newProgramHeader.BitcodeHeader.BitcodeOffset =
uNewGapSize + sizeof(newProgramHeader.BitcodeHeader);
unsigned uNewSizeInBytes =
sizeof(newProgramHeader) + uNewGapSize + uBitcodeSize + uNewSuffixeBytes;
VERIFY_IS_TRUE(uNewSizeInBytes % sizeof(UINT32) == 0);
newProgramHeader.SizeInUint32 = uNewSizeInBytes / sizeof(UINT32);
llvm::SmallVector<char, 0> buffer;
llvm::raw_svector_ostream OS(buffer);
// Write the header
OS.write((char *)&newProgramHeader, sizeof(newProgramHeader));
// Write some garbage between the header and the bitcode
for (unsigned i = 0; i < uNewGapSize; i++) {
OS.write(0xFF);
}
// Write the actual bitcode
OS.write(pBitcode, uBitcodeSize);
// Write some garbage after the bitcode
for (unsigned i = 0; i < uNewSuffixeBytes; i++) {
OS.write(0xFF);
}
OS.flush();
// Try to load this new program, make sure dia is still okay.
CComPtr<IDxcBlobEncoding> pNewProgramBlob;
VERIFY_SUCCEEDED(pLib->CreateBlobWithEncodingFromPinned(
buffer.data(), buffer.size(), CP_ACP, &pNewProgramBlob));
CComPtr<IStream> pNewProgramStream;
VERIFY_SUCCEEDED(
pLib->CreateStreamFromBlobReadOnly(pNewProgramBlob, &pNewProgramStream));
CComPtr<IDiaDataSource> pDiaDataSource;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaDataSource));
VERIFY_SUCCEEDED(pDiaDataSource->loadDataFromIStream(pNewProgramStream));
}
TEST_F(PixDiaTest, DiaCompileArgs) {
static const char source[] = R"(
SamplerState samp0 : register(s0);
Texture2DArray tex0 : register(t0);
float4 foo(Texture2DArray textures[], int idx, SamplerState samplerState, float3 uvw) {
return textures[NonUniformResourceIndex(idx)].Sample(samplerState, uvw);
}
[RootSignature( "DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)) " )]
float4 main(int index : INDEX, float3 uvw : TEXCOORD) : SV_Target {
Texture2DArray textures[] = {
tex0,
};
return foo(textures, index, samp0, uvw);
}
)";
CComPtr<IDxcBlob> pPart;
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pStream;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
const WCHAR *FlagList[] = {
L"/Zi", L"-Zpr", L"/Qembed_debug", L"/Fd",
L"F:\\my dir\\", L"-Fo", L"F:\\my dir\\file.dxc",
};
const WCHAR *DefineList[] = {
L"MY_SPECIAL_DEFINE",
L"MY_OTHER_SPECIAL_DEFINE=\"MY_STRING\"",
};
std::vector<LPCWSTR> args;
for (unsigned i = 0; i < _countof(FlagList); i++) {
args.push_back(FlagList[i]);
}
for (unsigned i = 0; i < _countof(DefineList); i++) {
args.push_back(L"/D");
args.push_back(DefineList[i]);
}
auto CompileAndGetDebugPart = [&args](dxc::DxcDllSupport &dllSupport,
const char *source,
const wchar_t *profile,
IDxcBlob **ppDebugPart) {
CComPtr<IDxcBlob> pContainer;
CComPtr<IDxcLibrary> pLib;
CComPtr<IDxcContainerReflection> pReflection;
UINT32 index;
VerifyCompileOK(dllSupport, source, profile, args, &pContainer);
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
VERIFY_SUCCEEDED(
dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(pReflection->Load(pContainer));
VERIFY_SUCCEEDED(
pReflection->FindFirstPartKind(hlsl::DFCC_ShaderDebugInfoDXIL, &index));
VERIFY_SUCCEEDED(pReflection->GetPartContent(index, ppDebugPart));
};
CompileAndGetDebugPart(m_dllSupport, source, L"ps_6_0", &pPart);
CComPtr<IStream> pNewProgramStream;
VERIFY_SUCCEEDED(
pLib->CreateStreamFromBlobReadOnly(pPart, &pNewProgramStream));
CComPtr<IDiaDataSource> pDiaDataSource;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaDataSource));
VERIFY_SUCCEEDED(pDiaDataSource->loadDataFromIStream(pNewProgramStream));
CComPtr<IDiaSession> pSession;
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pSession));
CComPtr<IDiaEnumTables> pEnumTables;
VERIFY_SUCCEEDED(pSession->getEnumTables(&pEnumTables));
CComPtr<IDiaTable> pSymbolTable;
LONG uCount = 0;
VERIFY_SUCCEEDED(pEnumTables->get_Count(&uCount));
for (int i = 0; i < uCount; i++) {
CComPtr<IDiaTable> pTable;
VARIANT index = {};
index.vt = VT_I4;
index.intVal = i;
VERIFY_SUCCEEDED(pEnumTables->Item(index, &pTable));
CComBSTR pName;
VERIFY_SUCCEEDED(pTable->get_name(&pName));
if (pName == "Symbols") {
pSymbolTable = pTable;
break;
}
}
std::wstring Args;
std::wstring Entry;
std::wstring Target;
std::vector<std::wstring> Defines;
std::vector<std::wstring> Flags;
auto ReadNullSeparatedTokens = [](BSTR Str) -> std::vector<std::wstring> {
std::vector<std::wstring> Result;
while (*Str) {
Result.push_back(std::wstring(Str));
Str += wcslen(Str) + 1;
}
return Result;
};
VERIFY_SUCCEEDED(pSymbolTable->get_Count(&uCount));
for (int i = 0; i < uCount; i++) {
CComPtr<IUnknown> pSymbolUnk;
CComPtr<IDiaSymbol> pSymbol;
CComVariant pValue;
CComBSTR pName;
VERIFY_SUCCEEDED(pSymbolTable->Item(i, &pSymbolUnk));
VERIFY_SUCCEEDED(pSymbolUnk->QueryInterface(&pSymbol));
VERIFY_SUCCEEDED(pSymbol->get_name(&pName));
VERIFY_SUCCEEDED(pSymbol->get_value(&pValue));
if (pName == "hlslTarget") {
if (pValue.vt == VT_BSTR)
Target = pValue.bstrVal;
} else if (pName == "hlslEntry") {
if (pValue.vt == VT_BSTR)
Entry = pValue.bstrVal;
} else if (pName == "hlslFlags") {
if (pValue.vt == VT_BSTR)
Flags = ReadNullSeparatedTokens(pValue.bstrVal);
} else if (pName == "hlslArguments") {
if (pValue.vt == VT_BSTR)
Args = pValue.bstrVal;
} else if (pName == "hlslDefines") {
if (pValue.vt == VT_BSTR)
Defines = ReadNullSeparatedTokens(pValue.bstrVal);
}
}
auto VectorContains = [](std::vector<std::wstring> &Tokens,
std::wstring Sub) {
for (unsigned i = 0; i < Tokens.size(); i++) {
if (Tokens[i].find(Sub) != std::wstring::npos)
return true;
}
return false;
};
VERIFY_IS_TRUE(Target == L"ps_6_0");
VERIFY_IS_TRUE(Entry == L"main");
VERIFY_IS_TRUE(_countof(FlagList) == Flags.size());
for (unsigned i = 0; i < _countof(FlagList); i++) {
VERIFY_IS_TRUE(Flags[i] == FlagList[i]);
}
for (unsigned i = 0; i < _countof(DefineList); i++) {
VERIFY_IS_TRUE(VectorContains(Defines, DefineList[i]));
}
}
TEST_F(PixDiaTest, DiaLoadBitcodePlusExtraData) {
// Test that dia doesn't crash when bitcode has unused extra data at the end
static const char source[] = R"(
SamplerState samp0 : register(s0);
Texture2DArray tex0 : register(t0);
float4 foo(Texture2DArray textures[], int idx, SamplerState samplerState, float3 uvw) {
return textures[NonUniformResourceIndex(idx)].Sample(samplerState, uvw);
}
[RootSignature( "DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)) " )]
float4 main(int index : INDEX, float3 uvw : TEXCOORD) : SV_Target {
Texture2DArray textures[] = {
tex0,
};
return foo(textures, index, samp0, uvw);
}
)";
CComPtr<IDxcBlob> pPart;
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pStream;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CompileAndGetDebugPart(m_dllSupport, source, L"ps_6_0", &pPart);
const char *pPartData = (char *)pPart->GetBufferPointer();
// Get program header
const hlsl::DxilProgramHeader *programHeader =
(const hlsl::DxilProgramHeader *)pPartData;
const char *pBitcode = nullptr;
uint32_t uBitcodeSize = 0;
hlsl::GetDxilProgramBitcode(programHeader, &pBitcode, &uBitcodeSize);
llvm::SmallVector<char, 0> buffer;
llvm::raw_svector_ostream OS(buffer);
// Write the bitcode
OS.write(pBitcode, uBitcodeSize);
for (unsigned i = 0; i < 12; i++) {
OS.write(0xFF);
}
OS.flush();
// Try to load this new program, make sure dia is still okay.
CComPtr<IDxcBlobEncoding> pNewProgramBlob;
VERIFY_SUCCEEDED(pLib->CreateBlobWithEncodingFromPinned(
buffer.data(), buffer.size(), CP_ACP, &pNewProgramBlob));
CComPtr<IStream> pNewProgramStream;
VERIFY_SUCCEEDED(
pLib->CreateStreamFromBlobReadOnly(pNewProgramBlob, &pNewProgramStream));
CComPtr<IDiaDataSource> pDiaDataSource;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaDataSource));
VERIFY_SUCCEEDED(pDiaDataSource->loadDataFromIStream(pNewProgramStream));
}
TEST_F(PixDiaTest, DiaLoadDebugThenOK) {
CompileTestAndLoadDia(m_dllSupport, nullptr);
}
TEST_F(PixDiaTest, DiaTableIndexThenOK) {
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IDiaSession> pDiaSession;
CComPtr<IDiaEnumTables> pEnumTables;
CComPtr<IDiaTable> pTable;
VARIANT vtIndex;
CompileTestAndLoadDia(m_dllSupport, &pDiaSource);
VERIFY_SUCCEEDED(pDiaSource->openSession(&pDiaSession));
VERIFY_SUCCEEDED(pDiaSession->getEnumTables(&pEnumTables));
vtIndex.vt = VT_EMPTY;
VERIFY_FAILED(pEnumTables->Item(vtIndex, &pTable));
vtIndex.vt = VT_I4;
vtIndex.intVal = 1;
VERIFY_SUCCEEDED(pEnumTables->Item(vtIndex, &pTable));
VERIFY_IS_NOT_NULL(pTable.p);
pTable.Release();
vtIndex.vt = VT_UI4;
vtIndex.uintVal = 1;
VERIFY_SUCCEEDED(pEnumTables->Item(vtIndex, &pTable));
VERIFY_IS_NOT_NULL(pTable.p);
pTable.Release();
vtIndex.uintVal = 100;
VERIFY_FAILED(pEnumTables->Item(vtIndex, &pTable));
}
TEST_F(PixDiaTest, PixDebugCompileInfo) {
static const char source[] = R"(
SamplerState samp0 : register(s0);
Texture2DArray tex0 : register(t0);
float4 foo(Texture2DArray textures[], int idx, SamplerState samplerState, float3 uvw) {
return textures[NonUniformResourceIndex(idx)].Sample(samplerState, uvw);
}
[RootSignature( "DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)) " )]
float4 main(int index : INDEX, float3 uvw : TEXCOORD) : SV_Target {
Texture2DArray textures[] = {
tex0,
};
return foo(textures, index, samp0, uvw);
}
)";
CComPtr<IDxcBlob> pPart;
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IStream> pStream;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
const WCHAR *FlagList[] = {
L"/Zi", L"-Zpr", L"/Qembed_debug", L"/Fd",
L"F:\\my dir\\", L"-Fo", L"F:\\my dir\\file.dxc",
};
const WCHAR *DefineList[] = {
L"MY_SPECIAL_DEFINE",
L"MY_OTHER_SPECIAL_DEFINE=\"MY_STRING\"",
};
std::vector<LPCWSTR> args;
for (unsigned i = 0; i < _countof(FlagList); i++) {
args.push_back(FlagList[i]);
}
for (unsigned i = 0; i < _countof(DefineList); i++) {
args.push_back(L"/D");
args.push_back(DefineList[i]);
}
auto CompileAndGetDebugPart = [&args](dxc::DxcDllSupport &dllSupport,
const char *source,
const wchar_t *profile,
IDxcBlob **ppDebugPart) {
CComPtr<IDxcBlob> pContainer;
CComPtr<IDxcLibrary> pLib;
CComPtr<IDxcContainerReflection> pReflection;
UINT32 index;
VerifyCompileOK(dllSupport, source, profile, args, &pContainer);
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
VERIFY_SUCCEEDED(
dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(pReflection->Load(pContainer));
VERIFY_SUCCEEDED(
pReflection->FindFirstPartKind(hlsl::DFCC_ShaderDebugInfoDXIL, &index));
VERIFY_SUCCEEDED(pReflection->GetPartContent(index, ppDebugPart));
};
const wchar_t *profile = L"ps_6_0";
CompileAndGetDebugPart(m_dllSupport, source, profile, &pPart);
CComPtr<IStream> pNewProgramStream;
VERIFY_SUCCEEDED(
pLib->CreateStreamFromBlobReadOnly(pPart, &pNewProgramStream));
CComPtr<IDiaDataSource> pDiaDataSource;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaDataSource));
VERIFY_SUCCEEDED(pDiaDataSource->loadDataFromIStream(pNewProgramStream));
CComPtr<IDiaSession> pSession;
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pSession));
CComPtr<IDxcPixDxilDebugInfoFactory> factory;
VERIFY_SUCCEEDED(pSession->QueryInterface(IID_PPV_ARGS(&factory)));
CComPtr<IDxcPixCompilationInfo> compilationInfo;
VERIFY_SUCCEEDED(factory->NewDxcPixCompilationInfo(&compilationInfo));
CComBSTR arguments;
VERIFY_SUCCEEDED(compilationInfo->GetArguments(&arguments));
for (unsigned i = 0; i < _countof(FlagList); i++) {
VERIFY_IS_TRUE(nullptr != wcsstr(arguments, FlagList[i]));
}
CComBSTR macros;
VERIFY_SUCCEEDED(compilationInfo->GetMacroDefinitions(¯os));
for (unsigned i = 0; i < _countof(DefineList); i++) {
std::wstring MacroDef = std::wstring(L"-D") + DefineList[i];
VERIFY_IS_TRUE(nullptr != wcsstr(macros, MacroDef.c_str()));
}
CComBSTR entryPointFile;
VERIFY_SUCCEEDED(compilationInfo->GetEntryPointFile(&entryPointFile));
VERIFY_ARE_EQUAL(std::wstring(L"source.hlsl"), std::wstring(entryPointFile));
CComBSTR entryPointFunction;
VERIFY_SUCCEEDED(compilationInfo->GetEntryPoint(&entryPointFunction));
VERIFY_ARE_EQUAL(std::wstring(L"main"), std::wstring(entryPointFunction));
CComBSTR hlslTarget;
VERIFY_SUCCEEDED(compilationInfo->GetHlslTarget(&hlslTarget));
VERIFY_ARE_EQUAL(std::wstring(profile), std::wstring(hlslTarget));
}
void PixDiaTest::CompileAndRunAnnotationAndLoadDiaSource(
dxc::DxcDllSupport &dllSupport, const char *source, const wchar_t *profile,
IDxcIncludeHandler *includer, IDiaDataSource **ppDataSource,
std::vector<const wchar_t *> extraArgs) {
CComPtr<IDxcBlob> pDebugContent;
CComPtr<IStream> pStream;
CComPtr<IDiaDataSource> pDiaSource;
CComPtr<IDxcLibrary> pLib;
VERIFY_SUCCEEDED(dllSupport.CreateInstance(CLSID_DxcLibrary, &pLib));
CompileAndRunAnnotationAndGetDebugPart(dllSupport, source, profile, includer,
&pDebugContent, extraArgs);
VERIFY_SUCCEEDED(pLib->CreateStreamFromBlobReadOnly(pDebugContent, &pStream));
VERIFY_SUCCEEDED(
dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &pDiaSource));
VERIFY_SUCCEEDED(pDiaSource->loadDataFromIStream(pStream));
if (ppDataSource) {
*ppDataSource = pDiaSource.Detach();
}
}
TEST_F(PixDiaTest, PixTypeManager_InheritancePointerStruct) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
struct Base
{
float floatValue;
};
struct Derived : Base
{
int intValue;
};
RaytracingAccelerationStructure Scene : register(t0, space0);
[shader("raygeneration")]
void main()
{
RayDesc ray;
ray.Origin = float3(0,0,0);
ray.Direction = float3(0,0,1);
// Set TMin to a non-zero small value to avoid aliasing issues due to floating - point errors.
// TMin should be kept small to prevent missing geometry at close contact areas.
ray.TMin = 0.001;
ray.TMax = 10000.0;
Derived payload;
payload.floatValue = 1;
payload.intValue = 2;
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);}
)";
CComPtr<IDiaDataSource> pDiaDataSource;
CComPtr<IDiaSession> pDiaSession;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"lib_6_6",
nullptr, &pDiaDataSource);
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pDiaSession));
}
TEST_F(PixDiaTest, PixTypeManager_MatricesInBase) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
struct Base
{
float4x4 mat;
};
typedef Base BaseTypedef;
struct Derived : BaseTypedef
{
int intValue;
};
RaytracingAccelerationStructure Scene : register(t0, space0);
[shader("raygeneration")]
void main()
{
RayDesc ray;
ray.Origin = float3(0,0,0);
ray.Direction = float3(0,0,1);
// Set TMin to a non-zero small value to avoid aliasing issues due to floating - point errors.
// TMin should be kept small to prevent missing geometry at close contact areas.
ray.TMin = 0.001;
ray.TMax = 10000.0;
Derived payload;
payload.mat[0][0] = 1;
payload.intValue = 2;
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);}
)";
CComPtr<IDiaDataSource> pDiaDataSource;
CComPtr<IDiaSession> pDiaSession;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"lib_6_6",
nullptr, &pDiaDataSource);
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pDiaSession));
}
TEST_F(PixDiaTest, PixTypeManager_SamplersAndResources) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
static const SamplerState SamplerRef = SamplerDescriptorHeap[1];
Texture3D<uint4> Tex3DTemplated ;
Texture3D Tex3d ;
Texture2D Tex2D ;
Texture2D<uint> Tex2DTemplated ;
StructuredBuffer<float4> StructBuf ;
Texture2DArray Tex2DArray ;
Buffer<float4> Buff ;
static const struct
{
float AFloat;
SamplerState Samp1;
Texture3D<uint4> Tex1;
Texture3D Tex2;
Texture2D Tex3;
Texture2D<uint> Tex4;
StructuredBuffer<float4> Buff1;
Texture2DArray Tex5;
Buffer<float4> Buff2;
float AnotherFloat;
} View = {
1,
SamplerRef,
Tex3DTemplated,
Tex3d,
Tex2D,
Tex2DTemplated,
StructBuf,
Tex2DArray,
Buff,
2
};
struct Payload
{
int intValue;
};
RaytracingAccelerationStructure Scene : register(t0, space0);
[shader("raygeneration")]
void main()
{
RayDesc ray;
ray.Origin = float3(0,0,0);
ray.Direction = float3(0,0,1);
ray.TMin = 0.001;
ray.TMax = 10000.0;
Payload payload;
payload.intValue = View.AFloat;
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);}
)";
CComPtr<IDiaDataSource> pDiaDataSource;
CComPtr<IDiaSession> pDiaSession;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"lib_6_6",
nullptr, &pDiaDataSource);
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pDiaSession));
}
TEST_F(PixDiaTest, PixTypeManager_XBoxDiaAssert) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
struct VSOut
{
float4 vPosition : SV_POSITION;
float4 vLightAndFog : COLOR0_center;
float4 vTexCoords : TEXCOORD1;
};
struct HSPatchData
{
float edges[3] : SV_TessFactor;
float inside : SV_InsideTessFactor;
};
HSPatchData HSPatchFunc(const InputPatch<VSOut, 3> tri)
{
float dist = (tri[0].vPosition.w + tri[1].vPosition.w + tri[2].vPosition.w) / 3;
float tf = max(1, dist / 100.f);
HSPatchData pd;
pd.edges[0] = pd.edges[1] = pd.edges[2] = tf;
pd.inside = tf;
return pd;
}
[domain("tri")]
[partitioning("fractional_odd")]
[outputtopology("triangle_cw")]
[patchconstantfunc("HSPatchFunc")]
[outputcontrolpoints(3)]
[RootSignature("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), " "DescriptorTable(SRV(t0, numDescriptors=2), visibility=SHADER_VISIBILITY_ALL)," "DescriptorTable(Sampler(s0, numDescriptors=2), visibility=SHADER_VISIBILITY_PIXEL)," "DescriptorTable(CBV(b0, numDescriptors=1), visibility=SHADER_VISIBILITY_ALL)," "DescriptorTable(CBV(b1, numDescriptors=1), visibility=SHADER_VISIBILITY_ALL)," "DescriptorTable(CBV(b2, numDescriptors=1), visibility=SHADER_VISIBILITY_ALL)," "DescriptorTable(SRV(t3, numDescriptors=1), visibility=SHADER_VISIBILITY_ALL)," "DescriptorTable(UAV(u9, numDescriptors=2), visibility=SHADER_VISIBILITY_ALL),")]
VSOut main( const uint id : SV_OutputControlPointID,
const InputPatch< VSOut, 3 > triIn )
{
return triIn[id];
}
)";
CComPtr<IDiaDataSource> pDiaDataSource;
CComPtr<IDiaSession> pDiaSession;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"hs_6_0",
nullptr, &pDiaDataSource);
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pDiaSession));
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_InstructionOffsets) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl =
R"(RaytracingAccelerationStructure Scene : register(t0, space0);
RWTexture2D<float4> RenderTarget : register(u0);
struct SceneConstantBuffer
{
float4x4 projectionToWorld;
float4 cameraPosition;
float4 lightPosition;
float4 lightAmbientColor;
float4 lightDiffuseColor;
};
ConstantBuffer<SceneConstantBuffer> g_sceneCB : register(b0);
struct RayPayload
{
float4 color;
};
inline void GenerateCameraRay(uint2 index, out float3 origin, out float3 direction)
{
float2 xy = index + 0.5f; // center in the middle of the pixel.
float2 screenPos = xy;// / DispatchRaysDimensions().xy * 2.0 - 1.0;
// Invert Y for DirectX-style coordinates.
screenPos.y = -screenPos.y;
// Unproject the pixel coordinate into a ray.
float4 world = /*mul(*/float4(screenPos, 0, 1)/*, g_sceneCB.projectionToWorld)*/;
//world.xyz /= world.w;
origin = world.xyz; //g_sceneCB.cameraPosition.xyz;
direction = float3(1,0,0);//normalize(world.xyz - origin);
}
void RaygenCommon()
{
float3 rayDir;
float3 origin;
// Generate a ray for a camera pixel corresponding to an index from the dispatched 2D grid.
GenerateCameraRay(DispatchRaysIndex().xy, origin, rayDir);
// Trace the ray.
// Set the ray's extents.
RayDesc ray;
ray.Origin = origin;
ray.Direction = rayDir;
// Set TMin to a non-zero small value to avoid aliasing issues due to floating - point errors.
// TMin should be kept small to prevent missing geometry at close contact areas.
ray.TMin = 0.001;
ray.TMax = 10000.0;
RayPayload payload = { float4(0, 0, 0, 0) };
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);
// Write the raytraced color to the output texture.
// RenderTarget[DispatchRaysIndex().xy] = payload.color;
}
[shader("raygeneration")]
void Raygen()
{
RaygenCommon();
}
typedef BuiltInTriangleIntersectionAttributes MyAttributes;
namespace ANameSpace
{
namespace AContainedNamespace
{
float4 RoundaboutWayToReturnAmbientColor()
{
return g_sceneCB.lightAmbientColor;
}
}
}
[shader("closesthit")]
void InnerClosestHitShader(inout RayPayload payload, in MyAttributes attr)
{
payload.color = ANameSpace::AContainedNamespace::RoundaboutWayToReturnAmbientColor();
}
[shader("miss")]
void MyMissShader(inout RayPayload payload)
{
payload.color = float4(1, 0, 0, 0);
})";
auto lines = SplitAndPreserveEmptyLines(std::string(hlsl), '\n');
DWORD countOfSourceLines = static_cast<DWORD>(lines.size());
CComPtr<IDiaDataSource> pDiaDataSource;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"lib_6_6",
nullptr, &pDiaDataSource);
CComPtr<IDiaSession> session;
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&session));
CComPtr<IDxcPixDxilDebugInfoFactory> Factory;
VERIFY_SUCCEEDED(session->QueryInterface(IID_PPV_ARGS(&Factory)));
CComPtr<IDxcPixDxilDebugInfo> dxilDebugger;
VERIFY_SUCCEEDED(Factory->NewDxcPixDxilDebugInfo(&dxilDebugger));
// Quick crash test for wrong filename:
CComPtr<IDxcPixDxilInstructionOffsets> garbageOffsets;
dxilDebugger->InstructionOffsetsFromSourceLocation(L"garbage", 0, 0,
&garbageOffsets);
// Since the API offers both source-from-instruction and
// instruction-from-source, we'll compare them against each other:
for (size_t line = 0; line < lines.size(); ++line) {
auto lineNumber = static_cast<DWORD>(line);
constexpr DWORD sourceLocationReaderOnlySupportsColumnZero = 0;
CComPtr<IDxcPixDxilInstructionOffsets> offsets;
dxilDebugger->InstructionOffsetsFromSourceLocation(
defaultFilename, lineNumber, sourceLocationReaderOnlySupportsColumnZero,
&offsets);
auto offsetCount = offsets->GetCount();
for (DWORD offsetOrdinal = 0; offsetOrdinal < offsetCount;
++offsetOrdinal) {
DWORD instructionOffsetFromSource =
offsets->GetOffsetByIndex(offsetOrdinal);
CComPtr<IDxcPixDxilSourceLocations> sourceLocations;
VERIFY_SUCCEEDED(dxilDebugger->SourceLocationsFromInstructionOffset(
instructionOffsetFromSource, &sourceLocations));
auto count = sourceLocations->GetCount();
for (DWORD sourceLocationOrdinal = 0; sourceLocationOrdinal < count;
++sourceLocationOrdinal) {
DWORD lineNumber =
sourceLocations->GetLineNumberByIndex(sourceLocationOrdinal);
DWORD column = sourceLocations->GetColumnByIndex(sourceLocationOrdinal);
CComBSTR filename;
VERIFY_SUCCEEDED(sourceLocations->GetFileNameByIndex(
sourceLocationOrdinal, &filename));
VERIFY_IS_TRUE(lineNumber < countOfSourceLines);
constexpr DWORD lineNumbersAndColumnsStartAtOne = 1;
VERIFY_IS_TRUE(
column - lineNumbersAndColumnsStartAtOne <=
static_cast<DWORD>(
lines.at(lineNumber - lineNumbersAndColumnsStartAtOne).size()));
VERIFY_IS_TRUE(0 == wcscmp(filename, defaultFilename));
}
}
}
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_InstructionOffsetsInClassMethods) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWByteAddressBuffer RawUAV: register(u1);
class AClass
{
float Saturate(float f) // StartClassMethod
{
float l = RawUAV.Load(0);
return saturate(f * l);
} //EndClassMethod
};
[numthreads(1, 1, 1)]
void main()
{
uint orig;
AClass aClass;
float i = orig;
float f = aClass.Saturate(i);
uint fi = (uint)f;
RawUAV.InterlockedAdd(0, 42, fi);
}
)";
auto lines = SplitAndPreserveEmptyLines(std::string(hlsl), '\n');
CComPtr<IDiaDataSource> pDiaDataSource;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"cs_6_6",
nullptr, &pDiaDataSource);
CComPtr<IDiaSession> session;
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&session));
CComPtr<IDxcPixDxilDebugInfoFactory> Factory;
VERIFY_SUCCEEDED(session->QueryInterface(IID_PPV_ARGS(&Factory)));
CComPtr<IDxcPixDxilDebugInfo> dxilDebugger;
VERIFY_SUCCEEDED(Factory->NewDxcPixDxilDebugInfo(&dxilDebugger));
size_t lineAfterMethod = 0;
size_t lineBeforeMethod = static_cast<size_t>(-1);
for (size_t line = 0; line < lines.size(); ++line) {
if (lines[line].find("StartClassMethod") != std::string::npos)
lineBeforeMethod = line;
if (lines[line].find("EndClassMethod") != std::string::npos)
lineAfterMethod = line;
}
VERIFY_IS_TRUE(lineAfterMethod > lineBeforeMethod);
// For each source line, get the instruction numbers.
// For each instruction number, map back to source line.
// Some of them better be in the class method
bool foundClassMethodLines = false;
for (size_t line = 0; line < lines.size(); ++line) {
auto lineNumber = static_cast<DWORD>(line);
constexpr DWORD sourceLocationReaderOnlySupportsColumnZero = 0;
CComPtr<IDxcPixDxilInstructionOffsets> offsets;
dxilDebugger->InstructionOffsetsFromSourceLocation(
defaultFilename, lineNumber, sourceLocationReaderOnlySupportsColumnZero,
&offsets);
auto offsetCount = offsets->GetCount();
for (DWORD offsetOrdinal = 0; offsetOrdinal < offsetCount;
++offsetOrdinal) {
DWORD instructionOffsetFromSource =
offsets->GetOffsetByIndex(offsetOrdinal);
CComPtr<IDxcPixDxilSourceLocations> sourceLocations;
VERIFY_SUCCEEDED(dxilDebugger->SourceLocationsFromInstructionOffset(
instructionOffsetFromSource, &sourceLocations));
auto count = sourceLocations->GetCount();
for (DWORD sourceLocationOrdinal = 0; sourceLocationOrdinal < count;
++sourceLocationOrdinal) {
DWORD lineNumber =
sourceLocations->GetLineNumberByIndex(sourceLocationOrdinal);
if (lineNumber >= lineBeforeMethod && lineNumber <= lineAfterMethod) {
foundClassMethodLines = true;
}
}
}
}
VERIFY_IS_TRUE(foundClassMethodLines);
}
TEST_F(PixDiaTest, PixTypeManager_InheritancePointerTypedef) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
struct Base
{
float floatValue;
};
typedef Base BaseTypedef;
struct Derived : BaseTypedef
{
int intValue;
};
RaytracingAccelerationStructure Scene : register(t0, space0);
[shader("raygeneration")]
void main()
{
RayDesc ray;
ray.Origin = float3(0,0,0);
ray.Direction = float3(0,0,1);
// Set TMin to a non-zero small value to avoid aliasing issues due to floating - point errors.
// TMin should be kept small to prevent missing geometry at close contact areas.
ray.TMin = 0.001;
ray.TMax = 10000.0;
Derived payload;
payload.floatValue = 1;
payload.intValue = 2;
TraceRay(Scene, RAY_FLAG_CULL_BACK_FACING_TRIANGLES, ~0, 0, 1, 0, ray, payload);}
)";
CComPtr<IDiaDataSource> pDiaDataSource;
CComPtr<IDiaSession> pDiaSession;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"lib_6_6",
nullptr, &pDiaDataSource);
VERIFY_SUCCEEDED(pDiaDataSource->openSession(&pDiaSession));
}
TEST_F(PixDiaTest, SymbolManager_Embedded2DArray) {
const char *code = R"x(
struct EmbeddedStruct
{
uint32_t TwoDArray[2][2];
};
struct smallPayload
{
uint32_t OneInt;
EmbeddedStruct embeddedStruct;
uint64_t bigOne;
};
[numthreads(1, 1, 1)]
void ASMain()
{
smallPayload p;
p.OneInt = -137;
p.embeddedStruct.TwoDArray[0][0] = 252;
p.embeddedStruct.TwoDArray[0][1] = 253;
p.embeddedStruct.TwoDArray[1][0] = 254;
p.embeddedStruct.TwoDArray[1][1] = 255;
p.bigOne = 123456789;
DispatchMesh(2, 1, 1, p);
}
)x";
auto compiled = Compile(m_dllSupport, code, L"as_6_5", {}, L"ASMain");
auto debugPart = GetDebugPart(
m_dllSupport,
WrapInNewContainer(m_dllSupport,
RunAnnotationPasses(m_dllSupport, compiled).blob));
CComPtr<IDxcLibrary> library;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
CComPtr<IStream> programStream;
VERIFY_SUCCEEDED(
library->CreateStreamFromBlobReadOnly(debugPart, &programStream));
CComPtr<IDiaDataSource> diaDataSource;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcDiaDataSource, &diaDataSource));
VERIFY_SUCCEEDED(diaDataSource->loadDataFromIStream(programStream));
CComPtr<IDiaSession> session;
VERIFY_SUCCEEDED(diaDataSource->openSession(&session));
CComPtr<IDxcPixDxilDebugInfoFactory> Factory;
VERIFY_SUCCEEDED(session->QueryInterface(&Factory));
CComPtr<IDxcPixDxilDebugInfo> dxilDebugger;
VERIFY_SUCCEEDED(Factory->NewDxcPixDxilDebugInfo(&dxilDebugger));
auto lines = SplitAndPreserveEmptyLines(code, '\n');
auto DispatchMeshLineFind =
std::find_if(lines.begin(), lines.end(), [](std::string const &line) {
return line.find("DispatchMesh") != std::string::npos;
});
auto DispatchMeshLine =
static_cast<DWORD>(DispatchMeshLineFind - lines.begin()) + 2;
CComPtr<IDxcPixDxilInstructionOffsets> instructionOffsets;
VERIFY_SUCCEEDED(dxilDebugger->InstructionOffsetsFromSourceLocation(
L"source.hlsl", DispatchMeshLine, 0, &instructionOffsets));
VERIFY_IS_TRUE(instructionOffsets->GetCount() > 0);
DWORD InstructionOrdinal = instructionOffsets->GetOffsetByIndex(0);
CComPtr<IDxcPixDxilLiveVariables> liveVariables;
VERIFY_SUCCEEDED(
dxilDebugger->GetLiveVariablesAt(InstructionOrdinal, &liveVariables));
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(0, &variable));
CComBSTR name;
variable->GetName(&name);
VERIFY_ARE_EQUAL_WSTR(name, L"p");
CComPtr<IDxcPixType> type;
VERIFY_SUCCEEDED(variable->GetType(&type));
CComPtr<IDxcPixStructType> structType;
VERIFY_SUCCEEDED(type->QueryInterface(IID_PPV_ARGS(&structType)));
auto ValidateStructMember = [&structType](DWORD index, const wchar_t *name,
uint64_t offset) {
CComPtr<IDxcPixStructField> member;
VERIFY_SUCCEEDED(structType->GetFieldByIndex(index, &member));
CComBSTR actualName;
VERIFY_SUCCEEDED(member->GetName(&actualName));
VERIFY_ARE_EQUAL_WSTR(actualName, name);
DWORD actualOffset = 0;
VERIFY_SUCCEEDED(member->GetOffsetInBits(&actualOffset));
VERIFY_ARE_EQUAL(actualOffset, offset);
};
ValidateStructMember(0, L"OneInt", 0);
ValidateStructMember(1, L"embeddedStruct", 4 * 8);
ValidateStructMember(2, L"bigOne", 24 * 8);
}
TEST_F(PixDiaTest,
DxcPixDxilDebugInfo_GlobalBackedGlobalStaticEmbeddedArrays_NoDbgValue) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
struct GlobalStruct
{
int IntArray[2];
float FloatArray[2];
};
static GlobalStruct globalStruct;
[noinline]
void fn()
{
float Accumulator;
globalStruct.IntArray[0] = floatRWUAV[0];
globalStruct.IntArray[1] = floatRWUAV[1];
globalStruct.FloatArray[0] = floatRWUAV[4];
globalStruct.FloatArray[1] = floatRWUAV[5];
Accumulator = 0;
uint killSwitch = 0;
[loop] // do not unroll this
while (true)
{
Accumulator += globalStruct.FloatArray[killSwitch % 2];
if (killSwitch++ == 4) break;
}
floatRWUAV[0] = Accumulator + globalStruct.IntArray[0] + globalStruct.IntArray[1];
}
[shader("compute")]
[numthreads(1, 1, 1)]
void main()
{
fn();
}
)";
// The above HLSL should generate a module that represents the FloatArray
// member as a global, and the IntArray as an alloca. Since only embedded
// arrays are present in GlobalStruct, no dbg.value will be present for
// globalStruct. We expect the value-to-declare pass to generate its own
// dbg.value for stores into FloatArray. We will observe those dbg.value here
// via the PIX-specific debug data API.
std::vector<VariableComponentInfo> Expected;
Expected.push_back({L"global.globalStruct.IntArray[0]", L"int"});
Expected.push_back({L"global.globalStruct.IntArray[1]", L"int"});
Expected.push_back({L"global.globalStruct.FloatArray[0]", L"float"});
Expected.push_back({L"global.globalStruct.FloatArray[1]", L"float"});
TestGlobalStaticCase(hlsl, L"lib_6_6", "float Accumulator", Expected);
}
TEST_F(
PixDiaTest,
DxcPixDxilDebugInfo_GlobalBackedGlobalStaticEmbeddedArrays_WithDbgValue) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
struct GlobalStruct
{
float Accumulator;
int IntArray[2];
float FloatArray[2];
};
static GlobalStruct globalStruct;
[numthreads(1, 1, 1)]
void main()
{
globalStruct.IntArray[0] = floatRWUAV[0];
globalStruct.IntArray[1] = floatRWUAV[1];
globalStruct.FloatArray[0] = floatRWUAV[4];
globalStruct.FloatArray[1] = floatRWUAV[5];
globalStruct.Accumulator = 0;
uint killSwitch = 0;
[loop] // do not unroll this
while (true)
{
globalStruct.Accumulator += globalStruct.FloatArray[killSwitch % 2];
if (killSwitch++ == 4) break;
}
floatRWUAV[0] = globalStruct.Accumulator + globalStruct.IntArray[0] + globalStruct.IntArray[1];
}
)";
// The above HLSL should generate a module that represents the FloatArray
// member as a global, and the IntArray as an alloca. The presence of
// Accumulator in the GlobalStruct will force a dbg.value to be present for
// globalStruct. We expect the value-to-declare pass to find that dbg.value.
std::vector<VariableComponentInfo> Expected;
Expected.push_back({L"global.globalStruct.Accumulator", L"float"});
Expected.push_back({L"global.globalStruct.IntArray[0]", L"int"});
Expected.push_back({L"global.globalStruct.IntArray[1]", L"int"});
Expected.push_back({L"global.globalStruct.FloatArray[0]", L"float"});
Expected.push_back({L"global.globalStruct.FloatArray[1]", L"float"});
TestGlobalStaticCase(hlsl, L"cs_6_6", "float Accumulator", Expected);
}
TEST_F(
PixDiaTest,
DxcPixDxilDebugInfo_GlobalBackedGlobalStaticEmbeddedArrays_ArrayInValues) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
struct GlobalStruct
{
float Accumulator;
int IntArray[2];
float FloatArray[2];
};
static GlobalStruct globalStruct;
[shader("compute")]
[numthreads(1, 1, 1)]
void main()
{
globalStruct.IntArray[0] =0;
globalStruct.IntArray[1] =1;
globalStruct.FloatArray[0] = floatRWUAV[4];
globalStruct.FloatArray[1] = floatRWUAV[5];
globalStruct.Accumulator = 0;
uint killSwitch = 0;
[loop] // do not unroll this
while (true)
{
globalStruct.Accumulator += globalStruct.FloatArray[killSwitch % 2];
if (killSwitch++ == 4) break;
}
floatRWUAV[0] = globalStruct.Accumulator + globalStruct.IntArray[0] + globalStruct.IntArray[1];
}
)";
// The above HLSL should generate a module that represents the FloatArray
// member as a global, and the IntArray as individual values.
std::vector<VariableComponentInfo> Expected;
Expected.push_back({L"global.globalStruct.Accumulator", L"float"});
Expected.push_back({L"global.globalStruct.IntArray[0]", L"int"});
Expected.push_back({L"global.globalStruct.IntArray[1]", L"int"});
Expected.push_back({L"global.globalStruct.FloatArray[0]", L"float"});
Expected.push_back({L"global.globalStruct.FloatArray[1]", L"float"});
TestGlobalStaticCase(hlsl, L"lib_6_6", "float Accumulator", Expected);
}
int CountLiveGlobals(IDxcPixDxilLiveVariables *liveVariables) {
int globalCount = 0;
DWORD varCount;
VERIFY_SUCCEEDED(liveVariables->GetCount(&varCount));
for (DWORD i = 0; i < varCount; ++i) {
CComPtr<IDxcPixVariable> var;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &var));
CComBSTR name;
VERIFY_SUCCEEDED(var->GetName(&name));
if (wcsstr(name, L"global.") != nullptr)
globalCount++;
}
return globalCount;
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_DuplicateGlobals) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char *hlsl = R"(
static float global = 1.0;
struct RayPayload
{
float4 color;
};
typedef BuiltInTriangleIntersectionAttributes MyAttributes;
[shader("closesthit")]
void InnerClosestHitShader(inout RayPayload payload, in MyAttributes attr)
{
payload.color = float4(global, 0, 0, 0); // CHLine
}
[shader("miss")]
void MyMissShader(inout RayPayload payload)
{
payload.color = float4(0, 1, 0, 0); // MSLine
})";
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"lib_6_6").debugInfo;
auto CHVars = GetLiveVariablesAt(hlsl, "CHLine", dxilDebugger);
VERIFY_ARE_EQUAL(1, CountLiveGlobals(CHVars));
auto MSVars = GetLiveVariablesAt(hlsl, "MSLine", dxilDebugger);
VERIFY_ARE_EQUAL(0, CountLiveGlobals(MSVars));
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_StructInheritance) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
struct AStruct
{
float f;
int i[2];
};
struct ADerivedStruct : AStruct
{
bool b[2];
};
int AFunction(ADerivedStruct theStruct)
{
return theStruct.i[0] + theStruct.i[1] + theStruct.f + (theStruct.b[0] ? 1 : 0) + (theStruct.b[1] ? 2 : 3); // InterestingLine
}
[numthreads(1, 1, 1)]
void main()
{
ADerivedStruct aStruct;
aStruct.f = floatRWUAV[1];
aStruct.i[0] = floatRWUAV[2];
aStruct.i[1] = floatRWUAV[3];
aStruct.b[0] = floatRWUAV[4] != 0.0;
aStruct.b[1] = floatRWUAV[5] != 0.0;
floatRWUAV[0] = AFunction(aStruct);
}
)";
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"cs_6_6").debugInfo;
auto liveVariables =
GetLiveVariablesAt(hlsl, "InterestingLine", dxilDebugger);
DWORD count;
VERIFY_SUCCEEDED(liveVariables->GetCount(&count));
bool FoundTheStruct = false;
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &variable));
CComBSTR name;
variable->GetName(&name);
if (0 == wcscmp(name, L"theStruct")) {
FoundTheStruct = true;
CComPtr<IDxcPixDxilStorage> storage;
VERIFY_SUCCEEDED(variable->GetStorage(&storage));
std::vector<VariableComponentInfo> ActualVariableComponents;
VERIFY_IS_TRUE(AddStorageComponents(storage, L"theStruct",
ActualVariableComponents));
std::vector<VariableComponentInfo> Expected;
Expected.push_back({L"theStruct.b[0]", L"bool"});
Expected.push_back({L"theStruct.b[1]", L"bool"});
Expected.push_back({L"theStruct.f", L"float"});
Expected.push_back({L"theStruct.i[0]", L"int"});
Expected.push_back({L"theStruct.i[1]", L"int"});
VERIFY_IS_TRUE(ContainedBy(ActualVariableComponents, Expected));
break;
}
}
VERIFY_IS_TRUE(FoundTheStruct);
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_StructContainedResource) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
Texture2D srv2DTexture : register(t0, space1);
struct AStruct
{
float f;
Texture2D tex;
};
float4 AFunction(AStruct theStruct)
{
return theStruct.tex.Load(int3(0, 0, 0)) + theStruct.f.xxxx; // InterestingLine
}
[numthreads(1, 1, 1)]
void main()
{
AStruct aStruct;
aStruct.f = floatRWUAV[1];
aStruct.tex = srv2DTexture;
floatRWUAV[0] = AFunction(aStruct).x;
}
)";
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"cs_6_6").debugInfo;
auto liveVariables =
GetLiveVariablesAt(hlsl, "InterestingLine", dxilDebugger);
DWORD count;
VERIFY_SUCCEEDED(liveVariables->GetCount(&count));
bool FoundTheStruct = false;
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &variable));
CComBSTR name;
variable->GetName(&name);
if (0 == wcscmp(name, L"theStruct")) {
FoundTheStruct = true;
CComPtr<IDxcPixDxilStorage> storage;
VERIFY_SUCCEEDED(variable->GetStorage(&storage));
std::vector<VariableComponentInfo> ActualVariableComponents;
VERIFY_IS_TRUE(AddStorageComponents(storage, L"theStruct",
ActualVariableComponents));
std::vector<VariableComponentInfo> Expected;
Expected.push_back({L"theStruct.f", L"float"});
VERIFY_IS_TRUE(ContainedBy(ActualVariableComponents, Expected));
break;
}
}
VERIFY_IS_TRUE(FoundTheStruct);
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_StructStaticInit) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
struct AStruct
{
float f;
static AStruct Init(float fi)
{
AStruct ret;
ret.f = fi;
for(int i =0; i < 4; ++i)
{
ret.f += floatRWUAV[i+2];
}
return ret;
}
};
[numthreads(1, 1, 1)]
void main()
{
AStruct aStruct = AStruct::Init(floatRWUAV[1]);
floatRWUAV[0] = aStruct.f; // InterestingLine
}
)";
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"cs_6_6").debugInfo;
auto liveVariables =
GetLiveVariablesAt(hlsl, "InterestingLine", dxilDebugger);
DWORD count;
VERIFY_SUCCEEDED(liveVariables->GetCount(&count));
bool FoundTheStruct = false;
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &variable));
CComBSTR name;
variable->GetName(&name);
if (0 == wcscmp(name, L"aStruct")) {
FoundTheStruct = true;
CComPtr<IDxcPixDxilStorage> storage;
VERIFY_SUCCEEDED(variable->GetStorage(&storage));
std::vector<VariableComponentInfo> ActualVariableComponents;
VERIFY_IS_TRUE(
AddStorageComponents(storage, L"aStruct", ActualVariableComponents));
std::vector<VariableComponentInfo> Expected;
Expected.push_back({L"aStruct.f", L"float"});
VERIFY_IS_TRUE(ContainedBy(ActualVariableComponents, Expected));
break;
}
}
VERIFY_IS_TRUE(FoundTheStruct);
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_StructMemberFnFirst) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
struct AStruct
{
void Init(float fi);
float f;
};
void AStruct::Init(float fi)
{
AStruct ret;
f = fi;
for(int i =0; i < 4; ++i)
{
f += floatRWUAV[i+2];
}
}
[numthreads(1, 1, 1)]
void main()
{
AStruct aStruct;
aStruct.Init(floatRWUAV[1]);
floatRWUAV[0] = aStruct.f; // InterestingLine
}
)";
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"cs_6_6").debugInfo;
auto liveVariables =
GetLiveVariablesAt(hlsl, "InterestingLine", dxilDebugger);
DWORD count;
VERIFY_SUCCEEDED(liveVariables->GetCount(&count));
bool FoundTheStruct = false;
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &variable));
CComBSTR name;
variable->GetName(&name);
if (0 == wcscmp(name, L"aStruct")) {
FoundTheStruct = true;
CComPtr<IDxcPixDxilStorage> storage;
VERIFY_SUCCEEDED(variable->GetStorage(&storage));
std::vector<VariableComponentInfo> ActualVariableComponents;
VERIFY_IS_TRUE(
AddStorageComponents(storage, L"aStruct", ActualVariableComponents));
std::vector<VariableComponentInfo> Expected;
Expected.push_back({L"aStruct.f", L"float"});
VERIFY_IS_TRUE(ContainedBy(ActualVariableComponents, Expected));
break;
}
}
VERIFY_IS_TRUE(FoundTheStruct);
}
void PixDiaTest::TestUnnamedTypeCase(const char *hlsl,
const wchar_t *expectedTypeName) {
if (m_ver.SkipDxilVersion(1, 2))
return;
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"cs_6_0").debugInfo;
auto liveVariables =
GetLiveVariablesAt(hlsl, "InterestingLine", dxilDebugger);
DWORD count;
VERIFY_SUCCEEDED(liveVariables->GetCount(&count));
bool FoundTheVariable = false;
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &variable));
CComBSTR name;
variable->GetName(&name);
if (0 == wcscmp(name, L"glbl")) {
FoundTheVariable = true;
CComPtr<IDxcPixType> type;
VERIFY_SUCCEEDED(variable->GetType(&type));
CComBSTR typeName;
VERIFY_SUCCEEDED(type->GetName(&typeName));
VERIFY_ARE_EQUAL(typeName, expectedTypeName);
break;
}
}
VERIFY_IS_TRUE(FoundTheVariable);
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_UnnamedConstStruct) {
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
const struct
{
float fg;
RWStructuredBuffer<float> buf;
} glbl = {42.f, floatRWUAV};
float f = glbl.fg + glbl.buf[1]; // InterestingLine
floatRWUAV[0] = f;
}
)";
TestUnnamedTypeCase(hlsl, L"const <unnamed>");
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_UnnamedStruct) {
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
struct
{
float fg;
RWStructuredBuffer<float> buf;
} glbl = {42.f, floatRWUAV};
glbl.fg = 41.f;
float f = glbl.fg + glbl.buf[1]; // InterestingLine
floatRWUAV[0] = f;
}
)";
TestUnnamedTypeCase(hlsl, L"<unnamed>");
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_UnnamedArray) {
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
struct
{
float fg;
RWStructuredBuffer<float> buf;
} glbl[2] = {{42.f, floatRWUAV},{43.f, floatRWUAV}};
float f = glbl[0].fg + glbl[1].buf[1]; // InterestingLine
floatRWUAV[0] = f;
}
)";
TestUnnamedTypeCase(hlsl, L"<unnamed>[]");
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_UnnamedField) {
const char *hlsl = R"(
RWStructuredBuffer<float> floatRWUAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
struct
{
struct {
float fg;
RWStructuredBuffer<float> buf;
} contained;
} glbl = { {42.f, floatRWUAV} };
float f = glbl.contained.fg + glbl.contained.buf[1]; // InterestingLine
floatRWUAV[0] = f;
}
)";
if (m_ver.SkipDxilVersion(1, 2))
return;
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"cs_6_0").debugInfo;
auto liveVariables =
GetLiveVariablesAt(hlsl, "InterestingLine", dxilDebugger);
DWORD count;
VERIFY_SUCCEEDED(liveVariables->GetCount(&count));
bool FoundTheVariable = false;
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(liveVariables->GetVariableByIndex(i, &variable));
CComBSTR name;
variable->GetName(&name);
if (0 == wcscmp(name, L"glbl")) {
CComPtr<IDxcPixType> type;
VERIFY_SUCCEEDED(variable->GetType(&type));
CComPtr<IDxcPixStructType> structType;
VERIFY_SUCCEEDED(type->QueryInterface(IID_PPV_ARGS(&structType)));
DWORD fieldCount = 0;
VERIFY_SUCCEEDED(structType->GetNumFields(&fieldCount));
VERIFY_ARE_EQUAL(fieldCount, 1u);
// Just a crash test:
CComPtr<IDxcPixStructField> structField;
structType->GetFieldByName(L"", &structField);
VERIFY_SUCCEEDED(structType->GetFieldByIndex(0, &structField));
FoundTheVariable = true;
CComPtr<IDxcPixType> fieldType;
VERIFY_SUCCEEDED(structField->GetType(&fieldType));
CComBSTR typeName;
VERIFY_SUCCEEDED(fieldType->GetName(&typeName));
VERIFY_ARE_EQUAL(typeName, L"<unnamed>");
break;
}
}
VERIFY_IS_TRUE(FoundTheVariable);
}
class DxcIncludeHandlerForInjectedSourcesForPix : public IDxcIncludeHandler {
private:
DXC_MICROCOM_REF_FIELD(m_dwRef)
std::vector<std::pair<std::wstring, std::string>> m_files;
PixDiaTest *m_pixTest;
public:
DXC_MICROCOM_ADDREF_RELEASE_IMPL(m_dwRef)
DxcIncludeHandlerForInjectedSourcesForPix(
PixDiaTest *pixTest,
std::vector<std::pair<std::wstring, std::string>> files)
: m_dwRef(0), m_files(files), m_pixTest(pixTest){};
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
void **ppvObject) override {
return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject);
}
HRESULT insertIncludeFile(LPCWSTR pFilename, IDxcBlobEncoding *pBlob,
UINT32 dataLen) {
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE LoadSource(LPCWSTR pFilename,
IDxcBlob **ppIncludeSource) override {
for (auto const &file : m_files) {
std::wstring prependedWithDotHack = L".\\" + file.first;
if (prependedWithDotHack == std::wstring(pFilename)) {
CComPtr<IDxcBlobEncoding> blob;
CreateBlobFromText(m_pixTest->m_dllSupport, file.second.c_str(), &blob);
*ppIncludeSource = blob.Detach();
return S_OK;
}
}
return E_FAIL;
}
};
void PixDiaTest::RunSubProgramsCase(const char *hlsl) {
CComPtr<DxcIncludeHandlerForInjectedSourcesForPix> pIncludeHandler =
new DxcIncludeHandlerForInjectedSourcesForPix(
this, {{L"..\\include1\\samefilename.h",
"float fn1(int c, float v) { for(int i = 0; i< c; ++ i) v += "
"sqrt(v); return v; } "},
{L"..\\include2\\samefilename.h",
R"(
float4 fn2( float3 f3, float d, bool sanitize = true )
{
if (sanitize)
{
f3 = any(isnan(f3) | isinf(f3)) ? 0 : clamp(f3, 0, 1034.f);
d = (isnan(d) | isinf(d)) ? 0 : clamp(d, 0, 1024.f);
}
if( d != 0 ) d = max( d, -1024.f);
return float4( f3, d );}
)"}});
auto dxilDebugger =
CompileAndCreateDxcDebug(hlsl, L"cs_6_0", pIncludeHandler).debugInfo;
struct SourceLocations {
CComBSTR Filename;
DWORD Column;
DWORD Line;
};
std::vector<SourceLocations> sourceLocations;
DWORD instructionOffset = 0;
CComPtr<IDxcPixDxilSourceLocations> DxcSourceLocations;
while (SUCCEEDED(dxilDebugger->SourceLocationsFromInstructionOffset(
instructionOffset++, &DxcSourceLocations))) {
auto count = DxcSourceLocations->GetCount();
for (DWORD i = 0; i < count; ++i) {
sourceLocations.push_back({});
DxcSourceLocations->GetFileNameByIndex(i,
&sourceLocations.back().Filename);
sourceLocations.back().Line = DxcSourceLocations->GetLineNumberByIndex(i);
sourceLocations.back().Column = DxcSourceLocations->GetColumnByIndex(i);
}
DxcSourceLocations = nullptr;
}
auto it = sourceLocations.begin();
VERIFY_IS_FALSE(it == sourceLocations.end());
const WCHAR *mainFileName = L"source.hlsl";
// The list of source locations should start with the containing file:
while (it != sourceLocations.end() && it->Filename == mainFileName)
it++;
VERIFY_IS_FALSE(it == sourceLocations.end());
// Then have a bunch of "../include2/samefilename.h"
VERIFY_ARE_EQUAL_WSTR(L"./../include2/samefilename.h", it->Filename);
while (it != sourceLocations.end() &&
it->Filename == L"./../include2/samefilename.h")
it++;
VERIFY_IS_FALSE(it == sourceLocations.end());
// Then some more main file:
VERIFY_ARE_EQUAL_WSTR(mainFileName, it->Filename);
while (it != sourceLocations.end() && it->Filename == mainFileName)
it++;
// And that should be the end:
VERIFY_IS_TRUE(it == sourceLocations.end());
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_SubPrograms) {
if (m_ver.SkipDxilVersion(1, 2))
return;
const char *hlsl = R"(
#include "../include1/samefilename.h"
namespace n1 {
#include "../include2/samefilename.h"
}
RWStructuredBuffer<float> floatRWUAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
float4 result = n1::fn2(
float3(floatRWUAV[0], floatRWUAV[1], floatRWUAV[2]),
floatRWUAV[3]);
floatRWUAV[0] = result.x;
floatRWUAV[1] = result.y;
floatRWUAV[2] = result.z;
floatRWUAV[3] = result.w;
}
)";
RunSubProgramsCase(hlsl);
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_QIOldFieldInterface) {
const char *hlsl = R"(
struct Struct
{
unsigned int first;
unsigned int second;
};
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
Struct s;
s.second = UAV[0];
UAV[16] = s.second; //STOP_HERE
}
)";
auto debugInfo = CompileAndCreateDxcDebug(hlsl, L"cs_6_5", nullptr).debugInfo;
auto live = GetLiveVariablesAt(hlsl, "STOP_HERE", debugInfo);
CComPtr<IDxcPixVariable> bf;
VERIFY_SUCCEEDED(live->GetVariableByName(L"s", &bf));
CComPtr<IDxcPixType> bfType;
VERIFY_SUCCEEDED(bf->GetType(&bfType));
CComPtr<IDxcPixStructType> bfStructType;
VERIFY_SUCCEEDED(bfType->QueryInterface(IID_PPV_ARGS(&bfStructType)));
CComPtr<IDxcPixStructField> field;
VERIFY_SUCCEEDED(bfStructType->GetFieldByIndex(1, &field));
CComPtr<IDxcPixStructField0> mike;
VERIFY_SUCCEEDED(field->QueryInterface(IID_PPV_ARGS(&mike)));
DWORD secondFieldOffset = 0;
VERIFY_SUCCEEDED(mike->GetOffsetInBits(&secondFieldOffset));
VERIFY_ARE_EQUAL(32u, secondFieldOffset);
}
void PixDiaTest::RunSizeAndOffsetTestCase(
const char *hlsl, std::array<DWORD, 4> const &memberOffsets,
std::array<DWORD, 4> const &memberSizes,
std::vector<const wchar_t *> extraArgs) {
if (m_ver.SkipDxilVersion(1, 5))
return;
auto debugInfo =
CompileAndCreateDxcDebug(hlsl, L"cs_6_5", nullptr, extraArgs).debugInfo;
auto live = GetLiveVariablesAt(hlsl, "STOP_HERE", debugInfo);
CComPtr<IDxcPixVariable> bf;
VERIFY_SUCCEEDED(live->GetVariableByName(L"bf", &bf));
CComPtr<IDxcPixType> bfType;
VERIFY_SUCCEEDED(bf->GetType(&bfType));
CComPtr<IDxcPixStructType> bfStructType;
VERIFY_SUCCEEDED(bfType->QueryInterface(IID_PPV_ARGS(&bfStructType)));
for (size_t i = 0; i < memberOffsets.size(); ++i) {
CComPtr<IDxcPixStructField> field;
VERIFY_SUCCEEDED(
bfStructType->GetFieldByIndex(static_cast<DWORD>(i), &field));
DWORD offsetInBits = 0;
VERIFY_SUCCEEDED(field->GetOffsetInBits(&offsetInBits));
VERIFY_ARE_EQUAL(memberOffsets[i], offsetInBits);
DWORD sizeInBits = 0;
VERIFY_SUCCEEDED(field->GetFieldSizeInBits(&sizeInBits));
VERIFY_ARE_EQUAL(memberSizes[i], sizeInBits);
}
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_BitFields_Simple) {
const char *hlsl = R"(
struct Bitfields
{
unsigned int first : 17;
unsigned int second : 15; // consume all 32 bits of first dword
unsigned int third : 3; // should be at bit offset 32
unsigned int fourth; // should be at bit offset 64
};
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
Bitfields bf;
bf.first = UAV[0];
bf.second = UAV[1];
bf.third = UAV[2];
bf.fourth = UAV[3];
UAV[16] = bf.first + bf.second + bf.third + bf.fourth; //STOP_HERE
}
)";
RunSizeAndOffsetTestCase(hlsl, {0, 17, 32, 64}, {17, 15, 3, 32});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_BitFields_Derived) {
const char *hlsl = R"(
struct Bitfields
{
uint first : 17;
uint second : 15; // consume all 32 bits of first dword
uint third : 3; // should be at bit offset 32
uint fourth; // should be at bit offset 64
};
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
Bitfields bf;
bf.first = UAV[0];
bf.second = UAV[1];
bf.third = UAV[2];
bf.fourth = UAV[3];
UAV[16] = bf.first + bf.second + bf.third + bf.fourth; //STOP_HERE
}
)";
RunSizeAndOffsetTestCase(hlsl, {0, 17, 32, 64}, {17, 15, 3, 32});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_BitFields_Bool) {
const char *hlsl = R"(
struct Bitfields
{
bool first : 1;
bool second : 1;
bool third : 3; // just to be weird
uint fourth; // should be at bit offset 64
};
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
Bitfields bf;
bf.first = UAV[0];
bf.second = UAV[1];
bf.third = UAV[2];
bf.fourth = UAV[3];
UAV[16] = bf.first + bf.second + bf.third + bf.fourth; //STOP_HERE
}
)";
RunSizeAndOffsetTestCase(hlsl, {0, 1, 2, 32}, {1, 1, 3, 32});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_BitFields_Overlap) {
const char *hlsl = R"(
struct Bitfields
{
unsigned int first : 20;
unsigned int second : 20; // should end up in second DWORD
unsigned int third : 3; // should shader second DWORD
unsigned int fourth; // should be in third DWORD
};
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
Bitfields bf;
bf.first = UAV[0];
bf.second = UAV[1];
bf.third = UAV[2];
bf.fourth = UAV[3];
UAV[16] = bf.first + bf.second + bf.third + bf.fourth; //STOP_HERE
}
)";
RunSizeAndOffsetTestCase(hlsl, {0, 32, 52, 64}, {20, 20, 3, 32});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_Alignment_ConstInt) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
const uint c = UAV[0];
UAV[16] = c;
}
)";
CComPtr<IDiaDataSource> pDiaDataSource;
CompileAndRunAnnotationAndLoadDiaSource(m_dllSupport, hlsl, L"cs_6_5",
nullptr, &pDiaDataSource, {L"-Od"});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_Min16SizesAndOffsets_Enabled) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
struct Mins
{
min16uint first;
min16int second;
min12int third;
min16float fourth;
};
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
Mins bf;
bf.first = UAV[0];
bf.second = UAV[1];
bf.third = UAV[2];
bf.fourth = UAV[3];
UAV[16] = bf.first + bf.second + bf.third + bf.fourth; //STOP_HERE
}
)";
RunSizeAndOffsetTestCase(hlsl, {0, 16, 32, 48}, {16, 16, 16, 16},
{L"-Od", L"-enable-16bit-types"});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_Min16SizesAndOffsets_Disabled) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
struct Mins
{
min16uint first;
min16int second;
min12int third;
min16float fourth;
};
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
Mins bf;
bf.first = UAV[0];
bf.second = UAV[1];
bf.third = UAV[2];
bf.fourth = UAV[3];
UAV[16] = bf.first + bf.second + bf.third + bf.fourth; //STOP_HERE
}
)";
RunSizeAndOffsetTestCase(hlsl, {0, 32, 64, 96}, {16, 16, 16, 16}, {L"-Od"});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_Min16VectorOffsets_Enabled) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
min16float4 vector;
vector.x = UAV[0];
vector.y = UAV[1];
vector.z = UAV[2];
vector.w = UAV[3];
UAV[16] = vector.x + vector.y + vector.z + vector.w; //STOP_HERE
}
)";
RunVectorSizeAndOffsetTestCase(hlsl, {0, 16, 32, 48},
{L"-Od", L"-enable-16bit-types"});
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_Min16VectorOffsets_Disabled) {
if (m_ver.SkipDxilVersion(1, 5))
return;
const char *hlsl = R"(
RWStructuredBuffer<int> UAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
min16float4 vector;
vector.x = UAV[0];
vector.y = UAV[1];
vector.z = UAV[2];
vector.w = UAV[3];
UAV[16] = vector.x + vector.y + vector.z + vector.w; //STOP_HERE
}
)";
RunVectorSizeAndOffsetTestCase(hlsl, {0, 32, 64, 96});
}
void PixDiaTest::RunVectorSizeAndOffsetTestCase(
const char *hlsl, std::array<DWORD, 4> const &memberOffsets,
std::vector<const wchar_t *> extraArgs) {
if (m_ver.SkipDxilVersion(1, 5))
return;
auto debugInfo =
CompileAndCreateDxcDebug(hlsl, L"cs_6_5", nullptr, extraArgs).debugInfo;
auto live = GetLiveVariablesAt(hlsl, "STOP_HERE", debugInfo);
CComPtr<IDxcPixVariable> variable;
VERIFY_SUCCEEDED(live->GetVariableByName(L"vector", &variable));
CComPtr<IDxcPixType> type;
VERIFY_SUCCEEDED(variable->GetType(&type));
CComPtr<IDxcPixType> unAliasedType;
VERIFY_SUCCEEDED(UnAliasType(type, &unAliasedType));
CComPtr<IDxcPixStructType> structType;
VERIFY_SUCCEEDED(unAliasedType->QueryInterface(IID_PPV_ARGS(&structType)));
DWORD fieldCount = 0;
VERIFY_SUCCEEDED(structType->GetNumFields(&fieldCount));
VERIFY_ARE_EQUAL(fieldCount, 4u);
for (size_t i = 0; i < memberOffsets.size(); i++) {
CComPtr<IDxcPixStructField> field;
VERIFY_SUCCEEDED(structType->GetFieldByIndex(i, &field));
DWORD offsetInBits = 0;
VERIFY_SUCCEEDED(field->GetOffsetInBits(&offsetInBits));
VERIFY_ARE_EQUAL(memberOffsets[i], offsetInBits);
}
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_SubProgramsInNamespaces) {
if (m_ver.SkipDxilVersion(1, 2))
return;
const char *hlsl = R"(
#include "../include1/samefilename.h"
#include "../include2/samefilename.h"
RWStructuredBuffer<float> floatRWUAV: register(u0);
[numthreads(1, 1, 1)]
void main()
{
float4 result = fn2(
float3(floatRWUAV[0], floatRWUAV[1], floatRWUAV[2]),
floatRWUAV[3]);
floatRWUAV[0] = result.x;
floatRWUAV[1] = result.y;
floatRWUAV[2] = result.z;
floatRWUAV[3] = result.w;
}
)";
RunSubProgramsCase(hlsl);
}
static DWORD AdvanceUntilFunctionEntered(IDxcPixDxilDebugInfo *dxilDebugger,
DWORD instructionOffset,
wchar_t const *fnName) {
for (;;) {
CComBSTR FunctioName;
if (FAILED(
dxilDebugger->GetFunctionName(instructionOffset, &FunctioName))) {
VERIFY_FAIL(L"Didn't find function");
return -1;
}
if (FunctioName == fnName)
break;
instructionOffset++;
}
return instructionOffset;
}
static DWORD GetRegisterNumberForVariable(IDxcPixDxilDebugInfo *dxilDebugger,
DWORD instructionOffset,
wchar_t const *variableName,
wchar_t const *memberName = nullptr) {
CComPtr<IDxcPixDxilLiveVariables> DxcPixDxilLiveVariables;
if (SUCCEEDED(dxilDebugger->GetLiveVariablesAt(instructionOffset,
&DxcPixDxilLiveVariables))) {
DWORD count = 42;
VERIFY_SUCCEEDED(DxcPixDxilLiveVariables->GetCount(&count));
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> DxcPixVariable;
VERIFY_SUCCEEDED(
DxcPixDxilLiveVariables->GetVariableByIndex(i, &DxcPixVariable));
CComBSTR Name;
VERIFY_SUCCEEDED(DxcPixVariable->GetName(&Name));
if (Name == variableName) {
CComPtr<IDxcPixDxilStorage> DxcPixDxilStorage;
VERIFY_SUCCEEDED(DxcPixVariable->GetStorage(&DxcPixDxilStorage));
if (memberName != nullptr) {
CComPtr<IDxcPixDxilStorage> DxcPixDxilMemberStorage;
VERIFY_SUCCEEDED(DxcPixDxilStorage->AccessField(
memberName, &DxcPixDxilMemberStorage));
DxcPixDxilStorage = DxcPixDxilMemberStorage;
}
DWORD RegisterNumber = 42;
VERIFY_SUCCEEDED(DxcPixDxilStorage->GetRegisterNumber(&RegisterNumber));
return RegisterNumber;
}
}
}
VERIFY_FAIL(L"Couldn't find register number");
return -1;
}
static void
CheckVariableExistsAtThisInstruction(IDxcPixDxilDebugInfo *dxilDebugger,
DWORD instructionOffset,
wchar_t const *variableName) {
// It's sufficient to know that there _is_ a register number the var:
(void)GetRegisterNumberForVariable(dxilDebugger, instructionOffset,
variableName);
}
static void
CheckVariableDoesNOTExistsAtThisInstruction(IDxcPixDxilDebugInfo *dxilDebugger,
DWORD instructionOffset,
wchar_t const *variableName) {
CComPtr<IDxcPixDxilLiveVariables> DxcPixDxilLiveVariables;
VERIFY_SUCCEEDED(dxilDebugger->GetLiveVariablesAt(instructionOffset,
&DxcPixDxilLiveVariables));
DWORD count = 42;
VERIFY_SUCCEEDED(DxcPixDxilLiveVariables->GetCount(&count));
for (DWORD i = 0; i < count; ++i) {
CComPtr<IDxcPixVariable> DxcPixVariable;
VERIFY_SUCCEEDED(
DxcPixDxilLiveVariables->GetVariableByIndex(i, &DxcPixVariable));
CComBSTR Name;
VERIFY_SUCCEEDED(DxcPixVariable->GetName(&Name));
VERIFY_ARE_NOT_EQUAL(Name, variableName);
}
}
TEST_F(
PixDiaTest,
DxcPixDxilDebugInfo_VariableScopes_InlinedFunctions_TwiceInlinedFunctions) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char *hlsl = R"(
struct RayPayload
{
float4 color;
};
RWStructuredBuffer<float4> floatRWUAV: register(u0);
namespace StressScopesABit
{
#include "included.h"
}
namespace StressScopesMore
{
float4 InlinedFunction(in BuiltInTriangleIntersectionAttributes attr, int offset)
{
float4 ret = floatRWUAV.Load(offset + attr.barycentrics.x + 42);
float4 color2 = StressScopesABit::StressScopesEvenMore::DeeperInlinedFunction(attr, offset) + ret;
float4 color3 = StressScopesABit::StressScopesEvenMore::DeeperInlinedFunction(attr, offset+1);
return color2 + color3;
}
}
[shader("closesthit")]
void ClosestHitShader0(inout RayPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
payload.color = StressScopesMore::InlinedFunction(attr, 0);
}
[shader("closesthit")]
void ClosestHitShader1(inout RayPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
payload.color = StressScopesMore::InlinedFunction(attr, 1);
}
[shader("closesthit")]
void ClosestHitShader2(inout RayPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
float4 generateSomeLocalInstrucitons = floatRWUAV.Load(0);
float4 c0 = StressScopesMore::InlinedFunction(attr, 0);
float4 c1 = StressScopesABit::StressScopesEvenMore::DeeperInlinedFunction(attr, 42);
payload.color = c0 + c1 + generateSomeLocalInstrucitons;
}
)";
CComPtr<DxcIncludeHandlerForInjectedSourcesForPix> pIncludeHandler =
new DxcIncludeHandlerForInjectedSourcesForPix(this, {{L"included.h",
R"(
namespace StressScopesEvenMore
{
float4 DeeperInlinedFunction(in BuiltInTriangleIntersectionAttributes attr, int offset)
{
float4 ret = float4(0,0,0,0);
for(int i =0; i < offset; ++i)
{
float4 color0 = floatRWUAV.Load(offset + attr.barycentrics.x);
float4 color1 = floatRWUAV.Load(offset + attr.barycentrics.y);
ret += color0 + color1;
}
return ret;
}
}
)"}});
auto dxilDebugger =
CompileAndCreateDxcDebug(hlsl, L"lib_6_6", pIncludeHandler).debugInfo;
// Case: same functions called from two different top-level callers
DWORD instructionOffset =
AdvanceUntilFunctionEntered(dxilDebugger, 0, L"ClosestHitShader0");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"DeeperInlinedFunction");
DWORD RegisterNumber0 = GetRegisterNumberForVariable(
dxilDebugger, instructionOffset, L"ret", L"x");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"InlinedFunction");
DWORD RegisterNumber2 = GetRegisterNumberForVariable(
dxilDebugger, instructionOffset, L"color2", L"x");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"ClosestHitShader1");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"DeeperInlinedFunction");
DWORD RegisterNumber1 = GetRegisterNumberForVariable(
dxilDebugger, instructionOffset, L"ret", L"x");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"InlinedFunction");
DWORD RegisterNumber3 = GetRegisterNumberForVariable(
dxilDebugger, instructionOffset, L"color2", L"x");
VERIFY_ARE_NOT_EQUAL(RegisterNumber0, RegisterNumber1);
VERIFY_ARE_NOT_EQUAL(RegisterNumber2, RegisterNumber3);
// Case: two different functions called from same top-level function
instructionOffset =
AdvanceUntilFunctionEntered(dxilDebugger, 0, L"ClosestHitShader2");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"InlinedFunction");
DWORD ColorRegisterNumberWhenCalledFromOuterForInlined =
GetRegisterNumberForVariable(dxilDebugger, instructionOffset, L"ret",
L"x");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"DeeperInlinedFunction");
DWORD ColorRegisterNumberWhenCalledFromOuterForDeeper =
GetRegisterNumberForVariable(dxilDebugger, instructionOffset, L"ret",
L"x");
VERIFY_ARE_NOT_EQUAL(ColorRegisterNumberWhenCalledFromOuterForInlined,
ColorRegisterNumberWhenCalledFromOuterForDeeper);
}
TEST_F(
PixDiaTest,
DxcPixDxilDebugInfo_VariableScopes_InlinedFunctions_CalledTwiceInSameCaller) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char *hlsl = R"(
struct RayPayload
{
float4 color;
};
RWStructuredBuffer<float4> floatRWUAV: register(u0);
float4 InlinedFunction(in BuiltInTriangleIntersectionAttributes attr, int offset)
{
float4 ret = floatRWUAV.Load(offset + attr.barycentrics.x);
return ret;
}
[shader("closesthit")]
void ClosestHitShader3(inout RayPayload payload, in BuiltInTriangleIntersectionAttributes attr)
{
float4 generateSomeLocalInstrucitons = floatRWUAV.Load(0);
float4 c0 = InlinedFunction(attr, 2);
float4 generateSomeMoreLocalInstrucitons = floatRWUAV.Load(1);
float4 c1 = InlinedFunction(attr, 3);
payload.color = c0 + c1 + generateSomeLocalInstrucitons + generateSomeMoreLocalInstrucitons;
}
)";
auto dxilDebugger = CompileAndCreateDxcDebug(hlsl, L"lib_6_6").debugInfo;
// Case: same function called from two places in same top-level function.
// In this case, we expect the storage for the variable to be in the same
// place for both "instances" of the function: as a thread proceeds through
// the caller, it will write new values into the variable's storage during
// the second or subsequent invocations of the inlined function.
DWORD instructionOffset =
AdvanceUntilFunctionEntered(dxilDebugger, 0, L"ClosestHitShader3");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"InlinedFunction");
DWORD callsite0 = GetRegisterNumberForVariable(
dxilDebugger, instructionOffset, L"ret", L"x");
// advance until we're out of InlinedFunction before we call it a second
// time
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"ClosestHitShader3");
instructionOffset = AdvanceUntilFunctionEntered(
dxilDebugger, instructionOffset, L"InlinedFunction");
DWORD callsite1 = GetRegisterNumberForVariable(
dxilDebugger, instructionOffset++, L"ret", L"x");
VERIFY_ARE_EQUAL(callsite0, callsite1);
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_VariableScopes_ForScopes) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char *hlsl =
R"(/*01*/RWStructuredBuffer<int> intRWUAV: register(u0);
/*02*/[shader("compute")]
/*03*/[numthreads(1,1,1)]
/*04*/void CSMain()
/*05*/{
/*06*/ int zero = intRWUAV.Load(0);
/*07*/ int two = zero * 2; // debug-loc(CheckVariableExistsHere)
/*08*/ int three = zero * 3;
/*09*/ for(int i =0; i < two; ++ i)
/*10*/ {
/*11*/ int one = intRWUAV.Load(i);
/*12*/ three += one; // debug-loc(Stop inside loop)
/*13*/ }
/*14*/ intRWUAV[0] = three; // debug-loc(Stop here)
/*15*/}
)";
auto debugInterfaces = CompileAndCreateDxcDebug(hlsl, L"lib_6_6");
auto dxilDebugger = debugInterfaces.debugInfo;
auto Labels = GatherDebugLocLabelsFromDxcUtils(debugInterfaces);
// Case: same function called from two places in same top-level function.
// In this case, we expect the storage for the variable to be in the same
// place for both "instances" of the function: as a thread proceeds through
// the caller, it will write new values into the variable's storage during
// the second or subsequent invocations of the inlined function.
DWORD instructionOffset =
AdvanceUntilFunctionEntered(dxilDebugger, 0, L"CSMain");
instructionOffset =
Labels->FindInstructionOffsetForLabel(L"CheckVariableExistsHere");
CheckVariableExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"zero");
instructionOffset =
Labels->FindInstructionOffsetForLabel(L"Stop inside loop");
CheckVariableExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"zero");
instructionOffset = Labels->FindInstructionOffsetForLabel(L"Stop here");
CheckVariableDoesNOTExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"one");
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_VariableScopes_ScopeBraces) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char *hlsl =
R"(/*01*/RWStructuredBuffer<int> intRWUAV: register(u0);
/*02*/[shader("compute")]
/*03*/[numthreads(1,1,1)]
/*04*/void CSMain()
/*05*/{
/*06*/ int zero = intRWUAV.Load(0);
/*07*/ int two = zero * 2; // debug-loc(CheckVariableExistsHere)
/*08*/ {
/*09*/ int one = intRWUAV.Load(1);
/*10*/ two += one; // debug-loc(Stop inside loop)
/*11*/ }
/*12*/ intRWUAV[0] = two; // debug-loc(Stop here)
/*13*/}
)";
auto debugInterfaces = CompileAndCreateDxcDebug(hlsl, L"lib_6_6");
auto Labels = GatherDebugLocLabelsFromDxcUtils(debugInterfaces);
auto dxilDebugger = debugInterfaces.debugInfo;
// Case: same function called from two places in same top-level function.
// In this case, we expect the storage for the variable to be in the same
// place for both "instances" of the function: as a thread proceeds through
// the caller, it will write new values into the variable's storage during
// the second or subsequent invocations of the inlined function.
DWORD instructionOffset =
AdvanceUntilFunctionEntered(dxilDebugger, 0, L"CSMain");
instructionOffset =
Labels->FindInstructionOffsetForLabel(L"CheckVariableExistsHere");
CheckVariableExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"zero");
instructionOffset =
Labels->FindInstructionOffsetForLabel(L"Stop inside loop");
CheckVariableExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"zero");
instructionOffset = Labels->FindInstructionOffsetForLabel(L"Stop here");
CheckVariableDoesNOTExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"one");
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_VariableScopes_Function) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char *hlsl =
R"(/*01*/RWStructuredBuffer<int> intRWUAV: register(u0);
/*02*/int Square(int i) {
/*03*/ int i2 = i * i; // debug-loc(Stop in subroutine)
/*04*/ return i2;
/*05*/}
/*06*/[shader("compute")]
/*07*/[numthreads(1,1,1)]
/*08*/void CSMain()
/*09*/{
/*10*/ int zero = intRWUAV.Load(0);
/*11*/ int two = Square(zero);
/*12*/ intRWUAV[0] = two; // debug-loc(Stop here)
/*13*/}
)";
auto debugInterfaces = CompileAndCreateDxcDebug(hlsl, L"lib_6_6");
auto Labels = GatherDebugLocLabelsFromDxcUtils(debugInterfaces);
auto dxilDebugger = debugInterfaces.debugInfo;
// Case: same function called from two places in same top-level function.
// In this case, we expect the storage for the variable to be in the same
// place for both "instances" of the function: as a thread proceeds through
// the caller, it will write new values into the variable's storage during
// the second or subsequent invocations of the inlined function.
DWORD instructionOffset =
AdvanceUntilFunctionEntered(dxilDebugger, 0, L"CSMain");
instructionOffset =
Labels->FindInstructionOffsetForLabel(L"Stop in subroutine");
CheckVariableDoesNOTExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"zero");
instructionOffset = Labels->FindInstructionOffsetForLabel(L"Stop here");
CheckVariableDoesNOTExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"i2");
CheckVariableExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"zero");
}
TEST_F(PixDiaTest, DxcPixDxilDebugInfo_VariableScopes_Member) {
if (m_ver.SkipDxilVersion(1, 6))
return;
const char *hlsl =
R"(/*01*/RWStructuredBuffer<int> intRWUAV: register(u0);
struct Struct {
int i;
int Getter() {
int q = i;
return q; //debug-loc(inside member fn)
}
};
[shader("compute")]
[numthreads(1,1,1)]
void CSMain()
{
Struct s;
s.i = intRWUAV.Load(0);
int j = s.Getter();
intRWUAV[0] = j; // debug-loc(Stop here)
}
)";
auto debugInterfaces = CompileAndCreateDxcDebug(hlsl, L"lib_6_6");
auto Labels = GatherDebugLocLabelsFromDxcUtils(debugInterfaces);
auto dxilDebugger = debugInterfaces.debugInfo;
// Case: same function called from two places in same top-level function.
// In this case, we expect the storage for the variable to be in the same
// place for both "instances" of the function: as a thread proceeds through
// the caller, it will write new values into the variable's storage during
// the second or subsequent invocations of the inlined function.
DWORD instructionOffset =
AdvanceUntilFunctionEntered(dxilDebugger, 0, L"CSMain");
instructionOffset =
Labels->FindInstructionOffsetForLabel(L"inside member fn");
CheckVariableDoesNOTExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"s");
CheckVariableExistsAtThisInstruction(dxilDebugger, instructionOffset, L"q");
instructionOffset = Labels->FindInstructionOffsetForLabel(L"Stop here");
CheckVariableDoesNOTExistsAtThisInstruction(dxilDebugger, instructionOffset,
L"i");
CheckVariableExistsAtThisInstruction(dxilDebugger, instructionOffset, L"j");
}
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/ValidationTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// ValidationTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// //
///////////////////////////////////////////////////////////////////////////////
#define NOMINMAX
#include "dxc/Support/WinIncludes.h"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/DxilContainer/DxilContainerAssembler.h"
#include "dxc/DxilHash/DxilHash.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Regex.h"
#ifdef _WIN32
#include <atlbase.h>
#endif
#include "dxc/Support/FileIOHelper.h"
#include "dxc/Support/Global.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HlslTestUtils.h"
using namespace std;
using namespace hlsl;
#ifdef _WIN32
class ValidationTest {
#else
class ValidationTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(ValidationTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
TEST_METHOD(WhenCorrectThenOK)
TEST_METHOD(WhenMisalignedThenFail)
TEST_METHOD(WhenEmptyFileThenFail)
TEST_METHOD(WhenIncorrectMagicThenFail)
TEST_METHOD(WhenIncorrectTargetTripleThenFail)
TEST_METHOD(WhenIncorrectModelThenFail)
TEST_METHOD(WhenIncorrectPSThenFail)
TEST_METHOD(WhenWaveAffectsGradientThenFail)
TEST_METHOD(WhenMultipleModulesThenFail)
TEST_METHOD(WhenUnexpectedEOFThenFail)
TEST_METHOD(WhenUnknownBlocksThenFail)
TEST_METHOD(WhenZeroInputPatchCountWithInputThenFail)
TEST_METHOD(Float32DenormModeAttribute)
TEST_METHOD(LoadOutputControlPointNotInPatchConstantFunction)
TEST_METHOD(StorePatchControlNotInPatchConstantFunction)
TEST_METHOD(OutputControlPointIDInPatchConstantFunction)
TEST_METHOD(GsVertexIDOutOfBound)
TEST_METHOD(StreamIDOutOfBound)
TEST_METHOD(SignatureDataWidth)
TEST_METHOD(SignatureStreamIDForNonGS)
TEST_METHOD(TypedUAVStoreFullMask0)
TEST_METHOD(TypedUAVStoreFullMask1)
TEST_METHOD(UAVStoreMaskMatch)
TEST_METHOD(UAVStoreMaskGap)
TEST_METHOD(UAVStoreMaskGap2)
TEST_METHOD(UAVStoreMaskGap3)
TEST_METHOD(Recursive)
TEST_METHOD(ResourceRangeOverlap0)
TEST_METHOD(ResourceRangeOverlap1)
TEST_METHOD(ResourceRangeOverlap2)
TEST_METHOD(ResourceRangeOverlap3)
TEST_METHOD(CBufferOverlap0)
TEST_METHOD(CBufferOverlap1)
TEST_METHOD(ControlFlowHint)
TEST_METHOD(ControlFlowHint1)
TEST_METHOD(ControlFlowHint2)
TEST_METHOD(SemanticLength1)
TEST_METHOD(SemanticLength64)
TEST_METHOD(PullModelPosition)
TEST_METHOD(StructBufStrideAlign)
TEST_METHOD(StructBufStrideOutOfBound)
TEST_METHOD(StructBufGlobalCoherentAndCounter)
TEST_METHOD(StructBufLoadCoordinates)
TEST_METHOD(StructBufStoreCoordinates)
TEST_METHOD(TypedBufRetType)
TEST_METHOD(VsInputSemantic)
TEST_METHOD(VsOutputSemantic)
TEST_METHOD(HsInputSemantic)
TEST_METHOD(HsOutputSemantic)
TEST_METHOD(PatchConstSemantic)
TEST_METHOD(DsInputSemantic)
TEST_METHOD(DsOutputSemantic)
TEST_METHOD(GsInputSemantic)
TEST_METHOD(GsOutputSemantic)
TEST_METHOD(PsInputSemantic)
TEST_METHOD(PsOutputSemantic)
TEST_METHOD(ArrayOfSVTarget)
TEST_METHOD(InfiniteLog)
TEST_METHOD(InfiniteAsin)
TEST_METHOD(InfiniteAcos)
TEST_METHOD(InfiniteDdxDdy)
TEST_METHOD(IDivByZero)
TEST_METHOD(UDivByZero)
TEST_METHOD(UnusedMetadata)
TEST_METHOD(MemoryOutOfBound)
TEST_METHOD(LocalRes2)
TEST_METHOD(LocalRes3)
TEST_METHOD(LocalRes5)
TEST_METHOD(LocalRes5Dbg)
TEST_METHOD(LocalRes6)
TEST_METHOD(LocalRes6Dbg)
TEST_METHOD(AddrSpaceCast)
TEST_METHOD(PtrBitCast)
TEST_METHOD(MinPrecisionBitCast)
TEST_METHOD(StructBitCast)
TEST_METHOD(MultiDimArray)
TEST_METHOD(SimpleGs8)
TEST_METHOD(SimpleGs9)
TEST_METHOD(SimpleGs10)
TEST_METHOD(IllegalSampleOffset3)
TEST_METHOD(IllegalSampleOffset4)
TEST_METHOD(NoFunctionParam)
TEST_METHOD(I8Type)
TEST_METHOD(EmptyStructInBuffer)
TEST_METHOD(BigStructInBuffer)
// TODO: enable this.
// TEST_METHOD(TGSMRaceCond)
// TEST_METHOD(TGSMRaceCond2)
TEST_METHOD(AddUint64Odd)
TEST_METHOD(BarycentricFloat4Fail)
TEST_METHOD(BarycentricMaxIndexFail)
TEST_METHOD(BarycentricNoInterpolationFail)
TEST_METHOD(BarycentricSamePerspectiveFail)
TEST_METHOD(ClipCullMaxComponents)
TEST_METHOD(ClipCullMaxRows)
TEST_METHOD(DuplicateSysValue)
TEST_METHOD(FunctionAttributes)
TEST_METHOD(GSMainMissingAttributeFail)
TEST_METHOD(GSOtherMissingAttributeFail)
TEST_METHOD(GetAttributeAtVertexInVSFail)
TEST_METHOD(GetAttributeAtVertexIn60Fail)
TEST_METHOD(GetAttributeAtVertexInterpFail)
TEST_METHOD(SemTargetMax)
TEST_METHOD(SemTargetIndexMatchesRow)
TEST_METHOD(SemTargetCol0)
TEST_METHOD(SemIndexMax)
TEST_METHOD(SemTessFactorIndexMax)
TEST_METHOD(SemInsideTessFactorIndexMax)
TEST_METHOD(SemShouldBeAllocated)
TEST_METHOD(SemShouldNotBeAllocated)
TEST_METHOD(SemComponentOrder)
TEST_METHOD(SemComponentOrder2)
TEST_METHOD(SemComponentOrder3)
TEST_METHOD(SemIndexConflictArbSV)
TEST_METHOD(SemIndexConflictTessfactors)
TEST_METHOD(SemIndexConflictTessfactors2)
TEST_METHOD(SemRowOutOfRange)
TEST_METHOD(SemPackOverlap)
TEST_METHOD(SemPackOverlap2)
TEST_METHOD(SemMultiDepth)
TEST_METHOD(WhenInstrDisallowedThenFail)
TEST_METHOD(WhenDepthNotFloatThenFail)
TEST_METHOD(BarrierFail)
TEST_METHOD(CBufferLegacyOutOfBoundFail)
TEST_METHOD(CsThreadSizeFail)
TEST_METHOD(DeadLoopFail)
TEST_METHOD(EvalFail)
TEST_METHOD(GetDimCalcLODFail)
TEST_METHOD(HsAttributeFail)
TEST_METHOD(InnerCoverageFail)
TEST_METHOD(InterpChangeFail)
TEST_METHOD(InterpOnIntFail)
TEST_METHOD(InvalidSigCompTyFail)
TEST_METHOD(MultiStream2Fail)
TEST_METHOD(PhiTGSMFail)
TEST_METHOD(QuadOpInVS)
TEST_METHOD(ReducibleFail)
TEST_METHOD(SampleBiasFail)
TEST_METHOD(SamplerKindFail)
TEST_METHOD(SemaOverlapFail)
TEST_METHOD(SigOutOfRangeFail)
TEST_METHOD(SigOverlapFail)
TEST_METHOD(SimpleHs1Fail)
TEST_METHOD(SimpleHs3Fail)
TEST_METHOD(SimpleHs4Fail)
TEST_METHOD(SimpleDs1Fail)
TEST_METHOD(SimpleGs1Fail)
TEST_METHOD(UavBarrierFail)
TEST_METHOD(UndefValueFail)
TEST_METHOD(UpdateCounterFail)
TEST_METHOD(LocalResCopy)
TEST_METHOD(ResCounter)
TEST_METHOD(WhenSmUnknownThenFail)
TEST_METHOD(WhenSmLegacyThenFail)
TEST_METHOD(WhenMetaFlagsUsageDeclThenOK)
TEST_METHOD(WhenMetaFlagsUsageThenFail)
TEST_METHOD(WhenRootSigMismatchThenFail)
TEST_METHOD(WhenRootSigCompatThenSucceed)
TEST_METHOD(WhenRootSigMatchShaderSucceed_RootConstVis)
TEST_METHOD(WhenRootSigMatchShaderFail_RootConstVis)
TEST_METHOD(WhenRootSigMatchShaderSucceed_RootCBV)
TEST_METHOD(WhenRootSigMatchShaderFail_RootCBV_Range)
TEST_METHOD(WhenRootSigMatchShaderFail_RootCBV_Space)
TEST_METHOD(WhenRootSigMatchShaderSucceed_RootSRV)
TEST_METHOD(WhenRootSigMatchShaderFail_RootSRV_ResType)
TEST_METHOD(WhenRootSigMatchShaderSucceed_RootUAV)
TEST_METHOD(WhenRootSigMatchShaderSucceed_DescTable)
TEST_METHOD(WhenRootSigMatchShaderSucceed_DescTable_GoodRange)
TEST_METHOD(WhenRootSigMatchShaderSucceed_DescTable_Unbounded)
TEST_METHOD(WhenRootSigMatchShaderFail_DescTable_Range1)
TEST_METHOD(WhenRootSigMatchShaderFail_DescTable_Range2)
TEST_METHOD(WhenRootSigMatchShaderFail_DescTable_Range3)
TEST_METHOD(WhenRootSigMatchShaderFail_DescTable_Space)
TEST_METHOD(WhenRootSigMatchShaderSucceed_Unbounded)
TEST_METHOD(WhenRootSigMatchShaderFail_Unbounded1)
TEST_METHOD(WhenRootSigMatchShaderFail_Unbounded2)
TEST_METHOD(WhenRootSigMatchShaderFail_Unbounded3)
TEST_METHOD(WhenProgramOutSigMissingThenFail)
TEST_METHOD(WhenProgramOutSigUnexpectedThenFail)
TEST_METHOD(WhenProgramSigMismatchThenFail)
TEST_METHOD(WhenProgramInSigMissingThenFail)
TEST_METHOD(WhenProgramSigMismatchThenFail2)
TEST_METHOD(WhenProgramPCSigMissingThenFail)
TEST_METHOD(WhenPSVMismatchThenFail)
TEST_METHOD(WhenRDATMismatchThenFail)
TEST_METHOD(WhenFeatureInfoMismatchThenFail)
TEST_METHOD(RayShaderWithSignaturesFail)
TEST_METHOD(ViewIDInCSFail)
TEST_METHOD(ViewIDIn60Fail)
TEST_METHOD(ViewIDNoSpaceFail)
TEST_METHOD(LibFunctionResInSig)
TEST_METHOD(RayPayloadIsStruct)
TEST_METHOD(RayAttrIsStruct)
TEST_METHOD(CallableParamIsStruct)
TEST_METHOD(RayShaderExtraArg)
TEST_METHOD(ResInShaderStruct)
TEST_METHOD(WhenPayloadSizeTooSmallThenFail)
TEST_METHOD(WhenMissingPayloadThenFail)
TEST_METHOD(ShaderFunctionReturnTypeVoid)
TEST_METHOD(WhenDisassembleInvalidBlobThenFail)
TEST_METHOD(MeshMultipleSetMeshOutputCounts)
TEST_METHOD(MeshMissingSetMeshOutputCounts)
TEST_METHOD(MeshNonDominatingSetMeshOutputCounts)
TEST_METHOD(MeshOversizePayload)
TEST_METHOD(MeshOversizeOutput)
TEST_METHOD(MeshOversizePayloadOutput)
TEST_METHOD(MeshMultipleGetMeshPayload)
TEST_METHOD(MeshOutofRangeMaxVertexCount)
TEST_METHOD(MeshOutofRangeMaxPrimitiveCount)
TEST_METHOD(MeshLessThanMinX)
TEST_METHOD(MeshGreaterThanMaxX)
TEST_METHOD(MeshLessThanMinY)
TEST_METHOD(MeshGreaterThanMaxY)
TEST_METHOD(MeshLessThanMinZ)
TEST_METHOD(MeshGreaterThanMaxZ)
TEST_METHOD(MeshGreaterThanMaxXYZ)
TEST_METHOD(MeshGreaterThanMaxVSigRowCount)
TEST_METHOD(MeshGreaterThanMaxPSigRowCount)
TEST_METHOD(MeshGreaterThanMaxTotalSigRowCount)
TEST_METHOD(MeshOversizeSM)
TEST_METHOD(AmplificationMultipleDispatchMesh)
TEST_METHOD(AmplificationMissingDispatchMesh)
TEST_METHOD(AmplificationNonDominatingDispatchMesh)
TEST_METHOD(AmplificationOversizePayload)
TEST_METHOD(AmplificationLessThanMinX)
TEST_METHOD(AmplificationGreaterThanMaxX)
TEST_METHOD(AmplificationLessThanMinY)
TEST_METHOD(AmplificationGreaterThanMaxY)
TEST_METHOD(AmplificationLessThanMinZ)
TEST_METHOD(AmplificationGreaterThanMaxZ)
TEST_METHOD(AmplificationGreaterThanMaxXYZ)
TEST_METHOD(ValidateRootSigContainer)
TEST_METHOD(ValidatePrintfNotAllowed)
TEST_METHOD(ValidateWithHash)
TEST_METHOD(ValidateVersionNotAllowed)
TEST_METHOD(CreateHandleNotAllowedSM66)
TEST_METHOD(AtomicsConsts)
TEST_METHOD(AtomicsInvalidDests)
TEST_METHOD(ComputeNodeCompatibility)
TEST_METHOD(NodeInputCompatibility)
TEST_METHOD(NodeInputMultiplicity)
TEST_METHOD(CacheInitWithMinPrec)
TEST_METHOD(CacheInitWithLowPrec)
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
void TestCheck(LPCWSTR name) {
std::wstring fullPath = hlsl_test::GetPathToHlslDataFile(name);
FileRunTestResult t =
FileRunTestResult::RunFromFileCommands(fullPath.c_str());
if (t.RunResult != 0) {
CA2W commentWide(t.ErrorMessage.c_str());
WEX::Logging::Log::Comment(commentWide);
WEX::Logging::Log::Error(L"Run result is not zero");
}
}
void CheckValidationMsgs(IDxcBlob *pBlob, llvm::ArrayRef<LPCSTR> pErrorMsgs,
bool bRegex = false,
UINT32 Flags = DxcValidatorFlags_Default) {
CComPtr<IDxcValidator> pValidator;
CComPtr<IDxcOperationResult> pResult;
if (!IsDxilContainerLike(pBlob->GetBufferPointer(),
pBlob->GetBufferSize())) {
// Validation of raw bitcode as opposed to DxilContainer is not supported
// through DXIL.dll
if (!m_ver.m_InternalValidator) {
WEX::Logging::Log::Comment(
L"Test skipped due to validation of raw bitcode without container "
L"and use of external DXIL.dll validator.");
return;
}
Flags |= DxcValidatorFlags_ModuleOnly;
}
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcValidator, &pValidator));
VERIFY_SUCCEEDED(pValidator->Validate(pBlob, Flags, &pResult));
CheckOperationResultMsgs(pResult, pErrorMsgs, false, bRegex);
}
void CheckValidationMsgs(const char *pBlob, size_t blobSize,
llvm::ArrayRef<LPCSTR> pErrorMsgs,
bool bRegex = false,
UINT32 Flags = DxcValidatorFlags_Default) {
CComPtr<IDxcLibrary> pLibrary;
CComPtr<IDxcBlobEncoding>
pBlobEncoding; // Encoding doesn't actually matter, it's binary.
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
VERIFY_SUCCEEDED(pLibrary->CreateBlobWithEncodingFromPinned(
pBlob, blobSize, DXC_CP_ACP, &pBlobEncoding));
CheckValidationMsgs(pBlobEncoding, pErrorMsgs, bRegex, Flags);
}
bool CompileSource(IDxcBlobEncoding *pSource, LPCSTR pShaderModel,
LPCWSTR *pArguments, UINT32 argCount,
const DxcDefine *pDefines, UINT32 defineCount,
IDxcBlob **pResultBlob) {
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlob> pProgram;
CA2W shWide(pShaderModel);
const wchar_t *pEntryName = L"main";
llvm::StringRef stage;
unsigned RequiredDxilMajor = 1, RequiredDxilMinor = 0;
if (ParseTargetProfile(pShaderModel, stage, RequiredDxilMajor,
RequiredDxilMinor)) {
if (stage.compare("lib") == 0)
pEntryName = L"";
if (stage.compare("rootsig") != 0) {
RequiredDxilMajor = std::max(RequiredDxilMajor, (unsigned)6) - 5;
if (m_ver.SkipDxilVersion(RequiredDxilMajor, RequiredDxilMinor))
return false;
}
}
std::vector<LPCWSTR> args;
args.reserve(argCount + 1);
args.insert(args.begin(), pArguments, pArguments + argCount);
args.emplace_back(L"-Qkeep_reflect_in_dxil");
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
VERIFY_SUCCEEDED(pCompiler->Compile(
pSource, L"hlsl.hlsl", pEntryName, shWide, args.data(),
(UINT32)args.size(), pDefines, defineCount, nullptr, &pResult));
CheckOperationResultMsgs(pResult, nullptr, false, false);
VERIFY_SUCCEEDED(pResult->GetResult(pResultBlob));
return true;
}
bool CompileSource(IDxcBlobEncoding *pSource, LPCSTR pShaderModel,
IDxcBlob **pResultBlob) {
return CompileSource(pSource, pShaderModel, nullptr, 0, nullptr, 0,
pResultBlob);
}
bool CompileSource(LPCSTR pSource, LPCSTR pShaderModel,
IDxcBlob **pResultBlob) {
CComPtr<IDxcBlobEncoding> pSourceBlob;
Utf8ToBlob(m_dllSupport, pSource, &pSourceBlob);
return CompileSource(pSourceBlob, pShaderModel, nullptr, 0, nullptr, 0,
pResultBlob);
}
void DisassembleProgram(IDxcBlob *pProgram, std::string *text) {
*text = ::DisassembleProgram(m_dllSupport, pProgram);
}
bool RewriteAssemblyCheckMsg(IDxcBlobEncoding *pSource, LPCSTR pShaderModel,
LPCWSTR *pArguments, UINT32 argCount,
const DxcDefine *pDefines, UINT32 defineCount,
llvm::ArrayRef<LPCSTR> pLookFors,
llvm::ArrayRef<LPCSTR> pReplacements,
llvm::ArrayRef<LPCSTR> pErrorMsgs,
bool bRegex = false) {
CComPtr<IDxcBlob> pText;
if (!RewriteAssemblyToText(pSource, pShaderModel, pArguments, argCount,
pDefines, defineCount, pLookFors, pReplacements,
&pText, bRegex))
return false;
CComPtr<IDxcAssembler> pAssembler;
CComPtr<IDxcOperationResult> pAssembleResult;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
VERIFY_SUCCEEDED(pAssembler->AssembleToContainer(pText, &pAssembleResult));
if (!CheckOperationResultMsgs(pAssembleResult, pErrorMsgs, true, bRegex)) {
// Assembly succeeded, try validation.
CComPtr<IDxcBlob> pBlob;
VERIFY_SUCCEEDED(pAssembleResult->GetResult(&pBlob));
CheckValidationMsgs(pBlob, pErrorMsgs, bRegex);
}
return true;
}
void RewriteAssemblyCheckMsg(LPCSTR pSource, LPCSTR pShaderModel,
LPCWSTR *pArguments, UINT32 argCount,
const DxcDefine *pDefines, UINT32 defineCount,
llvm::ArrayRef<LPCSTR> pLookFors,
llvm::ArrayRef<LPCSTR> pReplacements,
llvm::ArrayRef<LPCSTR> pErrorMsgs,
bool bRegex = false) {
CComPtr<IDxcBlobEncoding> pSourceBlob;
Utf8ToBlob(m_dllSupport, pSource, &pSourceBlob);
RewriteAssemblyCheckMsg(pSourceBlob, pShaderModel, pArguments, argCount,
pDefines, defineCount, pLookFors, pReplacements,
pErrorMsgs, bRegex);
}
void RewriteAssemblyCheckMsg(LPCSTR pSource, LPCSTR pShaderModel,
llvm::ArrayRef<LPCSTR> pLookFors,
llvm::ArrayRef<LPCSTR> pReplacements,
llvm::ArrayRef<LPCSTR> pErrorMsgs,
bool bRegex = false) {
RewriteAssemblyCheckMsg(pSource, pShaderModel, nullptr, 0, nullptr, 0,
pLookFors, pReplacements, pErrorMsgs, bRegex);
}
void RewriteAssemblyCheckMsg(LPCWSTR name, LPCSTR pShaderModel,
LPCWSTR *pArguments, UINT32 argCount,
const DxcDefine *pDefines, UINT32 defCount,
llvm::ArrayRef<LPCSTR> pLookFors,
llvm::ArrayRef<LPCSTR> pReplacements,
llvm::ArrayRef<LPCSTR> pErrorMsgs,
bool bRegex = false) {
std::wstring fullPath = hlsl_test::GetPathToHlslDataFile(name);
CComPtr<IDxcLibrary> pLibrary;
CComPtr<IDxcBlobEncoding> pSource;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
VERIFY_SUCCEEDED(
pLibrary->CreateBlobFromFile(fullPath.c_str(), nullptr, &pSource));
RewriteAssemblyCheckMsg(pSource, pShaderModel, pArguments, argCount,
pDefines, defCount, pLookFors, pReplacements,
pErrorMsgs, bRegex);
}
void RewriteAssemblyCheckMsg(LPCWSTR name, LPCSTR pShaderModel,
llvm::ArrayRef<LPCSTR> pLookFors,
llvm::ArrayRef<LPCSTR> pReplacements,
llvm::ArrayRef<LPCSTR> pErrorMsgs,
bool bRegex = false) {
RewriteAssemblyCheckMsg(name, pShaderModel, nullptr, 0, nullptr, 0,
pLookFors, pReplacements, pErrorMsgs, bRegex);
}
bool RewriteAssemblyToText(IDxcBlobEncoding *pSource, LPCSTR pShaderModel,
LPCWSTR *pArguments, UINT32 argCount,
const DxcDefine *pDefines, UINT32 defineCount,
llvm::ArrayRef<LPCSTR> pLookFors,
llvm::ArrayRef<LPCSTR> pReplacements,
IDxcBlob **pBlob, bool bRegex = false) {
CComPtr<IDxcBlob> pProgram;
std::string disassembly;
if (!CompileSource(pSource, pShaderModel, pArguments, argCount, pDefines,
defineCount, &pProgram))
return false;
DisassembleProgram(pProgram, &disassembly);
for (unsigned i = 0; i < pLookFors.size(); ++i) {
LPCSTR pLookFor = pLookFors[i];
bool bOptional = false;
if (pLookFor[0] == '?') {
bOptional = true;
pLookFor++;
}
LPCSTR pReplacement = pReplacements[i];
if (pLookFor && *pLookFor) {
if (bRegex) {
llvm::Regex RE(pLookFor);
std::string reErrors;
if (!RE.isValid(reErrors)) {
WEX::Logging::Log::Comment(WEX::Common::String().Format(
L"Regex errors:\r\n%.*S\r\nWhile compiling expression '%S'",
(unsigned)reErrors.size(), reErrors.data(), pLookFor));
}
VERIFY_IS_TRUE(RE.isValid(reErrors));
std::string replaced = RE.sub(pReplacement, disassembly, &reErrors);
if (!bOptional) {
if (!reErrors.empty()) {
WEX::Logging::Log::Comment(WEX::Common::String().Format(
L"Regex errors:\r\n%.*S\r\nWhile searching for '%S' in "
L"text:\r\n%.*S",
(unsigned)reErrors.size(), reErrors.data(), pLookFor,
(unsigned)disassembly.size(), disassembly.data()));
}
VERIFY_ARE_NOT_EQUAL(disassembly, replaced);
VERIFY_IS_TRUE(reErrors.empty());
}
disassembly = std::move(replaced);
} else {
bool found = false;
size_t pos = 0;
size_t lookForLen = strlen(pLookFor);
size_t replaceLen = strlen(pReplacement);
for (;;) {
pos = disassembly.find(pLookFor, pos);
if (pos == std::string::npos)
break;
found = true; // at least once
disassembly.replace(pos, lookForLen, pReplacement);
pos += replaceLen;
}
if (!bOptional) {
if (!found) {
WEX::Logging::Log::Comment(WEX::Common::String().Format(
L"String not found: '%S' in text:\r\n%.*S", pLookFor,
(unsigned)disassembly.size(), disassembly.data()));
}
VERIFY_IS_TRUE(found);
}
}
}
}
Utf8ToBlob(m_dllSupport, disassembly.c_str(), pBlob);
return true;
}
// compile one or two sources, validate module from 1 with container parts
// from 2, check messages
bool ReplaceContainerPartsCheckMsgs(LPCSTR pSource1, LPCSTR pSource2,
LPCSTR pShaderModel,
llvm::ArrayRef<DxilFourCC> PartsToReplace,
llvm::ArrayRef<LPCSTR> pErrorMsgs) {
CComPtr<IDxcBlob> pProgram1, pProgram2;
if (!CompileSource(pSource1, pShaderModel, &pProgram1))
return false;
VERIFY_IS_NOT_NULL(pProgram1);
if (pSource2) {
if (!CompileSource(pSource2, pShaderModel, &pProgram2))
return false;
VERIFY_IS_NOT_NULL(pProgram2);
} else {
pProgram2 = pProgram1;
}
// construct container with module from pProgram1 with other parts from
// pProgram2:
const DxilContainerHeader *pHeader1 = IsDxilContainerLike(
pProgram1->GetBufferPointer(), pProgram1->GetBufferSize());
VERIFY_IS_NOT_NULL(pHeader1);
const DxilContainerHeader *pHeader2 = IsDxilContainerLike(
pProgram2->GetBufferPointer(), pProgram2->GetBufferSize());
VERIFY_IS_NOT_NULL(pHeader2);
unique_ptr<DxilContainerWriter> pContainerWriter(NewDxilContainerWriter(
DXIL::CompareVersions(m_ver.m_ValMajor, m_ver.m_ValMinor, 1, 7) < 0));
// Add desired parts from first container
for (auto pPart : pHeader1) {
for (auto dfcc : PartsToReplace) {
if (dfcc == pPart->PartFourCC) {
pPart = nullptr;
break;
}
}
if (!pPart)
continue;
pContainerWriter->AddPart(pPart->PartFourCC, pPart->PartSize,
[=](AbstractMemoryStream *pStream) {
ULONG cbWritten = 0;
pStream->Write(GetDxilPartData(pPart),
pPart->PartSize, &cbWritten);
});
}
// Add desired parts from second container
for (auto pPart : pHeader2) {
for (auto dfcc : PartsToReplace) {
if (dfcc == pPart->PartFourCC) {
pContainerWriter->AddPart(pPart->PartFourCC, pPart->PartSize,
[=](AbstractMemoryStream *pStream) {
ULONG cbWritten = 0;
pStream->Write(GetDxilPartData(pPart),
pPart->PartSize,
&cbWritten);
});
break;
}
}
}
// Write the container
CComPtr<IMalloc> pMalloc;
VERIFY_SUCCEEDED(DxcCoGetMalloc(1, &pMalloc));
CComPtr<AbstractMemoryStream> pOutputStream;
VERIFY_SUCCEEDED(CreateMemoryStream(pMalloc, &pOutputStream));
pOutputStream->Reserve(pContainerWriter->size());
pContainerWriter->write(pOutputStream);
CheckValidationMsgs((const char *)pOutputStream->GetPtr(),
pOutputStream->GetPtrSize(), pErrorMsgs,
/*bRegex*/ false);
return true;
}
};
bool ValidationTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
TEST_F(ValidationTest, WhenCorrectThenOK) {
CComPtr<IDxcBlob> pProgram;
CompileSource("float4 main() : SV_Target { return 1; }", "ps_6_0", &pProgram);
CheckValidationMsgs(pProgram, nullptr);
}
// Lots of these going on below for simplicity in setting up payloads.
//
// warning C4838: conversion from 'int' to 'const char' requires a narrowing
// conversion warning C4309: 'initializing': truncation of constant value
#pragma warning(disable : 4838)
#pragma warning(disable : 4309)
TEST_F(ValidationTest, WhenMisalignedThenFail) {
// Bitcode size must 4-byte aligned
const char blob[] = {
'B',
'C',
};
CheckValidationMsgs(blob, _countof(blob), "Invalid bitcode size");
}
TEST_F(ValidationTest, WhenEmptyFileThenFail) {
// No blocks after signature.
const char blob[] = {'B', 'C', (char)0xc0, (char)0xde};
CheckValidationMsgs(blob, _countof(blob), "Malformed IR file");
}
TEST_F(ValidationTest, WhenIncorrectMagicThenFail) {
// Signature isn't 'B', 'C', 0xC0 0xDE
const char blob[] = {'B', 'C', (char)0xc0, (char)0xdd};
CheckValidationMsgs(blob, _countof(blob), "Invalid bitcode signature");
}
TEST_F(ValidationTest, WhenIncorrectTargetTripleThenFail) {
const char blob[] = {'B', 'C', (char)0xc0, (char)0xde};
CheckValidationMsgs(blob, _countof(blob), "Malformed IR file");
}
TEST_F(ValidationTest, WhenMultipleModulesThenFail) {
const char blob[] = {
'B', 'C', (char)0xc0, (char)0xde, 0x21, 0x0c, 0x00,
0x00, // Enter sub-block, BlockID = 8, Code Size=3, padding x2
0x00, 0x00, 0x00, 0x00, // NumWords = 0
0x08, 0x00, 0x00, 0x00, // End-of-block, padding
// At this point, this is valid bitcode (but missing required DXIL
// metadata) Trigger the case we're looking for now
0x21, 0x0c, 0x00,
0x00, // Enter sub-block, BlockID = 8, Code Size=3, padding x2
};
CheckValidationMsgs(blob, _countof(blob), "Unused bits in buffer");
}
TEST_F(ValidationTest, WhenUnexpectedEOFThenFail) {
// Importantly, this is testing the usage of report_fatal_error during
// deserialization.
const char blob[] = {
'B', 'C', (char)0xc0, (char)0xde, 0x21,
0x0c, 0x00, 0x00, // Enter sub-block, BlockID = 8, Code Size=3, padding x2
0x00, 0x00, 0x00, 0x00, // NumWords = 0
};
CheckValidationMsgs(blob, _countof(blob), "Invalid record");
}
TEST_F(ValidationTest, WhenUnknownBlocksThenFail) {
const char blob[] = {
'B', 'C', (char)0xc0, (char)0xde, // Signature
0x31, 0x00, 0x00, 0x00 // Enter sub-block, BlockID != 8
};
CheckValidationMsgs(blob, _countof(blob), "Unrecognized block found");
}
TEST_F(ValidationTest, WhenZeroInputPatchCountWithInputThenFail) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleHs1.hlsl", "hs_6_0",
"void ()* "
"@\"\\01?HSPerPatchFunc@@YA?AUHSPerPatchData@@V?$"
"InputPatch@UPSSceneIn@@$02@@@Z\", i32 3, i32 3",
"void ()* "
"@\"\\01?HSPerPatchFunc@@YA?AUHSPerPatchData@@V?$"
"InputPatch@UPSSceneIn@@$02@@@Z\", i32 0, i32 3",
"When HS input control point count is 0, no input "
"signature should exist");
}
TEST_F(ValidationTest, WhenInstrDisallowedThenFail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\abs2.hlsl", "ps_6_0",
{
"target triple = \"dxil-ms-dx\"",
"ret void",
"dx.op.loadInput.i32(i32 4, i32 0, i32 0, i8 3, i32 undef)",
"!\"ps\", i32 6, i32 0",
},
{
"target triple = \"dxil-ms-dx\"\n%dx.types.wave_t = type { i8* }",
"unreachable",
"dx.op.loadInput.i32(i32 4, i32 0, i32 0, i8 3, i32 "
"undef)\n%wave_local = alloca %dx.types.wave_t",
"!\"vs\", i32 6, i32 0",
},
{
"Semantic 'SV_Target' is invalid as vs Output",
"Declaration '%dx.types.wave_t = type { i8* }' uses a reserved "
"prefix",
"Instructions must be of an allowed type",
});
}
TEST_F(ValidationTest, WhenDepthNotFloatThenFail) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\IntegerDepth2.hlsl", "ps_6_0",
{
"!\"SV_Depth\", i8 9",
},
{
"!\"SV_Depth\", i8 4",
},
{
"SV_Depth must be float",
});
}
TEST_F(ValidationTest, BarrierFail) {
if (m_ver.SkipIRSensitiveTest())
return;
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\barrier.hlsl", "cs_6_0",
{
"dx.op.barrier(i32 80, i32 8)",
"dx.op.barrier(i32 80, i32 9)",
"dx.op.barrier(i32 80, i32 11)",
"%\"hostlayout.class.RWStructuredBuffer<matrix<float, 2, 2> >\" = "
"type { [2 x <2 x float>] }\n",
"call i32 @dx.op.flattenedThreadIdInGroup.i32(i32 96)",
},
{
"dx.op.barrier(i32 80, i32 15)",
"dx.op.barrier(i32 80, i32 0)",
"dx.op.barrier(i32 80, i32 %rem)",
"%\"hostlayout.class.RWStructuredBuffer<matrix<float, 2, 2> >\" = "
"type { [2 x <2 x float>] }\n"
"@dx.typevar.8 = external addrspace(1) constant "
"%\"hostlayout.class.RWStructuredBuffer<matrix<float, 2, 2> >\"\n"
"@\"internalGV\" = internal global [64 x <4 x float>] undef\n",
"call i32 @dx.op.flattenedThreadIdInGroup.i32(i32 96)\n"
"%load = load %\"hostlayout.class.RWStructuredBuffer<matrix<float, "
"2, 2> >\", %\"hostlayout.class.RWStructuredBuffer<matrix<float, 2, "
"2> >\" addrspace(1)* @dx.typevar.8",
},
{"Internal declaration 'internalGV' is unused",
"External declaration 'dx.typevar.8' is unused",
"Vector type '<4 x float>' is not allowed",
"Mode of Barrier must be an immediate constant",
"sync must include some form of memory barrier - _u (UAV) and/or _g "
"(Thread Group Shared Memory)",
"sync can't specify both _ugroup and _uglobal. If both are needed, just "
"specify _uglobal"});
}
TEST_F(ValidationTest, CBufferLegacyOutOfBoundFail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\cbuffer1.50.hlsl", "ps_6_0",
"cbufferLoadLegacy.f32(i32 59, %dx.types.Handle %Foo2_cbuffer, i32 0)",
"cbufferLoadLegacy.f32(i32 59, %dx.types.Handle %Foo2_cbuffer, i32 6)",
"Cbuffer access out of bound");
}
TEST_F(ValidationTest, CsThreadSizeFail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\share_mem1.hlsl", "cs_6_0",
{"!{i32 8, i32 8, i32 1", "[256 x float]"},
{"!{i32 1025, i32 1025, i32 1025", "[64000000 x float]"},
{
"Declared Thread Group X size 1025 outside valid range",
"Declared Thread Group Y size 1025 outside valid range",
"Declared Thread Group Z size 1025 outside valid range",
"Declared Thread Group Count 1076890625 (X*Y*Z) is beyond the valid "
"maximum",
"Total Thread Group Shared Memory storage is 256000000, exceeded "
"32768",
});
}
TEST_F(ValidationTest, DeadLoopFail) {
if (m_ver.SkipIRSensitiveTest())
return;
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\loop1.hlsl", "ps_6_0",
{"br i1 %exitcond, label %for.end.loopexit, label %for.body, !llvm.loop "
"!([0-9]+)",
"?%add(\\.lcssa)? = phi float \\[ %add, %for.body \\]",
"!dx.entryPoints = !\\{!([0-9]+)\\}",
"\\[ %add(\\.lcssa)?, %for.end.loopexit \\]"},
{"br label %for.body", "",
"!dx.entryPoints = !\\{!\\1\\}\n!dx.unused = !\\{!\\1\\}",
"[ 0.000000e+00, %for.end.loopexit ]"},
{
"Loop must have break",
"Named metadata 'dx.unused' is unknown",
},
/*bRegex*/ true);
}
TEST_F(ValidationTest, EvalFail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\eval.hlsl", "ps_6_0",
"!\"A\", i8 9, i8 0, !([0-9]+), i8 2, i32 1, i8 4",
"!\"A\", i8 9, i8 0, !\\1, i8 0, i32 1, i8 4",
"Interpolation mode on A used with eval_\\* instruction must be ",
/*bRegex*/ true);
}
TEST_F(ValidationTest, GetDimCalcLODFail) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\GetDimCalcLOD.hlsl", "ps_6_0",
{"extractvalue %dx.types.Dimensions %([0-9]+), 1",
"float 1.000000e\\+00, i1 true"},
{"extractvalue %dx.types.Dimensions %\\1, 2", "float undef, i1 true"},
{"GetDimensions used undef dimension z on TextureCube",
"coord uninitialized"},
/*bRegex*/ true);
}
TEST_F(ValidationTest, HsAttributeFail) {
if (m_ver.SkipDxilVersion(1, 8))
return;
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\hsAttribute.hlsl", "hs_6_0",
{"i32 3, i32 3, i32 2, i32 3, i32 3, float 6.400000e+01"},
{"i32 36, i32 36, i32 0, i32 0, i32 0, float 6.500000e+01"},
{"HS input control point count must be [0..32]. 36 specified",
"Invalid Tessellator Domain specified. Must be isoline, tri or quad",
"Invalid Tessellator Partitioning specified",
"Invalid Tessellator Output Primitive specified",
"Hull Shader MaxTessFactor must be [1.000000..64.000000]. 65.000000 "
"specified",
"output control point count must be [1..32]. 36 specified"});
}
TEST_F(ValidationTest, InnerCoverageFail) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\InnerCoverage2.hlsl", "ps_6_0",
{"dx.op.coverage.i32(i32 91)", "declare i32 @dx.op.coverage.i32(i32)"},
{"dx.op.coverage.i32(i32 91)\n %inner = call i32 "
"@dx.op.innerCoverage.i32(i32 92)",
"declare i32 @dx.op.coverage.i32(i32)\n"
"declare i32 @dx.op.innerCoverage.i32(i32)"},
"InnerCoverage and Coverage are mutually exclusive.");
}
TEST_F(ValidationTest, InterpChangeFail) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\interpChange.hlsl", "ps_6_0",
{"i32 1, i8 0, (.*)}", "?!dx.viewIdState ="},
{"i32 0, i8 2, \\1}", "!1012 ="},
"interpolation mode that differs from another element packed",
/*bRegex*/ true);
}
TEST_F(ValidationTest, InterpOnIntFail) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\interpOnInt2.hlsl", "ps_6_0",
"!\"A\", i8 5, i8 0, !([0-9]+), i8 1",
"!\"A\", i8 5, i8 0, !\\1, i8 2",
"signature element A specifies invalid interpolation "
"mode for integer component type",
/*bRegex*/ true);
}
TEST_F(ValidationTest, InvalidSigCompTyFail) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\abs2.hlsl", "ps_6_0",
"!\"A\", i8 4", "!\"A\", i8 0",
"A specifies unrecognized or invalid component type");
}
TEST_F(ValidationTest, MultiStream2Fail) {
if (m_ver.SkipDxilVersion(1, 7))
return;
// dxilver 1.7 because PSV0 data was incorrectly filled in before this point,
// making this test fail if running against prior validator versions.
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\multiStreamGS.hlsl", "gs_6_0",
"i32 1, i32 12, i32 7, i32 1, i32 1",
"i32 1, i32 12, i32 7, i32 2, i32 1",
"Multiple GS output streams are used but 'XXX' is not pointlist");
}
TEST_F(ValidationTest, PhiTGSMFail) {
if (m_ver.SkipIRSensitiveTest())
return;
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\phiTGSM.hlsl", "cs_6_0", "ret void",
"%arrayPhi = phi i32 addrspace(3)* [ %arrayidx, %if.then ], [ "
"%arrayidx2, %if.else ]\n"
"%phiAtom = atomicrmw add i32 addrspace(3)* %arrayPhi, i32 1 seq_cst\n"
"ret void",
"TGSM pointers must originate from an unambiguous TGSM global variable");
}
TEST_F(ValidationTest, QuadOpInVS) {
if (m_ver.SkipDxilVersion(1, 5))
return;
RewriteAssemblyCheckMsg(
"struct PerThreadData { int "
"input; int output; }; RWStructuredBuffer<PerThreadData> g_sb; "
"void main(uint vid : SV_VertexID)"
"{ g_sb[vid].output = WaveActiveBitAnd((uint)g_sb[vid].input); }",
"vs_6_0",
{"@dx.op.waveActiveBit.i32(i32 120",
"declare i32 @dx.op.waveActiveBit.i32(i32, i32, i8)"},
{"@dx.op.quadOp.i32(i32 123",
"declare i32 @dx.op.quadOp.i32(i32, i32, i8)"},
"QuadOp not valid in shader model vs_6_0");
}
TEST_F(ValidationTest, ReducibleFail) {
if (m_ver.SkipIRSensitiveTest())
return;
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\reducible.hlsl", "ps_6_0",
{"%conv\n"
" br label %if.end",
"to float\n"
" br label %if.end"},
{"%conv\n"
" br i1 %cmp, label %if.else, label %if.end",
"to float\n"
" br i1 %cmp, label %if.then, label %if.end"},
"Execution flow must be reducible");
}
TEST_F(ValidationTest, SampleBiasFail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\sampleBias.hlsl", "ps_6_0", {"float -1.600000e+01"},
{"float 1.800000e+01"},
"bias amount for sample_b must be in the range [-16.000000,15.990000]");
}
TEST_F(ValidationTest, SamplerKindFail) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\SamplerKind.hlsl", "ps_6_0",
{
"uav1_UAV_2d = call %dx.types.Handle "
"@dx.op.createHandle(i32 57, i8 1",
"g_txDiffuse_texture_2d = call %dx.types.Handle "
"@dx.op.createHandle(i32 57, i8 0",
"\"g_samLinear\", i32 0, i32 0, i32 1, i32 0",
"\"g_samLinearC\", i32 0, i32 1, i32 1, i32 1",
},
{
"uav1_UAV_2d = call %dx.types.Handle "
"@dx.op.createHandle(i32 57, i8 0",
"g_txDiffuse_texture_2d = call %dx.types.Handle "
"@dx.op.createHandle(i32 57, i8 1",
"\"g_samLinear\", i32 0, i32 0, i32 1, i32 3",
"\"g_samLinearC\", i32 0, i32 1, i32 1, i32 3",
},
{"Invalid sampler mode",
"require sampler declared in comparison mode",
"requires sampler declared in default mode",
// 1.4: "should", 1.5: "should be "
"on srv resource"});
}
TEST_F(ValidationTest, SemaOverlapFail) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\semaOverlap1.hlsl", "ps_6_0",
{
"!\\{i32 0, !\"A\", i8 9, i8 0, !([0-9]+), i8 2, "
"i32 1, i8 4, i32 0, i8 0, (.*)"
"!\\{i32 1, !\"A\", i8 9, i8 0, !([0-9]+)",
},
{
"!\\{i32 0, !\"A\", i8 9, i8 0, !\\1, i8 2, i32 "
"1, i8 4, i32 0, i8 0, \\2"
"!\\{i32 1, !\"A\", i8 9, i8 0, !\\1",
},
{"Semantic 'A' overlap at 0"},
/*bRegex*/ true);
}
TEST_F(ValidationTest, SigOutOfRangeFail) {
return; // Skip for now since this fails AssembleToContainer in PSV creation
// due to out of range start row
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\semaOverlap1.hlsl", "ps_6_0",
{
"i32 1, i8 0, null}",
},
{
"i32 8000, i8 0, null}",
},
{"signature element A at location (8000,0) size (1,4) is out of range"});
}
TEST_F(ValidationTest, SigOverlapFail) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\semaOverlap1.hlsl", "ps_6_0",
{"i8 2, i32 1, i8 4, i32 1, i8 0,", "?!dx.viewIdState ="},
{"i8 2, i32 1, i8 4, i32 0, i8 0,", "!1012 ="},
{"signature element A at location (0,0) size (1,4) overlaps another "
"signature element"});
}
TEST_F(ValidationTest, SimpleHs1Fail) {
if (m_ver.SkipDxilVersion(1, 8))
return;
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\SimpleHs1.hlsl", "hs_6_0",
{
"i32 3, i32 3, i32 2, i32 3, i32 3, float 6.400000e+01}",
"\"SV_TessFactor\", i8 9, i8 25",
"\"SV_InsideTessFactor\", i8 9, i8 26",
},
{
"i32 3, i32 3000, i32 2, i32 3, i32 3, float 6.400000e+01}",
"\"TessFactor\", i8 9, i8 0",
"\"InsideTessFactor\", i8 9, i8 0",
},
{
"output control point count must be [1..32]. 3000 specified",
"Required TessFactor for domain not found declared anywhere in Patch "
"Constant data",
// TODO: enable this after support pass thru hull shader.
//"For pass thru hull shader, input control point count must match
// output control point count", "Total number of scalars across all HS
// output control points must not exceed",
});
}
TEST_F(ValidationTest, SimpleHs3Fail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\SimpleHs3.hlsl", "hs_6_0",
{
"i32 3, i32 3, i32 2, i32 3, i32 3, float 6.400000e+01}",
},
{
"i32 3, i32 3, i32 2, i32 3, i32 2, float 6.400000e+01}",
},
{"Hull Shader declared with Tri Domain must specify output primitive "
"point, triangle_cw or triangle_ccw. Line output is not compatible with "
"the Tri domain"});
}
TEST_F(ValidationTest, SimpleHs4Fail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\SimpleHs4.hlsl", "hs_6_0",
{
"i32 2, i32 2, i32 1, i32 3, i32 2, float 6.400000e+01}",
},
{
"i32 2, i32 2, i32 1, i32 3, i32 3, float 6.400000e+01}",
},
{"Hull Shader declared with IsoLine Domain must specify output primitive "
"point or line. Triangle_cw or triangle_ccw output are not compatible "
"with the IsoLine Domain"});
}
TEST_F(ValidationTest, SimpleDs1Fail) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\SimpleDs1.hlsl", "ds_6_0", {"!{i32 2, i32 3}"},
{"!{i32 4, i32 36}"},
{"DS input control point count must be [0..32]. 36 specified",
"Invalid Tessellator Domain specified. Must be isoline, tri or quad",
"DomainLocation component index out of bounds for the domain"});
}
TEST_F(ValidationTest, SimpleGs1Fail) {
return; // Skip for now since this fails AssembleToContainer in PSV creation
// due to out of range stream index
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\SimpleGS1.hlsl", "gs_6_0",
{"!{i32 1, i32 3, i32 1, i32 5, i32 1}",
"i8 4, i32 1, i8 4, i32 2, i8 0, null}"},
{"!{i32 5, i32 1025, i32 1, i32 0, i32 33}",
"i8 4, i32 1, i8 4, i32 2, i8 0, !100}\n"
"!100 = !{i32 0, i32 5}"},
{"GS output vertex count must be [0..1024]. 1025 specified",
"GS instance count must be [1..32]. 33 specified",
"GS output primitive topology unrecognized",
"GS input primitive unrecognized",
"Stream index (5) must between 0 and 3"});
}
TEST_F(ValidationTest, UavBarrierFail) {
if (m_ver.SkipIRSensitiveTest())
return;
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\uavBarrier.hlsl", "ps_6_0",
{
"dx.op.barrier(i32 80, i32 2)",
"textureLoad.f32(i32 66, %dx.types.Handle %uav1_UAV_2d, i32 undef",
"i32 undef, i32 undef, i32 undef, i32 undef)",
"float %add9.i3, i8 15)",
},
{
"dx.op.barrier(i32 80, i32 9)",
"textureLoad.f32(i32 66, %dx.types.Handle %uav1_UAV_2d, i32 1",
"i32 1, i32 2, i32 undef, i32 undef)",
"float undef, i8 7)",
},
{"uav load don't support offset",
"uav load don't support mipLevel/sampleIndex",
"store on typed uav must write to all four components of the UAV",
"sync in a non-", // 1.4: "Compute" 1.5: "Compute/Amplification/Mesh"
" Shader must only sync UAV (sync_uglobal)"});
}
TEST_F(ValidationTest, UndefValueFail) {
TestCheck(L"..\\CodeGenHLSL\\UndefValue.hlsl");
}
TEST_F(ValidationTest, UpdateCounterFail) {
if (m_ver.SkipIRSensitiveTest())
return;
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\updateCounter2.hlsl", "ps_6_0",
{"%2 = call i32 @dx.op.bufferUpdateCounter(i32 70, %dx.types.Handle "
"%buf2_UAV_structbuf, i8 1)",
"%3 = call i32 @dx.op.bufferUpdateCounter(i32 70, %dx.types.Handle "
"%buf2_UAV_structbuf, i8 1)"},
{"%2 = call i32 @dx.op.bufferUpdateCounter(i32 70, %dx.types.Handle "
"%buf2_UAV_structbuf, i8 -1)",
"%3 = call i32 @dx.op.bufferUpdateCounter(i32 70, %dx.types.Handle "
"%buf2_UAV_structbuf, i8 1)\n"
"%srvUpdate = call i32 @dx.op.bufferUpdateCounter(i32 70, "
"%dx.types.Handle %buf1_texture_buf, i8 undef)"},
{"BufferUpdateCounter valid only on UAV",
"BufferUpdateCounter valid only on structured buffers",
"inc of BufferUpdateCounter must be an immediate constant",
"RWStructuredBuffers may increment or decrement their counters, but not "
"both"});
}
TEST_F(ValidationTest, LocalResCopy) {
// error updated, so must exclude previous validator versions.
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\resCopy.hlsl", "cs_6_0", {"ret void"},
{"%H = alloca %dx.types.ResRet.i32\n"
"ret void"},
{"Dxil struct types should only be used by ExtractValue"});
}
TEST_F(ValidationTest, WhenIncorrectModelThenFail) {
TestCheck(L"..\\CodeGenHLSL\\val-failures.hlsl");
}
TEST_F(ValidationTest, WhenIncorrectPSThenFail) {
TestCheck(L"..\\CodeGenHLSL\\val-failures-ps.hlsl");
}
TEST_F(ValidationTest, WhenSmUnknownThenFail) {
RewriteAssemblyCheckMsg("float4 main() : SV_Target { return 1; }", "ps_6_0",
{"{!\"ps\", i32 6, i32 0}"},
{"{!\"ps\", i32 1, i32 2}"},
"Unknown shader model 'ps_1_2'");
}
TEST_F(ValidationTest, WhenSmLegacyThenFail) {
RewriteAssemblyCheckMsg("float4 main() : SV_Target { return 1; }", "ps_6_0",
"{!\"ps\", i32 6, i32 0}", "{!\"ps\", i32 5, i32 1}",
"Unknown shader model 'ps_5_1'");
}
TEST_F(ValidationTest, WhenMetaFlagsUsageDeclThenOK) {
RewriteAssemblyCheckMsg(
"uint u; float4 main() : SV_Target { uint64_t n = u; n *= u; return "
"(uint)(n >> 32); }",
"ps_6_0", "1048576",
"1048577", // inhibit optimization, which should work fine
nullptr);
}
TEST_F(ValidationTest, GsVertexIDOutOfBound) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\SimpleGS1.hlsl", "gs_6_0",
"dx.op.loadInput.f32(i32 4, i32 0, i32 0, i8 2, i32 0)",
"dx.op.loadInput.f32(i32 4, i32 0, i32 0, i8 2, i32 1)",
"expect VertexID between 0~1, got 1");
}
TEST_F(ValidationTest, StreamIDOutOfBound) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleGS1.hlsl", "gs_6_0",
"dx.op.emitStream(i32 97, i8 0)",
"dx.op.emitStream(i32 97, i8 1)",
"expect StreamID between 0 , got 1");
}
TEST_F(ValidationTest, SignatureDataWidth) {
if (m_ver.SkipDxilVersion(1, 2))
return;
std::vector<LPCWSTR> pArguments = {L"-enable-16bit-types", L"-HV", L"2018"};
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\signature_packing_by_width.hlsl", "ps_6_2",
pArguments.data(), 3, nullptr, 0,
{"i8 8, i8 0, (![0-9]+), i8 2, i32 1, i8 2, i32 0, i8 0, null}"},
{"i8 9, i8 0, \\1, i8 2, i32 1, i8 2, i32 0, i8 0, null}"},
"signature element F at location \\(0, 2\\) size \\(1, 2\\) has data "
"width that differs from another element packed into the same row.",
true);
}
TEST_F(ValidationTest, SignatureStreamIDForNonGS) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\abs1.hlsl", "ps_6_0",
{", i8 0, i32 1, i8 4, i32 0, i8 0, [^,]+}", "?!dx.viewIdState ="},
{", i8 0, i32 1, i8 4, i32 0, i8 0, !1019}\n!1019 = !{i32 0, i32 1}",
"!1012 ="},
"Stream index \\(1\\) must between 0 and 0", true);
}
TEST_F(ValidationTest, TypedUAVStoreFullMask0) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\uav_typed_store.hlsl", "ps_6_0",
"float 2.000000e+00, i8 15)",
"float 2.000000e+00, i8 undef)",
"Mask of TextureStore must be an immediate constant");
}
TEST_F(ValidationTest, TypedUAVStoreFullMask1) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\uav_typed_store.hlsl", "ps_6_0",
"float 3.000000e+00, i8 15)",
"float 3.000000e+00, i8 undef)",
"Mask of BufferStore must be an immediate constant");
}
TEST_F(ValidationTest, UAVStoreMaskMatch) {
// error updated, so must exclude previous validator versions.
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\uav_store.hlsl", "ps_6_0",
"i32 2, i8 15)", "i32 2, i8 7)",
"uav store write mask must match store value mask, "
"write mask is 7 and store value mask is 15.");
}
TEST_F(ValidationTest, UAVStoreMaskGap) {
if (m_ver.SkipDxilVersion(1, 7))
return;
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\uav_store.hlsl", "ps_6_0",
"i32 2, i32 2, i32 2, i32 2, i8 15)",
"i32 undef, i32 2, i32 undef, i32 2, i8 10)",
"UAV write mask must be contiguous, starting at x: "
".x, .xy, .xyz, or .xyzw.");
}
TEST_F(ValidationTest, UAVStoreMaskGap2) {
if (m_ver.SkipDxilVersion(1, 7))
return;
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\uav_store.hlsl", "ps_6_0",
"i32 2, i32 2, i32 2, i32 2, i8 15)",
"i32 undef, i32 2, i32 2, i32 2, i8 14)",
"UAV write mask must be contiguous, starting at x: "
".x, .xy, .xyz, or .xyzw.");
}
TEST_F(ValidationTest, UAVStoreMaskGap3) {
if (m_ver.SkipDxilVersion(1, 7))
return;
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\uav_store.hlsl", "ps_6_0",
"i32 2, i32 2, i32 2, i32 2, i8 15)",
"i32 undef, i32 undef, i32 undef, i32 2, i8 8)",
"UAV write mask must be contiguous, starting at x: "
".x, .xy, .xyz, or .xyzw.");
}
TEST_F(ValidationTest, Recursive) {
// Includes coverage for user-defined functions.
TestCheck(L"..\\CodeGenHLSL\\recursive.ll");
}
TEST_F(ValidationTest, ResourceRangeOverlap0) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\resource_overlap.hlsl", "ps_6_0",
"!\"B\", i32 0, i32 1", "!\"B\", i32 0, i32 0",
"Resource B with base 0 size 1 overlap");
}
TEST_F(ValidationTest, ResourceRangeOverlap1) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\resource_overlap.hlsl", "ps_6_0",
"!\"s1\", i32 0, i32 1", "!\"s1\", i32 0, i32 0",
"Resource s1 with base 0 size 1 overlap");
}
TEST_F(ValidationTest, ResourceRangeOverlap2) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\resource_overlap.hlsl", "ps_6_0",
"!\"uav2\", i32 0, i32 0", "!\"uav2\", i32 0, i32 3",
"Resource uav2 with base 3 size 1 overlap");
}
TEST_F(ValidationTest, ResourceRangeOverlap3) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\resource_overlap.hlsl", "ps_6_0",
"!\"srv2\", i32 0, i32 1", "!\"srv2\", i32 0, i32 0",
"Resource srv2 with base 0 size 1 overlap");
}
TEST_F(ValidationTest, CBufferOverlap0) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\cbufferOffset.hlsl", "ps_6_0",
"i32 6, !\"g2\", i32 3, i32 0",
"i32 6, !\"g2\", i32 3, i32 8",
"CBuffer Foo1 has offset overlaps at 16");
}
TEST_F(ValidationTest, CBufferOverlap1) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\cbufferOffset.hlsl", "ps_6_0", " = !{i32 32, !",
" = !{i32 16, !",
"CBuffer Foo1 size insufficient for element at offset 16");
}
TEST_F(ValidationTest, ControlFlowHint) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\if1.hlsl", "ps_6_0",
"!\"dx.controlflow.hints\", i32 1",
"!\"dx.controlflow.hints\", i32 5",
"Attribute forcecase only works for switch");
}
TEST_F(ValidationTest, ControlFlowHint1) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\if1.hlsl", "ps_6_0",
"!\"dx.controlflow.hints\", i32 1",
"!\"dx.controlflow.hints\", i32 1, i32 2",
"Can't use branch and flatten attributes together");
}
TEST_F(ValidationTest, ControlFlowHint2) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\if1.hlsl", "ps_6_0",
"!\"dx.controlflow.hints\", i32 1",
"!\"dx.controlflow.hints\", i32 3",
"Invalid control flow hint");
}
TEST_F(ValidationTest, SemanticLength1) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\binary1.hlsl", "ps_6_0",
"!\"C\"", "!\"\"",
"Semantic length must be at least 1 and at most 64");
}
TEST_F(ValidationTest, SemanticLength64) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\binary1.hlsl", "ps_6_0", "!\"C\"",
"!\"CSESESESESESESESESESESESESESESESESESESESESESESESESESESESESESESESE\"",
"Semantic length must be at least 1 and at most 64");
}
TEST_F(ValidationTest, PullModelPosition) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\eval.hlsl", "ps_6_0",
"!\"A\", i8 9, i8 0", "!\"SV_Position\", i8 9, i8 3",
"does not support pull-model evaluation of position");
}
TEST_F(ValidationTest, StructBufGlobalCoherentAndCounter) {
// error updated, so must exclude previous validator versions.
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\struct_buf1.hlsl", "ps_6_0",
"!\"buf2\", i32 0, i32 0, i32 1, i32 12, i1 false, i1 false",
"!\"buf2\", i32 0, i32 0, i32 1, i32 12, i1 true, i1 true",
"globallycoherent cannot be used with append/consume buffers: 'buf2'");
}
TEST_F(ValidationTest, StructBufStrideAlign) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\struct_buf1.hlsl", "ps_6_0",
"= !{i32 1, i32 52}", "= !{i32 1, i32 50}",
"structured buffer element size must be a multiple "
"of 4 bytes (actual size 50 bytes)");
}
TEST_F(ValidationTest, StructBufStrideOutOfBound) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\struct_buf1.hlsl", "ps_6_0",
"= !{i32 1, i32 52}", "= !{i32 1, i32 2052}",
"structured buffer elements cannot be larger than "
"2048 bytes (actual size 2052 bytes)");
}
TEST_F(ValidationTest, StructBufLoadCoordinates) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\struct_buf1.hlsl", "ps_6_0",
"bufferLoad.f32(i32 68, %dx.types.Handle "
"%buf1_texture_structbuf, i32 1, i32 8)",
"bufferLoad.f32(i32 68, %dx.types.Handle "
"%buf1_texture_structbuf, i32 1, i32 undef)",
"structured buffer require 2 coordinates");
}
TEST_F(ValidationTest, StructBufStoreCoordinates) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\struct_buf1.hlsl", "ps_6_0",
"bufferStore.f32(i32 69, %dx.types.Handle "
"%buf2_UAV_structbuf, i32 0, i32 0",
"bufferStore.f32(i32 69, %dx.types.Handle "
"%buf2_UAV_structbuf, i32 0, i32 undef",
"structured buffer require 2 coordinates");
}
TEST_F(ValidationTest, TypedBufRetType) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\sample5.hlsl", "ps_6_0",
" = type { <4 x float>", " = type { <4 x double>",
"elements of typed buffers and textures must fit in "
"four 32-bit quantities");
}
TEST_F(ValidationTest, VsInputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\clip_planes.hlsl", "vs_6_0",
"!\"POSITION\", i8 9, i8 0",
"!\"SV_Target\", i8 9, i8 16",
"Semantic 'SV_Target' is invalid as vs Input");
}
TEST_F(ValidationTest, VsOutputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\clip_planes.hlsl", "vs_6_0",
"!\"NORMAL\", i8 9, i8 0",
"!\"SV_Target\", i8 9, i8 16",
"Semantic 'SV_Target' is invalid as vs Output");
}
TEST_F(ValidationTest, HsInputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleHs1.hlsl", "hs_6_0",
"!\"TEXCOORD\", i8 9, i8 0",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as hs Input");
}
TEST_F(ValidationTest, HsOutputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleHs1.hlsl", "hs_6_0",
"!\"TEXCOORD\", i8 9, i8 0",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as hs Output");
}
TEST_F(ValidationTest, PatchConstSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleHs1.hlsl", "hs_6_0",
"!\"SV_TessFactor\", i8 9, i8 25",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as hs PatchConstant");
}
TEST_F(ValidationTest, DsInputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleDs1.hlsl", "ds_6_0",
"!\"TEXCOORD\", i8 9, i8 0",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as ds Input");
}
TEST_F(ValidationTest, DsOutputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleDs1.hlsl", "ds_6_0",
"!\"TEXCOORD\", i8 9, i8 0",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as ds Output");
}
TEST_F(ValidationTest, GsInputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleGS1.hlsl", "gs_6_0",
"!\"POSSIZE\", i8 9, i8 0",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as gs Input");
}
TEST_F(ValidationTest, GsOutputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\SimpleGS1.hlsl", "gs_6_0",
"!\"TEXCOORD\", i8 9, i8 0",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as gs Output");
}
TEST_F(ValidationTest, PsInputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\abs2.hlsl", "ps_6_0",
"!\"A\", i8 4, i8 0", "!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as ps Input");
}
TEST_F(ValidationTest, PsOutputSemantic) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\abs2.hlsl", "ps_6_0",
"!\"SV_Target\", i8 9, i8 16",
"!\"VertexID\", i8 4, i8 1",
"Semantic 'VertexID' is invalid as ps Output");
}
TEST_F(ValidationTest, ArrayOfSVTarget) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\targetArray.hlsl", "ps_6_0",
"i32 2, !\"SV_Target\", i8 9, i8 16, !([0-9]+), i8 "
"0, i32 1, i8 4, i32 0, i8 0, (.*)}",
"i32 2, !\"SV_Target\", i8 9, i8 16, !101, i8 0, i32 "
"2, i8 4, i32 0, i8 0, \\2}\n!101 = !{i32 5, i32 6}",
"Pixel shader output registers are not indexable.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, InfiniteLog) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\intrinsic_val_imm.hlsl", "ps_6_0",
"op.unary.f32\\(i32 23, float %[0-9+]\\)",
"op.unary.f32(i32 23, float 0x7FF0000000000000)",
"No indefinite logarithm",
/*bRegex*/ true);
}
TEST_F(ValidationTest, InfiniteAsin) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\intrinsic_val_imm.hlsl", "ps_6_0",
"op.unary.f32\\(i32 16, float %[0-9]+\\)",
"op.unary.f32(i32 16, float 0x7FF0000000000000)",
"No indefinite arcsine",
/*bRegex*/ true);
}
TEST_F(ValidationTest, InfiniteAcos) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\intrinsic_val_imm.hlsl", "ps_6_0",
"op.unary.f32\\(i32 15, float %[0-9]+\\)",
"op.unary.f32(i32 15, float 0x7FF0000000000000)",
"No indefinite arccosine",
/*bRegex*/ true);
}
TEST_F(ValidationTest, InfiniteDdxDdy) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\intrinsic_val_imm.hlsl", "ps_6_0",
"op.unary.f32\\(i32 85, float %[0-9]+\\)",
"op.unary.f32(i32 85, float 0x7FF0000000000000)",
"No indefinite derivative calculation",
/*bRegex*/ true);
}
TEST_F(ValidationTest, IDivByZero) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\intrinsic_val_imm.hlsl", "ps_6_0",
"sdiv i32 %([0-9]+), %[0-9]+", "sdiv i32 %\\1, 0",
"No signed integer division by zero",
/*bRegex*/ true);
}
TEST_F(ValidationTest, UDivByZero) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\intrinsic_val_imm.hlsl", "ps_6_0",
"udiv i32 %([0-9]+), %[0-9]+", "udiv i32 %\\1, 0",
"No unsigned integer division by zero",
/*bRegex*/ true);
}
TEST_F(ValidationTest, UnusedMetadata) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\loop2.hlsl", "ps_6_0",
", !llvm.loop ", ", !llvm.loop2 ",
"All metadata must be used by dxil");
}
TEST_F(ValidationTest, MemoryOutOfBound) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\targetArray.hlsl", "ps_6_0",
"getelementptr [4 x float], [4 x float]* %7, i32 0, i32 3",
"getelementptr [4 x float], [4 x float]* %7, i32 0, i32 10",
"Access to out-of-bounds memory is disallowed");
}
TEST_F(ValidationTest, LocalRes2) {
TestCheck(L"..\\CodeGenHLSL\\local_resource2.hlsl");
}
TEST_F(ValidationTest, LocalRes3) {
TestCheck(L"..\\CodeGenHLSL\\local_resource3.hlsl");
}
TEST_F(ValidationTest, LocalRes5) {
TestCheck(L"..\\CodeGenHLSL\\local_resource5.hlsl");
}
TEST_F(ValidationTest, LocalRes5Dbg) {
TestCheck(L"..\\CodeGenHLSL\\local_resource5_dbg.hlsl");
}
TEST_F(ValidationTest, LocalRes6) {
TestCheck(L"..\\CodeGenHLSL\\local_resource6.hlsl");
}
TEST_F(ValidationTest, LocalRes6Dbg) {
TestCheck(L"..\\CodeGenHLSL\\local_resource6_dbg.hlsl");
}
TEST_F(ValidationTest, AddrSpaceCast) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\staticGlobals.hlsl", "ps_6_0",
"%([0-9]+) = getelementptr \\[4 x i32\\], \\[4 x i32\\]\\* %([0-9]+), "
"i32 0, i32 0\n"
" store i32 %([0-9]+), i32\\* %\\1, align 4",
"%\\1 = getelementptr [4 x i32], [4 x i32]* %\\2, i32 0, i32 0\n"
" %X = addrspacecast i32* %\\1 to i32 addrspace(1)* \n"
" store i32 %\\3, i32 addrspace(1)* %X, align 4",
"generic address space",
/*bRegex*/ true);
}
TEST_F(ValidationTest, PtrBitCast) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\staticGlobals.hlsl", "ps_6_0",
"%([0-9]+) = getelementptr \\[4 x i32\\], \\[4 x i32\\]\\* %([0-9]+), "
"i32 0, i32 0\n"
" store i32 %([0-9]+), i32\\* %\\1, align 4",
"%\\1 = getelementptr [4 x i32], [4 x i32]* %\\2, i32 0, i32 0\n"
" %X = bitcast i32* %\\1 to double* \n"
" store i32 %\\3, i32* %\\1, align 4",
"Pointer type bitcast must be have same size",
/*bRegex*/ true);
}
TEST_F(ValidationTest, MinPrecisionBitCast) {
if (m_ver.SkipDxilVersion(1, 2))
return;
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\staticGlobals.hlsl", "ps_6_0",
"%([0-9]+) = getelementptr \\[4 x i32\\], \\[4 x i32\\]\\* %([0-9]+), "
"i32 0, i32 0\n"
" store i32 %([0-9]+), i32\\* %\\1, align 4",
"%\\1 = getelementptr [4 x i32], [4 x i32]* %\\2, i32 0, i32 0\n"
" %X = bitcast i32* %\\1 to half* \n"
" store i32 %\\3, i32* %\\1, align 4",
"Bitcast on minprecison types is not allowed",
/*bRegex*/ true);
}
TEST_F(ValidationTest, StructBitCast) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\staticGlobals.hlsl", "ps_6_0",
"%([0-9]+) = getelementptr \\[4 x i32\\], \\[4 x i32\\]\\* %([0-9]+), "
"i32 0, i32 0\n"
" store i32 %([0-9]+), i32\\* %\\1, align 4",
"%\\1 = getelementptr [4 x i32], [4 x i32]* %\\2, i32 0, i32 0\n"
" %X = bitcast i32* %\\1 to %dx.types.Handle* \n"
" store i32 %\\3, i32* %\\1, align 4",
"Bitcast on struct types is not allowed",
/*bRegex*/ true);
}
TEST_F(ValidationTest, MultiDimArray) {
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\staticGlobals.hlsl", "ps_6_0",
"= alloca [4 x i32]",
"= alloca [4 x i32]\n"
" %md = alloca [2 x [4 x float]]",
"Only one dimension allowed for array type");
}
TEST_F(ValidationTest, SimpleGs8) {
TestCheck(L"..\\CodeGenHLSL\\SimpleGS8.hlsl");
}
TEST_F(ValidationTest, SimpleGs9) {
TestCheck(L"..\\CodeGenHLSL\\SimpleGS9.hlsl");
}
TEST_F(ValidationTest, SimpleGs10) {
TestCheck(L"..\\CodeGenHLSL\\SimpleGS10.hlsl");
}
TEST_F(ValidationTest, IllegalSampleOffset3) {
TestCheck(L"..\\DXILValidation\\optForNoOpt3.hlsl");
}
TEST_F(ValidationTest, IllegalSampleOffset4) {
TestCheck(L"..\\DXILValidation\\optForNoOpt4.hlsl");
}
TEST_F(ValidationTest, NoFunctionParam) {
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\abs2.hlsl", "ps_6_0",
{"define void @main\\(\\)",
"void \\(\\)\\* @main, !([0-9]+)\\}(.*)!\\1 = !\\{!([0-9]+)\\}",
"void \\(\\)\\* @main"},
{"define void @main(<4 x i32> %mainArg)",
"void (<4 x i32>)* @main, !\\1}\\2!\\1 = !{!\\3, !\\3}",
"void (<4 x i32>)* @main"},
"with parameter is not permitted",
/*bRegex*/ true);
}
TEST_F(ValidationTest, I8Type) {
// error updated, so must exclude previous validator versions.
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\staticGlobals.hlsl", "ps_6_0",
"%([0-9]+) = alloca \\[4 x i32\\]",
"%\\1 = alloca [4 x i32]\n"
" %m8 = alloca i8",
"I8 can only be used as immediate value for intrinsic",
/*bRegex*/ true);
}
TEST_F(ValidationTest, EmptyStructInBuffer) {
TestCheck(L"..\\CodeGenHLSL\\EmptyStructInBuffer.hlsl");
}
TEST_F(ValidationTest, BigStructInBuffer) {
TestCheck(L"..\\CodeGenHLSL\\BigStructInBuffer.hlsl");
}
// TODO: enable this.
// TEST_F(ValidationTest, TGSMRaceCond) {
// TestCheck(L"..\\CodeGenHLSL\\RaceCond.hlsl");
//}
//
// TEST_F(ValidationTest, TGSMRaceCond2) {
// RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\structInBuffer.hlsl", "cs_6_0",
// "ret void",
// "%TID = call i32 @dx.op.flattenedThreadIdInGroup.i32(i32 96)\n"
// "store i32 %TID, i32 addrspace(3)* @\"\\01?sharedData@@3UFoo@@A.3\",
// align 4\n" "ret void", "Race condition writing to shared memory
// detected, consider making this write conditional");
//}
TEST_F(ValidationTest, AddUint64Odd) {
TestCheck(L"..\\CodeGenHLSL\\AddUint64Odd.hlsl");
}
TEST_F(ValidationTest, WhenWaveAffectsGradientThenFail) {
TestCheck(L"..\\CodeGenHLSL\\val-wave-failures-ps.hlsl");
}
TEST_F(ValidationTest, WhenMetaFlagsUsageThenFail) {
RewriteAssemblyCheckMsg("uint u; float4 main() : SV_Target { uint64_t n = u; "
"n *= u; return (uint)(n >> 32); }",
"ps_6_0", "1048576", "0", // remove the int64 flag
"Flags must match usage");
}
TEST_F(ValidationTest, StorePatchControlNotInPatchConstantFunction) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg("struct PSSceneIn \
{ \
float4 pos : SV_Position; \
float2 tex : TEXCOORD0; \
float3 norm : NORMAL; \
}; \
\
struct HSPerVertexData \
{ \
PSSceneIn v; \
}; \
struct HSPerPatchData \
{ \
float edges[ 3 ] : SV_TessFactor; \
float inside : SV_InsideTessFactor; \
}; \
HSPerPatchData HSPerPatchFunc( const InputPatch< PSSceneIn, 3 > points, \
OutputPatch<HSPerVertexData, 3> outpoints) \
{ \
HSPerPatchData d; \
\
d.edges[ 0 ] = points[0].tex.x + outpoints[0].v.tex.x; \
d.edges[ 1 ] = 1; \
d.edges[ 2 ] = 1; \
d.inside = 1; \
\
return d; \
}\
[domain(\"tri\")]\
[partitioning(\"fractional_odd\")]\
[outputtopology(\"triangle_cw\")]\
[patchconstantfunc(\"HSPerPatchFunc\")]\
[outputcontrolpoints(3)]\
HSPerVertexData main( const uint id : SV_OutputControlPointID,\
const InputPatch< PSSceneIn, 3 > points )\
{\
HSPerVertexData v;\
\
v.v = points[ id ];\
\
return v;\
}\
",
"hs_6_0", "dx.op.storeOutput.f32(i32 5",
"dx.op.storePatchConstant.f32(i32 106",
"opcode 'StorePatchConstant' should only be used in "
"'PatchConstant function'");
}
TEST_F(ValidationTest, LoadOutputControlPointNotInPatchConstantFunction) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg("struct PSSceneIn \
{ \
float4 pos : SV_Position; \
float2 tex : TEXCOORD0; \
float3 norm : NORMAL; \
}; \
\
struct HSPerVertexData \
{ \
PSSceneIn v; \
}; \
struct HSPerPatchData \
{ \
float edges[ 3 ] : SV_TessFactor; \
float inside : SV_InsideTessFactor; \
}; \
HSPerPatchData HSPerPatchFunc( const InputPatch< PSSceneIn, 3 > points, \
OutputPatch<HSPerVertexData, 3> outpoints) \
{ \
HSPerPatchData d; \
\
d.edges[ 0 ] = points[0].tex.x + outpoints[0].v.tex.x; \
d.edges[ 1 ] = 1; \
d.edges[ 2 ] = 1; \
d.inside = 1; \
\
return d; \
}\
[domain(\"tri\")]\
[partitioning(\"fractional_odd\")]\
[outputtopology(\"triangle_cw\")]\
[patchconstantfunc(\"HSPerPatchFunc\")]\
[outputcontrolpoints(3)]\
HSPerVertexData main( const uint id : SV_OutputControlPointID,\
const InputPatch< PSSceneIn, 3 > points )\
{\
HSPerVertexData v;\
\
v.v = points[ id ];\
\
return v;\
}\
",
"hs_6_0", "dx.op.loadInput.f32(i32 4",
"dx.op.loadOutputControlPoint.f32(i32 103",
"opcode 'LoadOutputControlPoint' should only be used "
"in 'PatchConstant function'");
}
TEST_F(ValidationTest, OutputControlPointIDInPatchConstantFunction) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct PSSceneIn \
{ \
float4 pos : SV_Position; \
float2 tex : TEXCOORD0; \
float3 norm : NORMAL; \
}; \
\
struct HSPerVertexData \
{ \
PSSceneIn v; \
}; \
struct HSPerPatchData \
{ \
float edges[ 3 ] : SV_TessFactor; \
float inside : SV_InsideTessFactor; \
}; \
HSPerPatchData HSPerPatchFunc( const InputPatch< PSSceneIn, 3 > points, \
OutputPatch<HSPerVertexData, 3> outpoints) \
{ \
HSPerPatchData d; \
\
d.edges[ 0 ] = points[0].tex.x + outpoints[0].v.tex.x; \
d.edges[ 1 ] = 1; \
d.edges[ 2 ] = 1; \
d.inside = 1; \
\
return d; \
}\
[domain(\"tri\")]\
[partitioning(\"fractional_odd\")]\
[outputtopology(\"triangle_cw\")]\
[patchconstantfunc(\"HSPerPatchFunc\")]\
[outputcontrolpoints(3)]\
HSPerVertexData main( const uint id : SV_OutputControlPointID,\
const InputPatch< PSSceneIn, 3 > points )\
{\
HSPerVertexData v;\
\
v.v = points[ id ];\
\
return v;\
}\
",
"hs_6_0", "ret void",
"call i32 @dx.op.outputControlPointID.i32(i32 107)\n ret void",
"opcode 'OutputControlPointID' should only be used in 'hull function'");
}
TEST_F(ValidationTest, ClipCullMaxComponents) {
RewriteAssemblyCheckMsg(" \
struct VSOut { \
float3 clip0 : SV_ClipDistance; \
float3 clip1 : SV_ClipDistance1; \
float cull0 : SV_CullDistance; \
float cull1 : SV_CullDistance1; \
float cull2 : CullDistance2; \
}; \
VSOut main() { \
VSOut Out; \
Out.clip0 = 0.1; \
Out.clip1 = 0.2; \
Out.cull0 = 0.3; \
Out.cull1 = 0.4; \
Out.cull2 = 0.5; \
return Out; \
} \
",
"vs_6_0", "!{i32 4, !\"CullDistance\", i8 9, i8 0,",
"!{i32 4, !\"SV_CullDistance\", i8 9, i8 7,",
"ClipDistance and CullDistance use more than the "
"maximum of 8 components combined.");
}
TEST_F(ValidationTest, ClipCullMaxRows) {
RewriteAssemblyCheckMsg(" \
struct VSOut { \
float3 clip0 : SV_ClipDistance; \
float3 clip1 : SV_ClipDistance1; \
float2 cull0 : CullDistance; \
}; \
VSOut main() { \
VSOut Out; \
Out.clip0 = 0.1; \
Out.clip1 = 0.2; \
Out.cull0 = 0.3; \
return Out; \
} \
",
"vs_6_0", "!{i32 2, !\"CullDistance\", i8 9, i8 0,",
"!{i32 2, !\"SV_CullDistance\", i8 9, i8 7,",
"ClipDistance and CullDistance occupy more than the "
"maximum of 2 rows combined.");
}
TEST_F(ValidationTest, DuplicateSysValue) {
RewriteAssemblyCheckMsg(" \
float4 main(uint vid : SV_VertexID, uint iid : SV_InstanceID) : SV_Position { \
return (float4)0 + vid + iid; \
} \
",
"vs_6_0", "!{i32 1, !\"SV_InstanceID\", i8 5, i8 2,",
"!{i32 1, !\"\", i8 5, i8 1,",
//"System value SV_VertexID appears more than once in
// the same signature.");
"Semantic 'SV_VertexID' overlap at 0");
}
TEST_F(ValidationTest, SemTargetMax) {
RewriteAssemblyCheckMsg(" \
float4 main(float4 col : COLOR) : SV_Target7 { return col; } \
",
"ps_6_0",
{"!{i32 0, !\"SV_Target\", i8 9, i8 16, ![0-9]+, i8 "
"0, i32 1, i8 4, i32 7, i8 0, (.*)}",
"?!dx.viewIdState ="},
{"!{i32 0, !\"SV_Target\", i8 9, i8 16, !101, i8 0, "
"i32 1, i8 4, i32 8, i8 0, \\1}\n!101 = !{i32 8}",
"!1012 ="},
"SV_Target semantic index exceeds maximum \\(7\\)",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemTargetIndexMatchesRow) {
RewriteAssemblyCheckMsg(
" \
float4 main(float4 col : COLOR) : SV_Target7 { return col; } \
",
"ps_6_0",
{"!{i32 0, !\"SV_Target\", i8 9, i8 16, !([0-9]+), i8 0, i32 1, i8 4, "
"i32 7, i8 0, (.*)}",
"?!dx.viewIdState ="},
{"!{i32 0, !\"SV_Target\", i8 9, i8 16, !\\1, i8 0, i32 1, i8 4, i32 6, "
"i8 0, \\2}",
"!1012 ="},
"SV_Target semantic index must match packed row location",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemTargetCol0) {
RewriteAssemblyCheckMsg(" \
float3 main(float4 col : COLOR) : SV_Target7 { return col.xyz; } \
",
"ps_6_0",
"!{i32 0, !\"SV_Target\", i8 9, i8 16, !([0-9]+), i8 "
"0, i32 1, i8 3, i32 7, i8 0, (.*)}",
"!{i32 0, !\"SV_Target\", i8 9, i8 16, !\\1, i8 0, "
"i32 1, i8 3, i32 7, i8 1, \\2}",
"SV_Target packed location must start at column 0",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemIndexMax) {
RewriteAssemblyCheckMsg(" \
float4 main(uint vid : SV_VertexID, uint iid : SV_InstanceID) : SV_Position { \
return (float4)0 + vid + iid; \
} \
",
"vs_6_0",
"!{i32 0, !\"SV_VertexID\", i8 5, i8 1, ![0-9]+, i8 "
"0, i32 1, i8 1, i32 0, i8 0, (.*)}",
"!{i32 0, !\"SV_VertexID\", i8 5, i8 1, !101, i8 0, "
"i32 1, i8 1, i32 0, i8 0, \\1}\n!101 = !{i32 1}",
"SV_VertexID semantic index exceeds maximum \\(0\\)",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemTessFactorIndexMax) {
RewriteAssemblyCheckMsg(
" \
struct Vertex { \
float4 pos : SV_Position; \
}; \
struct PatchConstant { \
float edges[ 3 ] : SV_TessFactor; \
float inside : SV_InsideTessFactor; \
}; \
PatchConstant PCMain( InputPatch<Vertex, 3> patch) { \
PatchConstant PC; \
PC.edges = (float[3])patch[1].pos.xyz; \
PC.inside = patch[1].pos.w; \
return PC; \
} \
[domain(\"tri\")] \
[partitioning(\"fractional_odd\")] \
[outputtopology(\"triangle_cw\")] \
[patchconstantfunc(\"PCMain\")] \
[outputcontrolpoints(3)] \
Vertex main(uint id : SV_OutputControlPointID, InputPatch< Vertex, 3 > patch) { \
Vertex Out = patch[id]; \
Out.pos.w += 0.25; \
return Out; \
} \
",
"hs_6_0",
"!{i32 0, !\"SV_TessFactor\", i8 9, i8 25, ![0-9]+, i8 0, i32 3, i8 1, "
"i32 0, i8 3, (.*)}",
"!{i32 0, !\"SV_TessFactor\", i8 9, i8 25, !101, i8 0, i32 2, i8 1, i32 "
"0, i8 3, \\1}\n!101 = !{i32 0, i32 1}",
"TessFactor rows, columns \\(2, 1\\) invalid for domain Tri. Expected 3 "
"rows and 1 column.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemInsideTessFactorIndexMax) {
RewriteAssemblyCheckMsg(
" \
struct Vertex { \
float4 pos : SV_Position; \
}; \
struct PatchConstant { \
float edges[ 3 ] : SV_TessFactor; \
float inside : SV_InsideTessFactor; \
}; \
PatchConstant PCMain( InputPatch<Vertex, 3> patch) { \
PatchConstant PC; \
PC.edges = (float[3])patch[1].pos.xyz; \
PC.inside = patch[1].pos.w; \
return PC; \
} \
[domain(\"tri\")] \
[partitioning(\"fractional_odd\")] \
[outputtopology(\"triangle_cw\")] \
[patchconstantfunc(\"PCMain\")] \
[outputcontrolpoints(3)] \
Vertex main(uint id : SV_OutputControlPointID, InputPatch< Vertex, 3 > patch) { \
Vertex Out = patch[id]; \
Out.pos.w += 0.25; \
return Out; \
} \
",
"hs_6_0",
{"!{i32 1, !\"SV_InsideTessFactor\", i8 9, i8 26, !([0-9]+), i8 0, i32 "
"1, i8 1, i32 3, i8 0, (.*)}",
"?!dx.viewIdState ="},
{"!{i32 1, !\"SV_InsideTessFactor\", i8 9, i8 26, !101, i8 0, i32 2, i8 "
"1, i32 3, i8 0, \\2}\n!101 = !{i32 0, i32 1}",
"!1012 ="},
"InsideTessFactor rows, columns \\(2, 1\\) invalid for domain Tri. "
"Expected 1 rows and 1 column.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemShouldBeAllocated) {
RewriteAssemblyCheckMsg(" \
struct Vertex { \
float4 pos : SV_Position; \
}; \
struct PatchConstant { \
float edges[ 3 ] : SV_TessFactor; \
float inside : SV_InsideTessFactor; \
}; \
PatchConstant PCMain( InputPatch<Vertex, 3> patch) { \
PatchConstant PC; \
PC.edges = (float[3])patch[1].pos.xyz; \
PC.inside = patch[1].pos.w; \
return PC; \
} \
[domain(\"tri\")] \
[partitioning(\"fractional_odd\")] \
[outputtopology(\"triangle_cw\")] \
[patchconstantfunc(\"PCMain\")] \
[outputcontrolpoints(3)] \
Vertex main(uint id : SV_OutputControlPointID, InputPatch< Vertex, 3 > patch) { \
Vertex Out = patch[id]; \
Out.pos.w += 0.25; \
return Out; \
} \
",
"hs_6_0",
"!{i32 0, !\"SV_TessFactor\", i8 9, i8 25, "
"!([0-9]+), i8 0, i32 3, i8 1, i32 0, i8 3, (.*)}",
"!{i32 0, !\"SV_TessFactor\", i8 9, i8 25, !\\1, i8 "
"0, i32 3, i8 1, i32 -1, i8 -1, \\2}",
"PatchConstant Semantic 'SV_TessFactor' should have "
"a valid packing location",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemShouldNotBeAllocated) {
RewriteAssemblyCheckMsg(
" \
float4 main(float4 col : COLOR, out uint coverage : SV_Coverage) : SV_Target7 { coverage = 7; return col; } \
",
"ps_6_0",
"!\"SV_Coverage\", i8 5, i8 14, !([0-9]+), i8 0, i32 1, i8 1, i32 -1, i8 "
"-1, (.*)}",
"!\"SV_Coverage\", i8 5, i8 14, !\\1, i8 0, i32 1, i8 1, i32 2, i8 0, "
"\\2}",
"Output Semantic 'SV_Coverage' should have a packing location of -1",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemComponentOrder) {
// error updated, so must exclude previous validator versions.
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(
" \
void main( \
float2 f2in : f2in, \
float3 f3in : f3in, \
uint vid : SV_VertexID, \
uint iid : SV_InstanceID, \
out float4 pos : SV_Position, \
out float2 f2out : f2out, \
out float3 f3out : f3out, \
out float2 ClipDistance : SV_ClipDistance, \
out float CullDistance : SV_CullDistance) \
{ \
pos = float4(f3in, f2in.x); \
ClipDistance = f2in.x; \
CullDistance = f2in.y; \
} \
",
"vs_6_0",
{"= !{i32 1, !\"f2out\", i8 9, i8 0, !([0-9]+), i8 2, i32 1, i8 2, i32 "
"1, i8 0, (.*)}\n"
"!([0-9]+) = !{i32 2, !\"f3out\", i8 9, i8 0, !([0-9]+), i8 2, i32 1, "
"i8 3, i32 2, i8 0, (.*)}\n"
"!([0-9]+) = !{i32 3, !\"SV_ClipDistance\", i8 9, i8 6, !([0-9]+), i8 "
"2, i32 1, i8 2, i32 3, i8 0, (.*)}\n"
"!([0-9]+) = !{i32 4, !\"SV_CullDistance\", i8 9, i8 7, !([0-9]+), i8 "
"2, i32 1, i8 1, i32 3, i8 2, (.*)}\n",
"?!dx.viewIdState ="},
{"= !{i32 1, !\"f2out\", i8 9, i8 0, !\\1, i8 2, i32 1, i8 2, i32 1, i8 "
"2, \\2}\n"
"!\\3 = !{i32 2, !\"f3out\", i8 9, i8 0, !\\4, i8 2, i32 1, i8 3, i32 "
"2, i8 1, \\5}\n"
"!\\6 = !{i32 3, !\"SV_ClipDistance\", i8 9, i8 6, !\\7, i8 2, i32 1, "
"i8 2, i32 2, i8 0, \\8}\n"
"!\\9 = !{i32 4, !\"SV_CullDistance\", i8 9, i8 7, !\\10, i8 2, i32 1, "
"i8 1, i32 1, i8 0, \\11}\n",
"!1012 ="},
{"signature element SV_ClipDistance at location \\(2,0\\) size \\(1,2\\) "
"violates component ordering rule \\(arb < sv < sgv\\).",
"signature element SV_CullDistance at location \\(1,0\\) size \\(1,1\\) "
"violates component ordering rule \\(arb < sv < sgv\\)."},
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemComponentOrder2) {
// error updated, so must exclude previous validator versions.
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(
" \
float4 main( \
float4 col : Color, \
uint2 val : Value, \
uint pid : SV_PrimitiveID, \
bool ff : SV_IsFrontFace) : SV_Target \
{ \
return col; \
} \
",
"ps_6_0",
"= !{i32 1, !\"Value\", i8 5, i8 0, !([0-9]+), i8 1, i32 1, i8 2, i32 1, "
"i8 0, null}\n"
"!([0-9]+) = !{i32 2, !\"SV_PrimitiveID\", i8 5, i8 10, !([0-9]+), i8 1, "
"i32 1, i8 1, i32 1, i8 2, null}\n"
"!([0-9]+) = !{i32 3, !\"SV_IsFrontFace\", i8 ([15]), i8 13, !([0-9]+), "
"i8 1, i32 1, i8 1, i32 1, i8 3, null}\n",
"= !{i32 1, !\"Value\", i8 5, i8 0, !\\1, i8 1, i32 1, i8 2, i32 1, i8 "
"2, null}\n"
"!\\2 = !{i32 2, !\"SV_PrimitiveID\", i8 5, i8 10, !\\3, i8 1, i32 1, i8 "
"1, i32 1, i8 0, null}\n"
"!\\4 = !{i32 3, !\"SV_IsFrontFace\", i8 \\5, i8 13, !\\6, i8 1, i32 1, "
"i8 1, i32 1, i8 1, null}\n",
{"signature element SV_PrimitiveID at location \\(1,0\\) size \\(1,1\\) "
"violates component ordering rule \\(arb < sv < sgv\\).",
"signature element SV_IsFrontFace at location \\(1,1\\) size \\(1,1\\) "
"violates component ordering rule \\(arb < sv < sgv\\)."},
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemComponentOrder3) {
// error updated, so must exclude previous validator versions.
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(
" \
float4 main( \
float4 col : Color, \
uint val : Value, \
uint pid : SV_PrimitiveID, \
bool ff : SV_IsFrontFace, \
uint vpid : ViewPortArrayIndex) : SV_Target \
{ \
return col; \
} \
",
"ps_6_0",
{"= !{i32 1, !\"Value\", i8 5, i8 0, !([0-9]+), i8 1, i32 1, i8 1, i32 "
"1, i8 0, null}\n"
"!([0-9]+) = !{i32 2, !\"SV_PrimitiveID\", i8 5, i8 10, !([0-9]+), i8 "
"1, i32 1, i8 1, i32 1, i8 1, null}\n"
"!([0-9]+) = !{i32 3, !\"SV_IsFrontFace\", i8 ([15]), i8 13, !([0-9]+), "
"i8 1, i32 1, i8 1, i32 1, i8 2, null}\n"
"!([0-9]+) = !{i32 4, !\"ViewPortArrayIndex\", i8 5, i8 0, !([0-9]+), "
"i8 1, i32 1, i8 1, i32 2, i8 0, null}\n",
"?!dx.viewIdState ="},
{"= !{i32 1, !\"Value\", i8 5, i8 0, !\\1, i8 1, i32 1, i8 1, i32 1, i8 "
"1, null}\n"
"!\\2 = !{i32 2, !\"SV_PrimitiveID\", i8 5, i8 10, !\\3, i8 1, i32 1, "
"i8 1, i32 1, i8 0, null}\n"
"!\\4 = !{i32 3, !\"SV_IsFrontFace\", i8 \\5, i8 13, !\\6, i8 1, i32 1, "
"i8 1, i32 1, i8 2, null}\n"
"!\\7 = !{i32 4, !\"ViewPortArrayIndex\", i8 5, i8 0, !\\8, i8 1, i32 "
"1, i8 1, i32 1, i8 3, null}\n",
"!1012 ="},
{"signature element SV_PrimitiveID at location \\(1,0\\) size \\(1,1\\) "
"violates component ordering rule \\(arb < sv < sgv\\).",
"signature element ViewPortArrayIndex at location \\(1,3\\) size "
"\\(1,1\\) violates component ordering rule \\(arb < sv < sgv\\)."},
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemIndexConflictArbSV) {
RewriteAssemblyCheckMsg(
" \
void main( \
float4 inpos : Position, \
uint iid : SV_InstanceID, \
out float4 pos : SV_Position, \
out uint id[2] : Array, \
out uint vpid : SV_ViewPortArrayIndex, \
out float2 ClipDistance : SV_ClipDistance, \
out float CullDistance : SV_CullDistance) \
{ \
pos = inpos; \
ClipDistance = inpos.x; \
CullDistance = inpos.y; \
vpid = iid; \
id[0] = iid; \
id[1] = iid + 1; \
} \
",
"vs_6_0",
"!{i32 2, !\"SV_ViewportArrayIndex\", i8 5, i8 5, !([0-9]+), i8 1, i32 "
"1, i8 1, i32 3, i8 0, (.*)}",
"!{i32 2, !\"SV_ViewportArrayIndex\", i8 5, i8 5, !\\1, i8 1, i32 1, i8 "
"1, i32 1, i8 3, \\2}",
"signature element SV_ViewportArrayIndex at location \\(1,3\\) size "
"\\(1,1\\) has an indexing conflict with another signature element "
"packed into the same row.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemIndexConflictTessfactors) {
RewriteAssemblyCheckMsg(
" \
struct Vertex { \
float4 pos : SV_Position; \
}; \
struct PatchConstant { \
float edges[ 4 ] : SV_TessFactor; \
float inside[ 2 ] : SV_InsideTessFactor; \
}; \
PatchConstant PCMain( InputPatch<Vertex, 4> patch) { \
PatchConstant PC; \
PC.edges = (float[4])patch[1].pos; \
PC.inside = (float[2])patch[1].pos.xy; \
return PC; \
} \
[domain(\"quad\")] \
[partitioning(\"fractional_odd\")] \
[outputtopology(\"triangle_cw\")] \
[patchconstantfunc(\"PCMain\")] \
[outputcontrolpoints(4)] \
Vertex main(uint id : SV_OutputControlPointID, InputPatch< Vertex, 4 > patch) { \
Vertex Out = patch[id]; \
Out.pos.w += 0.25; \
return Out; \
} \
",
"hs_6_0",
//!{i32 0, !"SV_TessFactor", i8 9, i8 25, !23, i8 0, i32 4, i8 1, i32 0,
//! i8 3, null}
{"!{i32 1, !\"SV_InsideTessFactor\", i8 9, i8 26, !([0-9]+), i8 0, i32 "
"2, i8 1, i32 4, i8 3, (.*)}",
"?!dx.viewIdState ="},
{"!{i32 1, !\"SV_InsideTessFactor\", i8 9, i8 26, !\\1, i8 0, i32 2, i8 "
"1, i32 0, i8 2, \\2}",
"!1012 ="},
"signature element SV_InsideTessFactor at location \\(0,2\\) size "
"\\(2,1\\) has an indexing conflict with another signature element "
"packed into the same row.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemIndexConflictTessfactors2) {
RewriteAssemblyCheckMsg(" \
struct Vertex { \
float4 pos : SV_Position; \
}; \
struct PatchConstant { \
float edges[ 4 ] : SV_TessFactor; \
float inside[ 2 ] : SV_InsideTessFactor; \
float arb [ 3 ] : Arb; \
}; \
PatchConstant PCMain( InputPatch<Vertex, 4> patch) { \
PatchConstant PC; \
PC.edges = (float[4])patch[1].pos; \
PC.inside = (float[2])patch[1].pos.xy; \
PC.arb[0] = 1; PC.arb[1] = 2; PC.arb[2] = 3; \
return PC; \
} \
[domain(\"quad\")] \
[partitioning(\"fractional_odd\")] \
[outputtopology(\"triangle_cw\")] \
[patchconstantfunc(\"PCMain\")] \
[outputcontrolpoints(4)] \
Vertex main(uint id : SV_OutputControlPointID, InputPatch< Vertex, 4 > patch) { \
Vertex Out = patch[id]; \
Out.pos.w += 0.25; \
return Out; \
} \
",
"hs_6_0",
"!{i32 2, !\"Arb\", i8 9, i8 0, !([0-9]+), i8 0, i32 "
"3, i8 1, i32 0, i8 0, (.*)}",
"!{i32 2, !\"Arb\", i8 9, i8 0, !\\1, i8 0, i32 3, "
"i8 1, i32 2, i8 0, \\2}",
"signature element Arb at location \\(2,0\\) size "
"\\(3,1\\) has an indexing conflict with another "
"signature element packed into the same row.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemRowOutOfRange) {
RewriteAssemblyCheckMsg(" \
struct Vertex { \
float4 pos : SV_Position; \
}; \
struct PatchConstant { \
float edges[ 4 ] : SV_TessFactor; \
float inside[ 2 ] : SV_InsideTessFactor; \
float arb [ 3 ] : Arb; \
}; \
PatchConstant PCMain( InputPatch<Vertex, 4> patch) { \
PatchConstant PC; \
PC.edges = (float[4])patch[1].pos; \
PC.inside = (float[2])patch[1].pos.xy; \
PC.arb[0] = 1; PC.arb[1] = 2; PC.arb[2] = 3; \
return PC; \
} \
[domain(\"quad\")] \
[partitioning(\"fractional_odd\")] \
[outputtopology(\"triangle_cw\")] \
[patchconstantfunc(\"PCMain\")] \
[outputcontrolpoints(4)] \
Vertex main(uint id : SV_OutputControlPointID, InputPatch< Vertex, 4 > patch) { \
Vertex Out = patch[id]; \
Out.pos.w += 0.25; \
return Out; \
} \
",
"hs_6_0",
{"!{i32 2, !\"Arb\", i8 9, i8 0, !([0-9]+), i8 0, "
"i32 3, i8 1, i32 0, i8 0, (.*)}",
"?!dx.viewIdState ="},
{"!{i32 2, !\"Arb\", i8 9, i8 0, !\\1, i8 0, i32 3, "
"i8 1, i32 31, i8 0, \\2}",
"!1012 ="},
"signature element Arb at location \\(31,0\\) size "
"\\(3,1\\) is out of range.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemPackOverlap) {
RewriteAssemblyCheckMsg(" \
struct Vertex { \
float4 pos : SV_Position; \
}; \
struct PatchConstant { \
float edges[ 4 ] : SV_TessFactor; \
float inside[ 2 ] : SV_InsideTessFactor; \
float arb [ 3 ] : Arb; \
}; \
PatchConstant PCMain( InputPatch<Vertex, 4> patch) { \
PatchConstant PC; \
PC.edges = (float[4])patch[1].pos; \
PC.inside = (float[2])patch[1].pos.xy; \
PC.arb[0] = 1; PC.arb[1] = 2; PC.arb[2] = 3; \
return PC; \
} \
[domain(\"quad\")] \
[partitioning(\"fractional_odd\")] \
[outputtopology(\"triangle_cw\")] \
[patchconstantfunc(\"PCMain\")] \
[outputcontrolpoints(4)] \
Vertex main(uint id : SV_OutputControlPointID, InputPatch< Vertex, 4 > patch) { \
Vertex Out = patch[id]; \
Out.pos.w += 0.25; \
return Out; \
} \
",
"hs_6_0",
"!{i32 2, !\"Arb\", i8 9, i8 0, !([0-9]+), i8 0, i32 "
"3, i8 1, i32 0, i8 0, (.*)}",
"!{i32 2, !\"Arb\", i8 9, i8 0, !\\1, i8 0, i32 3, "
"i8 1, i32 1, i8 3, \\2}",
"signature element Arb at location \\(1,3\\) size "
"\\(3,1\\) overlaps another signature element.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemPackOverlap2) {
RewriteAssemblyCheckMsg(" \
void main( \
float4 inpos : Position, \
uint iid : SV_InstanceID, \
out float4 pos : SV_Position, \
out uint id[2] : Array, \
out uint3 value : Value, \
out float2 ClipDistance : SV_ClipDistance, \
out float CullDistance : SV_CullDistance) \
{ \
pos = inpos; \
ClipDistance = inpos.x; \
CullDistance = inpos.y; \
value = iid; \
id[0] = iid; \
id[1] = iid + 1; \
} \
",
"vs_6_0",
{"!{i32 1, !\"Array\", i8 5, i8 0, !([0-9]+), i8 1, "
"i32 2, i8 1, i32 1, i8 0, (.*)}(.*)"
"!\\1 = !{i32 0, i32 1}\n",
"= !{i32 2, !\"Value\", i8 5, i8 0, !([0-9]+), i8 "
"1, i32 1, i8 3, i32 1, i8 1, (.*)}"},
{"!{i32 1, !\"Array\", i8 5, i8 0, !\\1, i8 1, i32 "
"2, i8 1, i32 1, i8 1, \\2}\\3"
"!\\1 = !{i32 0, i32 1}\n",
"= !{i32 2, !\"Value\", i8 5, i8 0, !\\1, i8 1, i32 "
"1, i8 3, i32 2, i8 0, \\2}"},
"signature element Value at location \\(2,0\\) size "
"\\(1,3\\) overlaps another signature element.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, SemMultiDepth) {
RewriteAssemblyCheckMsg(
" \
float4 main(float4 f4 : Input, out float d0 : SV_Depth, out float d1 : SV_Target) : SV_Target1 \
{ d0 = f4.z; d1 = f4.w; return f4; } \
",
"ps_6_0",
{"!{i32 2, !\"SV_Target\", i8 9, i8 16, !([0-9]+), i8 0, i32 1, i8 1, "
"i32 0, i8 0, (.*)}"},
{"!{i32 2, !\"SV_DepthGreaterEqual\", i8 9, i8 19, !\\1, i8 0, i32 1, i8 "
"1, i32 -1, i8 -1, \\2}"},
"Pixel Shader only allows one type of depth semantic to be declared",
/*bRegex*/ true);
}
TEST_F(ValidationTest, WhenRootSigMismatchThenFail) {
ReplaceContainerPartsCheckMsgs(
"float c; [RootSignature ( \"RootConstants(b0, num32BitConstants = 1)\" "
")] float4 main() : semantic { return c; }",
"[RootSignature ( \"\" )] float4 main() : semantic { return 0; }",
"vs_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigCompatThenSucceed) {
ReplaceContainerPartsCheckMsgs(
"[RootSignature ( \"\" )] float4 main() : semantic { return 0; }",
"float c; [RootSignature ( \"RootConstants(b0, num32BitConstants = 1)\" "
")] float4 main() : semantic { return c; }",
"vs_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_RootConstVis) {
ReplaceContainerPartsCheckMsgs(
"float c; float4 main() : semantic { return c; }",
"[RootSignature ( \"RootConstants(b0, visibility = "
"SHADER_VISIBILITY_VERTEX, num32BitConstants = 1)\" )]"
" float4 main() : semantic { return 0; }",
"vs_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_RootConstVis) {
ReplaceContainerPartsCheckMsgs(
"float c; float4 main() : semantic { return c; }",
"[RootSignature ( \"RootConstants(b0, visibility = "
"SHADER_VISIBILITY_PIXEL, num32BitConstants = 1)\" )]"
" float4 main() : semantic { return 0; }",
"vs_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_RootCBV) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { float a; int4 b; }; "
"ConstantBuffer<Foo> cb1 : register(b2, space5); "
"float4 main() : semantic { return cb1.b.x; }",
"[RootSignature ( \"CBV(b2, space = 5)\" )]"
" float4 main() : semantic { return 0; }",
"vs_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_RootCBV_Range) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { float a; int4 b; }; "
"ConstantBuffer<Foo> cb1 : register(b0, space5); "
"float4 main() : semantic { return cb1.b.x; }",
"[RootSignature ( \"CBV(b2, space = 5)\" )]"
" float4 main() : semantic { return 0; }",
"vs_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_RootCBV_Space) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { float a; int4 b; }; "
"ConstantBuffer<Foo> cb1 : register(b2, space7); "
"float4 main() : semantic { return cb1.b.x; }",
"[RootSignature ( \"CBV(b2, space = 5)\" )]"
" float4 main() : semantic { return 0; }",
"vs_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_RootSRV) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { float4 a; }; "
"StructuredBuffer<Foo> buf1 : register(t1, space3); "
"float4 main(float4 a : AAA) : SV_Target { return buf1[a.x].a; }",
"[RootSignature ( \"SRV(t1, space = 3)\" )]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_RootSRV_ResType) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { float4 a; }; "
"StructuredBuffer<Foo> buf1 : register(t1, space3); "
"float4 main(float4 a : AAA) : SV_Target { return buf1[a.x].a; }",
"[RootSignature ( \"UAV(u1, space = 3)\" )]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_RootUAV) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { float4 a; }; "
"RWStructuredBuffer<Foo> buf1 : register(u1, space3); "
"float4 main(float4 a : AAA) : SV_Target { return buf1[a.x].a; }",
"[RootSignature ( \"UAV(u1, space = 3)\" )]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_DescTable) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[4] : register(b2, space5);"
"Texture2D<float4> tex1[8] : register(t1, space3);"
"RWBuffer<float4> buf1[6] : register(u33, space17);"
"SamplerState sampler1[5] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( SRV(t1,space=3,numDescriptors=8), "
"CBV(b2,space=5,numDescriptors=4), "
"UAV(u33,space=17,numDescriptors=6)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_DescTable_GoodRange) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[4] : register(b2, space5);"
"Texture2D<float4> tex1[8] : register(t1, space3);"
"RWBuffer<float4> buf1[6] : register(u33, space17);"
"SamplerState sampler1[5] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( SRV(t0,space=3,numDescriptors=20), "
"CBV(b2,space=5,numDescriptors=4), "
"UAV(u33,space=17,numDescriptors=6)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_DescTable_Unbounded) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[4] : register(b2, space5);"
"Texture2D<float4> tex1[8] : register(t1, space3);"
"RWBuffer<float4> buf1[6] : register(u33, space17);"
"SamplerState sampler1[5] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( CBV(b2,space=5,numDescriptors=4), "
"SRV(t1,space=3,numDescriptors=8), "
"UAV(u10,space=17,numDescriptors=unbounded)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_DescTable_Range1) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[4] : register(b2, space5);"
"Texture2D<float4> tex1[8] : register(t1, space3);"
"RWBuffer<float4> buf1[6] : register(u33, space17);"
"SamplerState sampler1[5] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( CBV(b2,space=5,numDescriptors=4), "
"SRV(t2,space=3,numDescriptors=8), "
"UAV(u33,space=17,numDescriptors=6)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Shader SRV descriptor range (RegisterSpace=3, NumDescriptors=8, "
"BaseShaderRegister=1) is not fully bound in root signature.",
"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_DescTable_Range2) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[4] : register(b2, space5);"
"Texture2D<float4> tex1[8] : register(t1, space3);"
"RWBuffer<float4> buf1[6] : register(u33, space17);"
"SamplerState sampler1[5] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( SRV(t2,space=3,numDescriptors=8), "
"CBV(b20,space=5,numDescriptors=4), "
"UAV(u33,space=17,numDescriptors=6)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_DescTable_Range3) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[4] : register(b2, space5);"
"Texture2D<float4> tex1[8] : register(t1, space3);"
"RWBuffer<float4> buf1[6] : register(u33, space17);"
"SamplerState sampler1[5] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( CBV(b2,space=5,numDescriptors=4), "
"SRV(t1,space=3,numDescriptors=8), "
"UAV(u33,space=17,numDescriptors=5)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_DescTable_Space) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[4] : register(b2, space5);"
"Texture2D<float4> tex1[8] : register(t1, space3);"
"RWBuffer<float4> buf1[6] : register(u33, space17);"
"SamplerState sampler1[5] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( SRV(t2,space=3,numDescriptors=8), "
"CBV(b2,space=5,numDescriptors=4), "
"UAV(u33,space=0,numDescriptors=6)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderSucceed_Unbounded) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[] : register(b2, space5);"
"Texture2D<float4> tex1[] : register(t1, space3);"
"RWBuffer<float4> buf1[] : register(u33, space17);"
"SamplerState sampler1[] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( CBV(b2,space=5,numDescriptors=1)), "
"DescriptorTable( SRV(t1,space=3,numDescriptors=unbounded)), "
"DescriptorTable( UAV(u10,space=17,numDescriptors=100)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature}, {});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_Unbounded1) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[] : register(b2, space5);"
"Texture2D<float4> tex1[] : register(t1, space3);"
"RWBuffer<float4> buf1[] : register(u33, space17);"
"SamplerState sampler1[] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( CBV(b3,space=5,numDescriptors=1)), "
"DescriptorTable( SRV(t1,space=3,numDescriptors=unbounded)), "
"DescriptorTable( UAV(u10,space=17,numDescriptors=unbounded)), "
"DescriptorTable( Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_Unbounded2) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[] : register(b2, space5);"
"Texture2D<float4> tex1[] : register(t1, space3);"
"RWBuffer<float4> buf1[] : register(u33, space17);"
"SamplerState sampler1[] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( CBV(b2,space=5,numDescriptors=1)), "
"DescriptorTable( SRV(t1,space=3,numDescriptors=unbounded)), "
"DescriptorTable( UAV(u10,space=17,numDescriptors=unbounded)), "
"DescriptorTable( Sampler(s5, numDescriptors=unbounded))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRootSigMatchShaderFail_Unbounded3) {
ReplaceContainerPartsCheckMsgs(
"struct Foo { int a; float4 b; };"
""
"ConstantBuffer<Foo> cb1[] : register(b2, space5);"
"Texture2D<float4> tex1[] : register(t1, space3);"
"RWBuffer<float4> buf1[] : register(u33, space17);"
"SamplerState sampler1[] : register(s0, space0);"
""
"float4 main(float4 a : AAA) : SV_TARGET"
"{"
" return buf1[a.x][a.y] + cb1[a.x].b + tex1[a.x].Sample(sampler1[a.x], "
"a.xy);"
"}",
"[RootSignature(\"DescriptorTable( CBV(b2,space=5,numDescriptors=1)), "
"DescriptorTable( SRV(t1,space=3,numDescriptors=unbounded)), "
"DescriptorTable( UAV(u10,space=17,numDescriptors=7)), "
"DescriptorTable(Sampler(s0, numDescriptors=5))\")]"
" float4 main() : SV_Target { return 0; }",
"ps_6_0", {DFCC_RootSignature},
{"Root Signature in DXIL container is not compatible with shader.",
"Validation failed."});
}
#define VERTEX_STRUCT1 \
"struct PSSceneIn \n\
{ \n\
float4 pos : SV_Position; \n\
float2 tex : TEXCOORD0; \n\
float3 norm : NORMAL; \n\
}; \n"
#define VERTEX_STRUCT2 \
"struct PSSceneIn \n\
{ \n\
float4 pos : SV_Position; \n\
float2 tex : TEXCOORD0; \n\
}; \n"
#define PC_STRUCT1 \
"struct HSPerPatchData { \n\
float edges[ 3 ] : SV_TessFactor; \n\
float inside : SV_InsideTessFactor; \n\
float foo : FOO; \n\
}; \n"
#define PC_STRUCT2 \
"struct HSPerPatchData { \n\
float edges[ 3 ] : SV_TessFactor; \n\
float inside : SV_InsideTessFactor; \n\
}; \n"
#define PC_FUNC \
"HSPerPatchData HSPerPatchFunc( InputPatch< PSSceneIn, 3 > points, \n\
OutputPatch<PSSceneIn, 3> outpoints) { \n\
HSPerPatchData d = (HSPerPatchData)0; \n\
d.edges[ 0 ] = points[0].tex.x + outpoints[0].tex.x; \n\
d.edges[ 1 ] = 1; \n\
d.edges[ 2 ] = 1; \n\
d.inside = 1; \n\
return d; \n\
} \n"
#define PC_FUNC_NOOUT \
"HSPerPatchData HSPerPatchFunc( InputPatch< PSSceneIn, 3 > points ) { \n\
HSPerPatchData d = (HSPerPatchData)0; \n\
d.edges[ 0 ] = points[0].tex.x; \n\
d.edges[ 1 ] = 1; \n\
d.edges[ 2 ] = 1; \n\
d.inside = 1; \n\
return d; \n\
} \n"
#define PC_FUNC_NOIN \
"HSPerPatchData HSPerPatchFunc( OutputPatch<PSSceneIn, 3> outpoints) { \n\
HSPerPatchData d = (HSPerPatchData)0; \n\
d.edges[ 0 ] = outpoints[0].tex.x; \n\
d.edges[ 1 ] = 1; \n\
d.edges[ 2 ] = 1; \n\
d.inside = 1; \n\
return d; \n\
} \n"
#define HS_ATTR \
"[domain(\"tri\")] \n\
[partitioning(\"fractional_odd\")] \n\
[outputtopology(\"triangle_cw\")] \n\
[patchconstantfunc(\"HSPerPatchFunc\")] \n\
[outputcontrolpoints(3)] \n"
#define HS_FUNC \
"PSSceneIn main(const uint id : SV_OutputControlPointID, \n\
const InputPatch< PSSceneIn, 3 > points ) { \n\
return points[ id ]; \n\
} \n"
#define HS_FUNC_NOOUT \
"void main(const uint id : SV_OutputControlPointID, \n\
const InputPatch< PSSceneIn, 3 > points ) { \n\
} \n"
#define HS_FUNC_NOIN \
"PSSceneIn main( const uint id : SV_OutputControlPointID ) { \n\
return (PSSceneIn)0; \n\
} \n"
#define DS_FUNC \
"[domain(\"tri\")] PSSceneIn main(const float3 bary : SV_DomainLocation, \n\
const OutputPatch<PSSceneIn, 3> patch, \n\
const HSPerPatchData perPatchData) { \n\
PSSceneIn v = patch[0]; \n\
v.pos = patch[0].pos * bary.x; \n\
v.pos += patch[1].pos * bary.y; \n\
v.pos += patch[2].pos * bary.z; \n\
return v; \n\
} \n"
#define DS_FUNC_NOPC \
"[domain(\"tri\")] PSSceneIn main(const float3 bary : SV_DomainLocation, \n\
const OutputPatch<PSSceneIn, 3> patch) { \n\
PSSceneIn v = patch[0]; \n\
v.pos = patch[0].pos * bary.x; \n\
v.pos += patch[1].pos * bary.y; \n\
v.pos += patch[2].pos * bary.z; \n\
return v; \n\
} \n"
TEST_F(ValidationTest, WhenProgramOutSigMissingThenFail) {
ReplaceContainerPartsCheckMsgs(
VERTEX_STRUCT1 PC_STRUCT1 PC_FUNC HS_ATTR HS_FUNC,
VERTEX_STRUCT1 PC_STRUCT1 PC_FUNC_NOOUT HS_ATTR HS_FUNC_NOOUT,
"hs_6_0",
{DFCC_InputSignature, DFCC_OutputSignature, DFCC_PatchConstantSignature},
{"Container part 'Program Output Signature' does not match expected for "
"module.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenProgramOutSigUnexpectedThenFail) {
ReplaceContainerPartsCheckMsgs(
VERTEX_STRUCT1 PC_STRUCT1 PC_FUNC_NOOUT HS_ATTR HS_FUNC_NOOUT,
VERTEX_STRUCT1 PC_STRUCT1 PC_FUNC HS_ATTR HS_FUNC,
"hs_6_0",
{DFCC_InputSignature, DFCC_OutputSignature, DFCC_PatchConstantSignature},
{"Container part 'Program Output Signature' does not match expected for "
"module.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenProgramSigMismatchThenFail) {
ReplaceContainerPartsCheckMsgs(
VERTEX_STRUCT1 PC_STRUCT1 PC_FUNC HS_ATTR HS_FUNC,
VERTEX_STRUCT2 PC_STRUCT2 PC_FUNC HS_ATTR HS_FUNC,
"hs_6_0",
{DFCC_InputSignature, DFCC_OutputSignature, DFCC_PatchConstantSignature},
{"Container part 'Program Input Signature' does not match expected for "
"module.",
"Container part 'Program Output Signature' does not match expected for "
"module.",
"Container part 'Program Patch Constant Signature' does not match "
"expected for module.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenProgramInSigMissingThenFail) {
ReplaceContainerPartsCheckMsgs(
VERTEX_STRUCT1 PC_STRUCT1 PC_FUNC HS_ATTR HS_FUNC,
// Compiling the HS_FUNC_NOIN produces the following error
// error: validation errors
// HS input control point count must be [1..32]. 0 specified
VERTEX_STRUCT1 PC_STRUCT1 PC_FUNC_NOIN HS_ATTR HS_FUNC_NOIN, "hs_6_0",
{DFCC_InputSignature, DFCC_OutputSignature, DFCC_PatchConstantSignature},
{"Container part 'Program Input Signature' does not match expected for "
"module.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenProgramSigMismatchThenFail2) {
ReplaceContainerPartsCheckMsgs(
VERTEX_STRUCT1 PC_STRUCT1 DS_FUNC,
VERTEX_STRUCT2 PC_STRUCT2 DS_FUNC,
"ds_6_0",
{DFCC_InputSignature, DFCC_OutputSignature, DFCC_PatchConstantSignature},
{"Container part 'Program Input Signature' does not match expected for "
"module.",
"Container part 'Program Output Signature' does not match expected for "
"module.",
"Container part 'Program Patch Constant Signature' does not match "
"expected for module.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenProgramPCSigMissingThenFail) {
ReplaceContainerPartsCheckMsgs(
VERTEX_STRUCT1 PC_STRUCT1 DS_FUNC,
VERTEX_STRUCT2 PC_STRUCT2 DS_FUNC_NOPC,
"ds_6_0",
{DFCC_InputSignature, DFCC_OutputSignature, DFCC_PatchConstantSignature},
{"Container part 'Program Input Signature' does not match expected for "
"module.",
"Container part 'Program Output Signature' does not match expected for "
"module.",
"Missing part 'Program Patch Constant Signature' required by module.",
"Validation failed."});
}
#undef VERTEX_STRUCT1
#undef VERTEX_STRUCT2
#undef PC_STRUCT1
#undef PC_STRUCT2
#undef PC_FUNC
#undef PC_FUNC_NOOUT
#undef PC_FUNC_NOIN
#undef HS_ATTR
#undef HS_FUNC
#undef HS_FUNC_NOOUT
#undef HS_FUNC_NOIN
#undef DS_FUNC
#undef DS_FUNC_NOPC
TEST_F(ValidationTest, WhenPSVMismatchThenFail) {
ReplaceContainerPartsCheckMsgs(
"float c; [RootSignature ( \"RootConstants(b0, num32BitConstants = 1)\" "
")] float4 main() : semantic { return c; }",
"[RootSignature ( \"\" )] float4 main() : semantic { return 0; }",
"vs_6_0", {DFCC_PipelineStateValidation},
{"Container part 'Pipeline State Validation' does not match expected for "
"module.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenRDATMismatchThenFail) {
ReplaceContainerPartsCheckMsgs(
"export float4 main(float f) : semantic { return f; }",
"export float4 main() : semantic { return 0; }", "lib_6_3",
{DFCC_RuntimeData},
{"Container part 'Runtime Data (RDAT)' does not match expected for "
"module.",
"Validation failed."});
}
TEST_F(ValidationTest, WhenFeatureInfoMismatchThenFail) {
ReplaceContainerPartsCheckMsgs(
"float4 main(uint2 foo : FOO) : SV_Target { return asdouble(foo.x, "
"foo.y) * 2.0; }",
"float4 main() : SV_Target { return 0; }", "ps_6_0", {DFCC_FeatureInfo},
{"Container part 'Feature Info' does not match expected for module.",
"Validation failed."});
}
TEST_F(ValidationTest, RayShaderWithSignaturesFail) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"struct Param { float f; };\n"
"[shader(\"raygeneration\")] void RayGenProto() { return; }\n"
"[shader(\"intersection\")] void IntersectionProto() { return; }\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"[shader(\"miss\")] void MissProto(inout Payload p) { p.f += 1.0; }\n"
"[shader(\"callable\")] void CallableProto(inout Param p) { p.f += 1.0; "
"}\n"
"[shader(\"vertex\")] float VSOutOnly() : OUTPUT { return 1; }\n"
"[shader(\"vertex\")] void VSInOnly(float f : INPUT) : OUTPUT {}\n"
"[shader(\"vertex\")] float VSInOut(float f : INPUT) : OUTPUT { return "
"f; }\n",
"lib_6_3",
{"!{void \\(\\)\\* @VSInOnly, !\"VSInOnly\", !([0-9]+), null,(.*)!\\1 = ",
"!{void \\(\\)\\* @VSOutOnly, !\"VSOutOnly\", !([0-9]+), null,(.*)!\\1 "
"= ",
"!{void \\(\\)\\* @VSInOut, !\"VSInOut\", !([0-9]+), null,(.*)!\\1 = ",
"!{void \\(\\)\\* @\"\\\\01\\?RayGenProto@@YAXXZ\", "
"!\"\\\\01\\?RayGenProto@@YAXXZ\", null, null,",
"!{void \\(\\)\\* @\"\\\\01\\?IntersectionProto@@YAXXZ\", "
"!\"\\\\01\\?IntersectionProto@@YAXXZ\", null, null,",
"!{void \\(%struct.Payload\\*, %struct.Attributes\\*\\)\\* "
"@\"\\\\01\\?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\\\01\\?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", null, null,",
"!{void \\(%struct.Payload\\*, %struct.Attributes\\*\\)\\* "
"@\"\\\\01\\?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\\\01\\?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", null, "
"null,",
"!{void \\(%struct.Payload\\*\\)\\* "
"@\"\\\\01\\?MissProto@@YAXUPayload@@@Z\", "
"!\"\\\\01\\?MissProto@@YAXUPayload@@@Z\", null, null,",
"!{void \\(%struct.Param\\*\\)\\* "
"@\"\\\\01\\?CallableProto@@YAXUParam@@@Z\", "
"!\"\\\\01\\?CallableProto@@YAXUParam@@@Z\", null, null,"},
{"!{void ()* @VSInOnly, !\"VSInOnly\", !1001, null,\\2!1001 = ",
"!{void ()* @VSOutOnly, !\"VSOutOnly\", !1002, null,\\2!1002 = ",
"!{void ()* @VSInOut, !\"VSInOut\", !1003, null,\\2!1003 = ",
"!{void ()* @\"\\\\01?RayGenProto@@YAXXZ\", "
"!\"\\\\01?RayGenProto@@YAXXZ\", !1001, null,",
"!{void ()* @\"\\\\01?IntersectionProto@@YAXXZ\", "
"!\"\\\\01?IntersectionProto@@YAXXZ\", !1002, null,",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", !1003, null,",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", !1001, "
"null,",
"!{void (%struct.Payload*)* @\"\\\\01?MissProto@@YAXUPayload@@@Z\", "
"!\"\\\\01?MissProto@@YAXUPayload@@@Z\", !1002, null,",
"!{void (%struct.Param*)* @\"\\\\01?CallableProto@@YAXUParam@@@Z\", "
"!\"\\\\01?CallableProto@@YAXUParam@@@Z\", !1003, null,"},
{"Ray tracing shader '\\\\01\\?RayGenProto@@YAXXZ' should not have any "
"shader signatures",
"Ray tracing shader '\\\\01\\?IntersectionProto@@YAXXZ' should not have "
"any shader signatures",
"Ray tracing shader "
"'\\\\01\\?AnyHitProto@@YAXUPayload@@UAttributes@@@Z' should not have "
"any shader signatures",
"Ray tracing shader "
"'\\\\01\\?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z' should not "
"have any shader signatures",
"Ray tracing shader '\\\\01\\?MissProto@@YAXUPayload@@@Z' should not "
"have any shader signatures",
"Ray tracing shader '\\\\01\\?CallableProto@@YAXUParam@@@Z' should not "
"have any shader signatures"},
/*bRegex*/ true);
}
TEST_F(ValidationTest, ViewIDInCSFail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
" \
RWStructuredBuffer<uint> Buf; \
[numthreads(1,1,1)] \
void main(uint id : SV_GroupIndex) \
{ Buf[id] = 0; } \
",
"cs_6_1",
{"dx.op.flattenedThreadIdInGroup.i32(i32 96",
"declare i32 @dx.op.flattenedThreadIdInGroup.i32(i32)"},
{"dx.op.viewID.i32(i32 138", "declare i32 @dx.op.viewID.i32(i32)"},
"Opcode ViewID not valid in shader model cs_6_1",
/*bRegex*/ false);
}
TEST_F(ValidationTest, ViewIDIn60Fail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
" \
[domain(\"tri\")] \
float4 main(float3 pos : Position, uint id : SV_PrimitiveID) : SV_Position \
{ return float4(pos, id); } \
",
"ds_6_0",
{"dx.op.primitiveID.i32(i32 108",
"declare i32 @dx.op.primitiveID.i32(i32)"},
{"dx.op.viewID.i32(i32 138", "declare i32 @dx.op.viewID.i32(i32)"},
"Opcode ViewID not valid in shader model ds_6_0",
/*bRegex*/ false);
}
TEST_F(ValidationTest, ViewIDNoSpaceFail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
" \
float4 main(uint vid : SV_ViewID, float3 In[31] : INPUT) : SV_Target \
{ return float4(In[vid], 1); } \
",
"ps_6_1",
{"!{i32 0, !\"INPUT\", i8 9, i8 0, !([0-9]+), i8 2, i32 31",
"!{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 "
"9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 "
"18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, "
"i32 27, i32 28, i32 29, i32 30}",
"?!dx.viewIdState ="},
{"!{i32 0, !\"INPUT\", i8 9, i8 0, !\\1, i8 2, i32 32",
"!{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 "
"9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 "
"18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, "
"i32 27, i32 28, i32 29, i32 30, i32 31}",
"!1012 ="},
"Pixel shader input signature lacks available space for ViewID",
/*bRegex*/ true);
}
// Regression test for a double-delete when failing to parse bitcode.
TEST_F(ValidationTest, WhenDisassembleInvalidBlobThenFail) {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
}
CComPtr<IDxcBlobEncoding> pInvalidBitcode;
Utf8ToBlob(m_dllSupport, "This text is certainly not bitcode",
&pInvalidBitcode);
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
CComPtr<IDxcBlobEncoding> pDisassembly;
VERIFY_FAILED(pCompiler->Disassemble(pInvalidBitcode, &pDisassembly));
}
TEST_F(ValidationTest, GSMainMissingAttributeFail) {
TestCheck(L"..\\CodeGenHLSL\\attributes-gs-no-inout-main.hlsl");
}
TEST_F(ValidationTest, GSOtherMissingAttributeFail) {
TestCheck(L"..\\CodeGenHLSL\\attributes-gs-no-inout-other.hlsl");
}
TEST_F(ValidationTest, GetAttributeAtVertexInVSFail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
"float4 main(float4 pos: POSITION) : SV_POSITION { return pos.x; }",
"vs_6_1",
{"call float @dx.op.loadInput.f32(i32 4, i32 0, i32 0, i8 0, i32 undef)",
"declare float @dx.op.loadInput.f32(i32, i32, i32, i8, i32)"},
{"call float @dx.op.attributeAtVertex.f32(i32 137, i32 0, i32 0, i8 0, "
"i8 0)",
"declare float @dx.op.attributeAtVertex.f32(i32, i32, i32, i8, i8)"},
"Opcode AttributeAtVertex not valid in shader model vs_6_1",
/*bRegex*/ false);
}
TEST_F(ValidationTest, GetAttributeAtVertexIn60Fail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
"float4 main(float4 col : COLOR) : "
"SV_Target { return EvaluateAttributeCentroid(col).x; }",
"ps_6_0",
{"call float @dx.op.evalCentroid.f32(i32 89, i32 0, i32 0, i8 0)",
"declare float @dx.op.evalCentroid.f32(i32, i32, i32, i8)"},
{"call float @dx.op.attributeAtVertex.f32(i32 137, i32 0, i32 0, i8 0, "
"i8 0)",
"declare float @dx.op.attributeAtVertex.f32(i32, i32, i32, i8, i8)"},
"Opcode AttributeAtVertex not valid in shader model ps_6_0",
/*bRegex*/ false);
}
TEST_F(ValidationTest, GetAttributeAtVertexInterpFail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg("float4 main(nointerpolation float4 col : COLOR) : "
"SV_Target { return GetAttributeAtVertex(col, 0); }",
"ps_6_1", {"!\"COLOR\", i8 9, i8 0, (![0-9]+), i8 1"},
{"!\"COLOR\", i8 9, i8 0, \\1, i8 2"},
"Attribute COLOR must have nointerpolation mode in "
"order to use GetAttributeAtVertex function.",
/*bRegex*/ true);
}
TEST_F(ValidationTest, BarycentricMaxIndexFail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
"float4 main(float3 bary : SV_Barycentrics, noperspective float3 bary1 : "
"SV_Barycentrics1) : SV_Target { return 1; }",
"ps_6_1",
{"!([0-9]+) = !{i32 0, !\"SV_Barycentrics\", i8 9, i8 28, !([0-9]+), i8 "
"2, i32 1, i8 3, i32 -1, i8 -1, null}\n"
"!([0-9]+) = !{i32 0}"},
{"!\\1 = !{i32 0, !\"SV_Barycentrics\", i8 9, i8 28, !\\2, i8 2, i32 1, "
"i8 3, i32 -1, i8 -1, null}\n"
"!\\3 = !{i32 2}"},
"SV_Barycentrics semantic index exceeds maximum", /*bRegex*/ true);
}
TEST_F(ValidationTest, BarycentricNoInterpolationFail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
"float4 main(float3 bary : SV_Barycentrics) : "
"SV_Target { return bary.x * float4(1,0,0,0) + bary.y * float4(0,1,0,0) "
"+ bary.z * float4(0,0,1,0); }",
"ps_6_1", {"!\"SV_Barycentrics\", i8 9, i8 28, (![0-9]+), i8 2"},
{"!\"SV_Barycentrics\", i8 9, i8 28, \\1, i8 1"},
"SV_Barycentrics cannot be used with 'nointerpolation' type",
/*bRegex*/ true);
}
TEST_F(ValidationTest, BarycentricFloat4Fail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
"float4 main(float4 col : COLOR) : SV_Target { return col; }", "ps_6_1",
{"!\"COLOR\", i8 9, i8 0"}, {"!\"SV_Barycentrics\", i8 9, i8 28"},
"only 'float3' type is allowed for SV_Barycentrics.", false);
}
TEST_F(ValidationTest, BarycentricSamePerspectiveFail) {
if (m_ver.SkipDxilVersion(1, 1))
return;
RewriteAssemblyCheckMsg(
"float4 main(float3 bary : SV_Barycentrics, noperspective float3 bary1 : "
"SV_Barycentrics1) : SV_Target { return 1; }",
"ps_6_1", {"!\"SV_Barycentrics\", i8 9, i8 28, (![0-9]+), i8 4"},
{"!\"SV_Barycentrics\", i8 9, i8 28, \\1, i8 2"},
"There can only be up to two input attributes of SV_Barycentrics with "
"different perspective interpolation mode.",
true);
}
TEST_F(ValidationTest, Float32DenormModeAttribute) {
if (m_ver.SkipDxilVersion(1, 2))
return;
std::vector<LPCWSTR> pArguments = {L"-denorm", L"ftz"};
RewriteAssemblyCheckMsg(
"float4 main(float4 col: COL) : SV_Target { return col; }", "ps_6_2",
pArguments.data(), 2, nullptr, 0, {"\"fp32-denorm-mode\"=\"ftz\""},
{"\"fp32-denorm-mode\"=\"invalid_mode\""},
"contains invalid attribute 'fp32-denorm-mode' with value 'invalid_mode'",
false);
}
TEST_F(ValidationTest, ResCounter) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"RWStructuredBuffer<float4> buf; export float GetCounter() {return "
"buf.IncrementCounter();}",
"lib_6_3",
{"!\"buf\", i32 -1, i32 -1, i32 1, i32 12, i1 false, i1 true, i1 false, "
"!"},
{"!\"buf\", i32 -1, i32 -1, i32 1, i32 12, i1 false, i1 false, i1 false, "
"!"},
"BufferUpdateCounter valid only when HasCounter is true", true);
}
TEST_F(ValidationTest, FunctionAttributes) {
if (m_ver.SkipDxilVersion(1, 2))
return;
std::vector<LPCWSTR> pArguments = {L"-denorm", L"ftz"};
RewriteAssemblyCheckMsg(
"float4 main(float4 col: COL) : SV_Target { return col; }", "ps_6_2",
pArguments.data(), 2, nullptr, 0, {"\"fp32-denorm-mode\"=\"ftz\""},
{"\"dummy_attribute\"=\"invalid_mode\""},
"contains invalid attribute 'dummy_attribute' with value 'invalid_mode'",
false);
} // TODO: reject non-zero padding
TEST_F(ValidationTest, LibFunctionResInSig) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"Texture2D<float4> T1;\n"
"struct ResInStruct { float f; Texture2D<float4> T; };\n"
"struct ResStructInStruct { float f; ResInStruct S; };\n"
"ResStructInStruct fnResInReturn(float f) : SV_Target {\n"
" ResStructInStruct S1; S1.f = S1.S.f = f; S1.S.T = T1;\n"
" return S1; }\n"
"float fnResInArg(ResStructInStruct S1) : SV_Target {\n"
" return S1.f; }\n"
"struct Data { float f; };\n"
"float fnStreamInArg(float f, inout PointStream<Data> S1) : SV_Target {\n"
" S1.Append((Data)f); return 1.0; }\n",
"lib_6_x",
{"!{!\"lib\", i32 6, i32 15}", "!dx.valver = !{!([0-9]+)}",
"= !{i32 20, !([0-9]+), !([0-9]+), !([0-9]+)}"},
{"!{!\"lib\", i32 6, i32 3}",
"!dx.valver = !{!100\\1}\n!1002 = !{i32 1, i32 3}",
"= !{i32 20, !\\1, !\\2}"},
{"Function '\\\\01\\?fnResInReturn@@YA\\?AUResStructInStruct@@M@Z' uses "
"resource in function signature",
"Function '\\\\01\\?fnResInArg@@YAMUResStructInStruct@@@Z' uses "
"resource in function signature",
"Function '\\\\01\\?fnStreamInArg@@YAMMV\\?\\$PointStream@UData@@@@@Z' "
"uses resource in function signature"
// TODO: Unable to lower stream append, since it's used in a non-GS
// function. Should we fail to compile earlier (even on lib_6_x), or add
// lowering to linker?
,
"Function 'dx\\.hl\\.op\\.\\.void \\(i32, "
"%\"class\\.PointStream<Data>\"\\*, float\\*\\)' uses resource in "
"function signature"},
/*bRegex*/ true);
}
TEST_F(ValidationTest, RayPayloadIsStruct) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"export void BadAnyHit(inout float f, in Attributes a) { f += a.b.x; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"export void BadClosestHit(inout float f, in Attributes a) { f += a.b.y; "
"}\n"
"[shader(\"miss\")] void MissProto(inout Payload p) { p.f += 1.0; }\n"
"export void BadMiss(inout float f) { f += 1.0; }\n",
"lib_6_3",
{"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*)* @\"\\01?MissProto@@YAXUPayload@@@Z\", "
"!\"\\01?MissProto@@YAXUPayload@@@Z\","},
{"!{void (float*, %struct.Attributes*)* "
"@\"\\01?BadAnyHit@@YAXAIAMUAttributes@@@Z\", "
"!\"\\01?BadAnyHit@@YAXAIAMUAttributes@@@Z\",",
"!{void (float*, %struct.Attributes*)* "
"@\"\\01?BadClosestHit@@YAXAIAMUAttributes@@@Z\", "
"!\"\\01?BadClosestHit@@YAXAIAMUAttributes@@@Z\",",
"!{void (float*)* @\"\\01?BadMiss@@YAXAIAM@Z\", "
"!\"\\01?BadMiss@@YAXAIAM@Z\","},
{"Argument 'f' must be a struct type for payload in shader function "
"'\\01?BadAnyHit@@YAXAIAMUAttributes@@@Z'",
"Argument 'f' must be a struct type for payload in shader function "
"'\\01?BadClosestHit@@YAXAIAMUAttributes@@@Z'",
"Argument 'f' must be a struct type for payload in shader function "
"'\\01?BadMiss@@YAXAIAM@Z'"},
false);
}
TEST_F(ValidationTest, RayAttrIsStruct) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"export void BadAnyHit(inout Payload p, in float a) { p.f += a; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"export void BadClosestHit(inout Payload p, in float a) { p.f += a; }\n",
"lib_6_3",
{"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\","},
{"!{void (%struct.Payload*, float)* "
"@\"\\01?BadAnyHit@@YAXUPayload@@M@Z\", "
"!\"\\01?BadAnyHit@@YAXUPayload@@M@Z\",",
"!{void (%struct.Payload*, float)* "
"@\"\\01?BadClosestHit@@YAXUPayload@@M@Z\", "
"!\"\\01?BadClosestHit@@YAXUPayload@@M@Z\","},
{"Argument 'a' must be a struct type for attributes in shader function "
"'\\01?BadAnyHit@@YAXUPayload@@M@Z'",
"Argument 'a' must be a struct type for attributes in shader function "
"'\\01?BadClosestHit@@YAXUPayload@@M@Z'"},
false);
}
TEST_F(ValidationTest, CallableParamIsStruct) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct Param { float f; };\n"
"[shader(\"callable\")] void CallableProto(inout Param p) { p.f += 1.0; "
"}\n"
"export void BadCallable(inout float f) { f += 1.0; }\n",
"lib_6_3",
{"!{void (%struct.Param*)* @\"\\01?CallableProto@@YAXUParam@@@Z\", "
"!\"\\01?CallableProto@@YAXUParam@@@Z\","},
{"!{void (float*)* @\"\\01?BadCallable@@YAXAIAM@Z\", "
"!\"\\01?BadCallable@@YAXAIAM@Z\","},
{"Argument 'f' must be a struct type for callable shader function "
"'\\01?BadCallable@@YAXAIAM@Z'"},
false);
}
TEST_F(ValidationTest, RayShaderExtraArg) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"struct Param { float f; };\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"[shader(\"miss\")] void MissProto(inout Payload p) { p.f += 1.0; }\n"
"[shader(\"callable\")] void CallableProto(inout Param p) { p.f += 1.0; "
"}\n"
"export void BadAnyHit(inout Payload p, in Attributes a, float f) { p.f "
"+= f; }\n"
"export void BadClosestHit(inout Payload p, in Attributes a, float f) { "
"p.f += f; }\n"
"export void BadMiss(inout Payload p, float f) { p.f += f; }\n"
"export void BadCallable(inout Param p, float f) { p.f += f; }\n",
"lib_6_3",
{"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\"",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\"",
"!{void (%struct.Payload*)* @\"\\01?MissProto@@YAXUPayload@@@Z\", "
"!\"\\01?MissProto@@YAXUPayload@@@Z\"",
"!{void (%struct.Param*)* @\"\\01?CallableProto@@YAXUParam@@@Z\", "
"!\"\\01?CallableProto@@YAXUParam@@@Z\""},
{"!{void (%struct.Payload*, %struct.Attributes*, float)* "
"@\"\\01?BadAnyHit@@YAXUPayload@@UAttributes@@M@Z\", "
"!\"\\01?BadAnyHit@@YAXUPayload@@UAttributes@@M@Z\"",
"!{void (%struct.Payload*, %struct.Attributes*, float)* "
"@\"\\01?BadClosestHit@@YAXUPayload@@UAttributes@@M@Z\", "
"!\"\\01?BadClosestHit@@YAXUPayload@@UAttributes@@M@Z\"",
"!{void (%struct.Payload*, float)* @\"\\01?BadMiss@@YAXUPayload@@M@Z\", "
"!\"\\01?BadMiss@@YAXUPayload@@M@Z\"",
"!{void (%struct.Param*, float)* @\"\\01?BadCallable@@YAXUParam@@M@Z\", "
"!\"\\01?BadCallable@@YAXUParam@@M@Z\""},
{"Extra argument 'f' not allowed for shader function "
"'\\01?BadAnyHit@@YAXUPayload@@UAttributes@@M@Z'",
"Extra argument 'f' not allowed for shader function "
"'\\01?BadClosestHit@@YAXUPayload@@UAttributes@@M@Z'",
"Extra argument 'f' not allowed for shader function "
"'\\01?BadMiss@@YAXUPayload@@M@Z'",
"Extra argument 'f' not allowed for shader function "
"'\\01?BadCallable@@YAXUParam@@M@Z'"},
false);
}
TEST_F(ValidationTest, ResInShaderStruct) {
if (m_ver.SkipDxilVersion(1, 3))
return;
// Verify resource not used in shader argument structure
RewriteAssemblyCheckMsg(
"struct ResInStruct { float f; Texture2D<float4> T; };\n"
"struct ResStructInStruct { float f; ResInStruct S; };\n"
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"export void BadAnyHit(inout ResStructInStruct p, in Attributes a) { p.f "
"+= a.b.x; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"export void BadClosestHit(inout ResStructInStruct p, in Attributes a) { "
"p.f += a.b.x; }\n"
"[shader(\"miss\")] void MissProto(inout Payload p) { p.f += 1.0; }\n"
"export void BadMiss(inout ResStructInStruct p) { p.f += 1.0; }\n"
"struct Param { float f; };\n"
"[shader(\"callable\")] void CallableProto(inout Param p) { p.f += 1.0; "
"}\n"
"export void BadCallable(inout ResStructInStruct p) { p.f += 1.0; }\n",
"lib_6_x",
{"!{!\"lib\", i32 6, i32 15}", "!dx.valver = !{!([0-9]+)}",
"= !{i32 20, !([0-9]+), !([0-9]+), !([0-9]+)}",
"!{void \\(%struct\\.Payload\\*, %struct\\.Attributes\\*\\)\\* "
"@\"\\\\01\\?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\\\01\\?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void \\(%struct\\.Payload\\*, %struct\\.Attributes\\*\\)\\* "
"@\"\\\\01\\?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\\\01\\?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void \\(%struct\\.Payload\\*\\)\\* "
"@\"\\\\01\\?MissProto@@YAXUPayload@@@Z\", "
"!\"\\\\01\\?MissProto@@YAXUPayload@@@Z\",",
"!{void \\(%struct\\.Param\\*\\)\\* "
"@\"\\\\01\\?CallableProto@@YAXUParam@@@Z\", "
"!\"\\\\01\\?CallableProto@@YAXUParam@@@Z\","},
{
"!{!\"lib\", i32 6, i32 3}",
"!dx.valver = !{!100\\1}\n!1002 = !{i32 1, i32 3}",
"= !{i32 20, !\\1, !\\2}",
"!{void (%struct.ResStructInStruct*, %struct.Attributes*)* "
"@\"\\\\01?BadAnyHit@@YAXUResStructInStruct@@UAttributes@@@Z\", "
"!\"\\\\01?BadAnyHit@@YAXUResStructInStruct@@UAttributes@@@Z\",",
"!{void (%struct.ResStructInStruct*, %struct.Attributes*)* "
"@\"\\\\01?BadClosestHit@@YAXUResStructInStruct@@UAttributes@@@Z\", "
"!\"\\\\01?BadClosestHit@@YAXUResStructInStruct@@UAttributes@@@Z\",",
"!{void (%struct.ResStructInStruct*)* "
"@\"\\\\01?BadMiss@@YAXUResStructInStruct@@@Z\", "
"!\"\\\\01?BadMiss@@YAXUResStructInStruct@@@Z\",",
"!{void (%struct.ResStructInStruct*)* "
"@\"\\\\01?BadCallable@@YAXUResStructInStruct@@@Z\", "
"!\"\\\\01?BadCallable@@YAXUResStructInStruct@@@Z\",",
},
{"Function '\\\\01\\?BadAnyHit@@YAXUResStructInStruct@@UAttributes@@@Z' "
"uses resource in function signature",
"Function "
"'\\\\01\\?BadClosestHit@@YAXUResStructInStruct@@UAttributes@@@Z' uses "
"resource in function signature",
"Function '\\\\01\\?BadMiss@@YAXUResStructInStruct@@@Z' uses resource "
"in function signature",
"Function '\\\\01\\?BadCallable@@YAXUResStructInStruct@@@Z' uses "
"resource in function signature"},
/*bRegex*/ true);
}
TEST_F(ValidationTest, WhenPayloadSizeTooSmallThenFail) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"struct Param { float f; };\n"
"[shader(\"raygeneration\")] void RayGenProto() { return; }\n"
"[shader(\"intersection\")] void IntersectionProto() { return; }\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"[shader(\"miss\")] void MissProto(inout Payload p) { p.f += 1.0; }\n"
"[shader(\"callable\")] void CallableProto(inout Param p) { p.f += 1.0; "
"}\n"
"\n"
"struct BadPayload { float2 f; }; struct BadAttributes { float3 b; };\n"
"struct BadParam { float2 f; };\n"
"export void BadRayGen() { return; }\n"
"export void BadIntersection() { return; }\n"
"export void BadAnyHit(inout BadPayload p, in BadAttributes a) { p.f += "
"a.b.x; }\n"
"export void BadClosestHit(inout BadPayload p, in BadAttributes a) { p.f "
"+= a.b.y; }\n"
"export void BadMiss(inout BadPayload p) { p.f += 1.0; }\n"
"export void BadCallable(inout BadParam p) { p.f += 1.0; }\n",
"lib_6_3",
{"!{void ()* @\"\\01?RayGenProto@@YAXXZ\", !\"\\01?RayGenProto@@YAXXZ\",",
"!{void ()* @\"\\01?IntersectionProto@@YAXXZ\", "
"!\"\\01?IntersectionProto@@YAXXZ\",",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*)* @\"\\01?MissProto@@YAXUPayload@@@Z\", "
"!\"\\01?MissProto@@YAXUPayload@@@Z\",",
"!{void (%struct.Param*)* @\"\\01?CallableProto@@YAXUParam@@@Z\", "
"!\"\\01?CallableProto@@YAXUParam@@@Z\","},
{"!{void ()* @\"\\01?BadRayGen@@YAXXZ\", !\"\\01?BadRayGen@@YAXXZ\",",
"!{void ()* @\"\\01?BadIntersection@@YAXXZ\", "
"!\"\\01?BadIntersection@@YAXXZ\",",
"!{void (%struct.BadPayload*, %struct.BadAttributes*)* "
"@\"\\01?BadAnyHit@@YAXUBadPayload@@UBadAttributes@@@Z\", "
"!\"\\01?BadAnyHit@@YAXUBadPayload@@UBadAttributes@@@Z\",",
"!{void (%struct.BadPayload*, %struct.BadAttributes*)* "
"@\"\\01?BadClosestHit@@YAXUBadPayload@@UBadAttributes@@@Z\", "
"!\"\\01?BadClosestHit@@YAXUBadPayload@@UBadAttributes@@@Z\",",
"!{void (%struct.BadPayload*)* @\"\\01?BadMiss@@YAXUBadPayload@@@Z\", "
"!\"\\01?BadMiss@@YAXUBadPayload@@@Z\",",
"!{void (%struct.BadParam*)* @\"\\01?BadCallable@@YAXUBadParam@@@Z\", "
"!\"\\01?BadCallable@@YAXUBadParam@@@Z\","},
{"For shader '\\01?BadAnyHit@@YAXUBadPayload@@UBadAttributes@@@Z', "
"payload size is smaller than argument's allocation size",
"For shader '\\01?BadAnyHit@@YAXUBadPayload@@UBadAttributes@@@Z', "
"attribute size is smaller than argument's allocation size",
"For shader '\\01?BadClosestHit@@YAXUBadPayload@@UBadAttributes@@@Z', "
"payload size is smaller than argument's allocation size",
"For shader '\\01?BadClosestHit@@YAXUBadPayload@@UBadAttributes@@@Z', "
"attribute size is smaller than argument's allocation size",
"For shader '\\01?BadMiss@@YAXUBadPayload@@@Z', payload size is smaller "
"than argument's allocation size",
"For shader '\\01?BadCallable@@YAXUBadParam@@@Z', params size is "
"smaller than argument's allocation size"},
false);
}
TEST_F(ValidationTest, WhenMissingPayloadThenFail) {
if (m_ver.SkipDxilVersion(1, 3))
return;
RewriteAssemblyCheckMsg(
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"struct Param { float f; };\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"[shader(\"miss\")] void MissProto(inout Payload p) { p.f += 1.0; }\n"
"[shader(\"callable\")] void CallableProto(inout Param p) { p.f += 1.0; "
"}\n"
"export void BadAnyHit(inout Payload p) { p.f += 1.0; }\n"
"export void BadClosestHit() {}\n"
"export void BadMiss() {}\n"
"export void BadCallable() {}\n",
"lib_6_3",
{"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*)* @\"\\01?MissProto@@YAXUPayload@@@Z\", "
"!\"\\01?MissProto@@YAXUPayload@@@Z\",",
"!{void (%struct.Param*)* @\"\\01?CallableProto@@YAXUParam@@@Z\", "
"!\"\\01?CallableProto@@YAXUParam@@@Z\","},
{"!{void (%struct.Payload*)* @\"\\01?BadAnyHit@@YAXUPayload@@@Z\", "
"!\"\\01?BadAnyHit@@YAXUPayload@@@Z\",",
"!{void ()* @\"\\01?BadClosestHit@@YAXXZ\", "
"!\"\\01?BadClosestHit@@YAXXZ\",",
"!{void ()* @\"\\01?BadMiss@@YAXXZ\", !\"\\01?BadMiss@@YAXXZ\",",
"!{void ()* @\"\\01?BadCallable@@YAXXZ\", "
"!\"\\01?BadCallable@@YAXXZ\","},
{"anyhit shader '\\01?BadAnyHit@@YAXUPayload@@@Z' missing required "
"attributes parameter",
"closesthit shader '\\01?BadClosestHit@@YAXXZ' missing required payload "
"parameter",
"closesthit shader '\\01?BadClosestHit@@YAXXZ' missing required "
"attributes parameter",
"miss shader '\\01?BadMiss@@YAXXZ' missing required payload parameter",
"callable shader '\\01?BadCallable@@YAXXZ' missing required params "
"parameter"},
false);
}
TEST_F(ValidationTest, ShaderFunctionReturnTypeVoid) {
if (m_ver.SkipDxilVersion(1, 3))
return;
// Verify resource not used in shader argument structure
RewriteAssemblyCheckMsg(
"struct Payload { float f; }; struct Attributes { float2 b; };\n"
"struct Param { float f; };\n"
"[shader(\"raygeneration\")] void RayGenProto() { return; }\n"
"[shader(\"anyhit\")] void AnyHitProto(inout Payload p, in Attributes a) "
"{ p.f += a.b.x; }\n"
"[shader(\"closesthit\")] void ClosestHitProto(inout Payload p, in "
"Attributes a) { p.f += a.b.y; }\n"
"[shader(\"miss\")] void MissProto(inout Payload p) { p.f += 1.0; }\n"
"[shader(\"callable\")] void CallableProto(inout Param p) { p.f += 1.0; "
"}\n"
"export float BadRayGen() { return 1; }\n"
"export float BadAnyHit(inout Payload p, in Attributes a) { return p.f; "
"}\n"
"export float BadClosestHit(inout Payload p, in Attributes a) { return "
"p.f; }\n"
"export float BadMiss(inout Payload p) { return p.f; }\n"
"export float BadCallable(inout Param p) { return p.f; }\n",
"lib_6_3",
{"!{void ()* @\"\\01?RayGenProto@@YAXXZ\", "
"!\"\\01?RayGenProto@@YAXXZ\",",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?AnyHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\", "
"!\"\\01?ClosestHitProto@@YAXUPayload@@UAttributes@@@Z\",",
"!{void (%struct.Payload*)* @\"\\01?MissProto@@YAXUPayload@@@Z\", "
"!\"\\01?MissProto@@YAXUPayload@@@Z\",",
"!{void (%struct.Param*)* @\"\\01?CallableProto@@YAXUParam@@@Z\", "
"!\"\\01?CallableProto@@YAXUParam@@@Z\","},
{"!{float ()* @\"\\01?BadRayGen@@YAMXZ\", "
"!\"\\01?BadRayGen@@YAMXZ\",",
"!{float (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?BadAnyHit@@YAMUPayload@@UAttributes@@@Z\", "
"!\"\\01?BadAnyHit@@YAMUPayload@@UAttributes@@@Z\",",
"!{float (%struct.Payload*, %struct.Attributes*)* "
"@\"\\01?BadClosestHit@@YAMUPayload@@UAttributes@@@Z\", "
"!\"\\01?BadClosestHit@@YAMUPayload@@UAttributes@@@Z\",",
"!{float (%struct.Payload*)* @\"\\01?BadMiss@@YAMUPayload@@@Z\", "
"!\"\\01?BadMiss@@YAMUPayload@@@Z\",",
"!{float (%struct.Param*)* @\"\\01?BadCallable@@YAMUParam@@@Z\", "
"!\"\\01?BadCallable@@YAMUParam@@@Z\","},
{"Shader function '\\01?BadRayGen@@YAMXZ' must have void return type",
"Shader function '\\01?BadAnyHit@@YAMUPayload@@UAttributes@@@Z' must "
"have void return type",
"Shader function '\\01?BadClosestHit@@YAMUPayload@@UAttributes@@@Z' "
"must have void return type",
"Shader function '\\01?BadMiss@@YAMUPayload@@@Z' must have void return "
"type",
"Shader function '\\01?BadCallable@@YAMUParam@@@Z' must have void "
"return type"},
false);
}
TEST_F(ValidationTest, MeshMultipleSetMeshOutputCounts) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\multipleSetMeshOutputCounts.hlsl");
}
TEST_F(ValidationTest, MeshMissingSetMeshOutputCounts) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\missingSetMeshOutputCounts.hlsl");
}
TEST_F(ValidationTest, MeshNonDominatingSetMeshOutputCounts) {
TestCheck(
L"..\\CodeGenHLSL\\mesh-val\\nonDominatingSetMeshOutputCounts.hlsl");
}
TEST_F(ValidationTest, MeshOversizePayload) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\msOversizePayload.hlsl");
}
TEST_F(ValidationTest, MeshOversizeOutput) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\msOversizeOutput.hlsl");
}
TEST_F(ValidationTest, MeshOversizePayloadOutput) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\msOversizePayloadOutput.hlsl");
}
TEST_F(ValidationTest, MeshMultipleGetMeshPayload) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"%([0-9]+) = call %struct.MeshPayload\\* "
"@dx.op.getMeshPayload.struct.MeshPayload\\(i32 170\\) ; "
"GetMeshPayload\\(\\)",
"%\\1 = call %struct.MeshPayload* "
"@dx.op.getMeshPayload.struct.MeshPayload(i32 170) ; GetMeshPayload()\n"
" %.extra.unused.payload. = call %struct.MeshPayload* "
"@dx.op.getMeshPayload.struct.MeshPayload(i32 170) ; GetMeshPayload()",
"GetMeshPayload cannot be called multiple times.", true);
}
TEST_F(ValidationTest, MeshOutofRangeMaxVertexCount) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{!([0-9]+), i32 32, i32 16, i32 2, i32 40}",
"= !{!\\1, i32 257, i32 16, i32 2, i32 40}",
"MS max vertex output count must be \\[0..256\\]. 257 specified", true);
}
TEST_F(ValidationTest, MeshOutofRangeMaxPrimitiveCount) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{!([0-9]+), i32 32, i32 16, i32 2, i32 40}",
"= !{!\\1, i32 32, i32 257, i32 2, i32 40}",
"MS max primitive output count must be \\[0..256\\]. 257 specified",
true);
}
TEST_F(ValidationTest, MeshLessThanMinX) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 0, i32 1, i32 1}",
"Declared Thread Group X size 0 outside valid range [1..128]");
}
TEST_F(ValidationTest, MeshGreaterThanMaxX) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 129, i32 1, i32 1}",
"Declared Thread Group X size 129 outside valid range [1..128]");
}
TEST_F(ValidationTest, MeshLessThanMinY) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 32, i32 0, i32 1}",
"Declared Thread Group Y size 0 outside valid range [1..128]");
}
TEST_F(ValidationTest, MeshGreaterThanMaxY) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 1, i32 129, i32 1}",
"Declared Thread Group Y size 129 outside valid range [1..128]");
}
TEST_F(ValidationTest, MeshLessThanMinZ) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 32, i32 1, i32 0}",
"Declared Thread Group Z size 0 outside valid range [1..128]");
}
TEST_F(ValidationTest, MeshGreaterThanMaxZ) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 1, i32 1, i32 129}",
"Declared Thread Group Z size 129 outside valid range [1..128]");
}
TEST_F(ValidationTest, MeshGreaterThanMaxXYZ) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"= !{i32 32, i32 1, i32 1}",
"= !{i32 32, i32 2, i32 4}",
"Declared Thread Group Count 256 (X*Y*Z) is beyond "
"the valid maximum of 128");
}
TEST_F(ValidationTest, MeshGreaterThanMaxVSigRowCount) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"!([0-9]+) = !{i32 1, !\"COLOR\", i8 9, i8 0, "
"!([0-9]+), i8 2, i32 4, i8 1, i32 1, i8 0, (.*)"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3}",
"!\\1 = !{i32 1, !\"COLOR\", i8 9, i8 0, !\\2, i8 2, "
"i32 32, i8 1, i32 1, i8 0, \\3"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, "
"i32 6, i32 7, i32 8, i32 9, i32 10,"
"i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 "
"17, i32 18, i32 19, i32 20,"
"i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, i32 "
"27, i32 28, i32 29, i32 30, i32 31}",
"For shader 'main', vertex output signatures are "
"taking up more than 32 rows",
true);
}
TEST_F(ValidationTest, MeshGreaterThanMaxPSigRowCount) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
"!([0-9]+) = !{i32 4, !\"LAYER\", i8 4, i8 0, "
"!([0-9]+), i8 1, i32 6, i8 1, i32 1, i8 0, (.*)"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5}",
"!\\1 = !{i32 4, !\"LAYER\", i8 4, i8 0, !\\2, i8 1, "
"i32 32, i8 1, i32 1, i8 0, \\3"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, "
"i32 6, i32 7, i32 8, i32 9, i32 10,"
"i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 "
"17, i32 18, i32 19, i32 20,"
"i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, i32 "
"27, i32 28, i32 29, i32 30, i32 31}",
"For shader 'main', primitive output signatures are "
"taking up more than 32 rows",
true);
}
TEST_F(ValidationTest, MeshGreaterThanMaxTotalSigRowCount) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\mesh.hlsl", "ms_6_5",
{"!([0-9]+) = !{i32 1, !\"COLOR\", i8 9, i8 0, !([0-9]+), i8 2, i32 4, "
"i8 1, i32 1, i8 0, (.*)"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3}",
"!([0-9]+) = !{i32 4, !\"LAYER\", i8 4, i8 0, !([0-9]+), i8 1, i32 6, "
"i8 1, i32 1, i8 0, (.*)"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5}"},
{
"!\\1 = !{i32 1, !\"COLOR\", i8 9, i8 0, !\\2, i8 2, i32 16, i8 1, "
"i32 1, i8 0, \\3"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, "
"i32 8, i32 9, i32 10,"
"i32 11, i32 12, i32 13, i32 14, i32 15}",
"!\\1 = !{i32 4, !\"LAYER\", i8 4, i8 0, !\\2, i8 1, i32 16, i8 1, "
"i32 1, i8 0, \\3"
"!\\2 = !{i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, "
"i32 8, i32 9, i32 10,"
"i32 11, i32 12, i32 13, i32 14, i32 15}",
},
"For shader 'main', vertex and primitive output signatures are taking up "
"more than 32 rows",
true);
}
TEST_F(ValidationTest, MeshOversizeSM) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\oversizeSM.hlsl");
}
TEST_F(ValidationTest, AmplificationMultipleDispatchMesh) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\multipleDispatchMesh.hlsl");
}
TEST_F(ValidationTest, AmplificationMissingDispatchMesh) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\missingDispatchMesh.hlsl");
}
TEST_F(ValidationTest, AmplificationNonDominatingDispatchMesh) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\nonDominatingDispatchMesh.hlsl");
}
TEST_F(ValidationTest, AmplificationOversizePayload) {
TestCheck(L"..\\CodeGenHLSL\\mesh-val\\asOversizePayload.hlsl");
}
TEST_F(ValidationTest, AmplificationLessThanMinX) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\amplification.hlsl", "as_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 0, i32 1, i32 1}",
"Declared Thread Group X size 0 outside valid range [1..128]");
}
TEST_F(ValidationTest, AmplificationGreaterThanMaxX) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\amplification.hlsl", "as_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 129, i32 1, i32 1}",
"Declared Thread Group X size 129 outside valid range [1..128]");
}
TEST_F(ValidationTest, AmplificationLessThanMinY) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\amplification.hlsl", "as_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 32, i32 0, i32 1}",
"Declared Thread Group Y size 0 outside valid range [1..128]");
}
TEST_F(ValidationTest, AmplificationGreaterThanMaxY) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\amplification.hlsl", "as_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 1, i32 129, i32 1}",
"Declared Thread Group Y size 129 outside valid range [1..128]");
}
TEST_F(ValidationTest, AmplificationLessThanMinZ) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\amplification.hlsl", "as_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 32, i32 1, i32 0}",
"Declared Thread Group Z size 0 outside valid range [1..128]");
}
TEST_F(ValidationTest, AmplificationGreaterThanMaxZ) {
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\mesh-val\\amplification.hlsl", "as_6_5",
"= !{i32 32, i32 1, i32 1}", "= !{i32 1, i32 1, i32 129}",
"Declared Thread Group Z size 129 outside valid range [1..128]");
}
TEST_F(ValidationTest, AmplificationGreaterThanMaxXYZ) {
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\mesh-val\\amplification.hlsl",
"as_6_5", "= !{i32 32, i32 1, i32 1}",
"= !{i32 32, i32 2, i32 4}",
"Declared Thread Group Count 256 (X*Y*Z) is beyond "
"the valid maximum of 128");
}
TEST_F(ValidationTest, ValidateRootSigContainer) {
// Validation of root signature-only container not supported until 1.5
if (m_ver.SkipDxilVersion(1, 5))
return;
LPCSTR pSource = "#define main \"DescriptorTable(UAV(u0))\"";
CComPtr<IDxcBlob> pObject;
if (!CompileSource(pSource, "rootsig_1_0", &pObject))
return;
CheckValidationMsgs(pObject, {}, false,
DxcValidatorFlags_RootSignatureOnly |
DxcValidatorFlags_InPlaceEdit);
pObject.Release();
if (!CompileSource(pSource, "rootsig_1_1", &pObject))
return;
CheckValidationMsgs(pObject, {}, false,
DxcValidatorFlags_RootSignatureOnly |
DxcValidatorFlags_InPlaceEdit);
}
TEST_F(ValidationTest, ValidatePrintfNotAllowed) {
TestCheck(L"..\\CodeGenHLSL\\printf.hlsl");
}
TEST_F(ValidationTest, ValidateWithHash) {
if (m_ver.SkipDxilVersion(1, 8))
return;
CComPtr<IDxcBlob> pProgram;
CompileSource("float4 main(float a:A, float b:B) : SV_Target { return 1; }",
"ps_6_0", &pProgram);
CComPtr<IDxcValidator> pValidator;
CComPtr<IDxcOperationResult> pResult;
unsigned Flags = 0;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcValidator, &pValidator));
// With hash.
VERIFY_SUCCEEDED(pValidator->Validate(pProgram, Flags, &pResult));
// Make sure the validation was successful.
HRESULT status;
VERIFY_IS_NOT_NULL(pResult);
CComPtr<IDxcBlob> pValidationOutput;
pResult->GetStatus(&status);
VERIFY_SUCCEEDED(status);
pResult->GetResult(&pValidationOutput);
// Make sure the validation output is not null when hashing.
VERIFY_SUCCEEDED(pValidationOutput != nullptr);
hlsl::DxilContainerHeader *pHeader =
(hlsl::DxilContainerHeader *)pProgram->GetBufferPointer();
// Validate the hash.
constexpr uint32_t HashStartOffset =
offsetof(struct DxilContainerHeader, Version);
auto *DataToHash = (const BYTE *)pHeader + HashStartOffset;
UINT AmountToHash = pHeader->ContainerSizeInBytes - HashStartOffset;
BYTE Result[DxilContainerHashSize];
ComputeHashRetail(DataToHash, AmountToHash, Result);
VERIFY_ARE_EQUAL(memcmp(Result, pHeader->Hash.Digest, sizeof(Result)), 0);
}
TEST_F(ValidationTest, ValidateVersionNotAllowed) {
if (m_ver.SkipDxilVersion(1, 6))
return;
// When validator version is < dxil verrsion, compiler has a newer version
// than validator. We are checking the validator, so only use the validator
// version.
// This will also assume that the versions are tied together. This has always
// been the case, but it's not assumed that it has to be the case. If the
// versions diverged, it would be impossible to tell what DXIL version a
// validator supports just from the version returned in the IDxcVersion
// interface, without separate knowledge of the supported dxil version based
// on the validator version. If these versions must diverge in the future, we
// could rev the IDxcVersion interface to accomodate.
std::string maxMinor = std::to_string(m_ver.m_ValMinor);
std::string higherMinor = std::to_string(m_ver.m_ValMinor + 1);
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\basic.hlsl", "ps_6_0",
("= !{i32 1, i32 " + maxMinor + "}").c_str(),
("= !{i32 1, i32 " + higherMinor + "}").c_str(),
("error: Validator version in metadata (1." +
higherMinor + ") is not supported; maximum: (1." +
maxMinor + ")")
.c_str());
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\basic.hlsl", "ps_6_0",
"= !{i32 1, i32 0}", "= !{i32 1, i32 1}",
"error: Shader model requires Dxil Version 1.0");
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\basic.hlsl", "ps_6_0",
"= !{i32 1, i32 0}",
("= !{i32 1, i32 " + higherMinor + "}").c_str(),
("error: Dxil version in metadata (1." + higherMinor +
") is not supported; maximum: (1." + maxMinor + ")")
.c_str());
}
TEST_F(ValidationTest, CreateHandleNotAllowedSM66) {
if (m_ver.SkipDxilVersion(1, 6))
return;
RewriteAssemblyCheckMsg(L"..\\CodeGenHLSL\\basic.hlsl", "ps_6_5",
{"= !{i32 1, i32 5}", "= !{!\"ps\", i32 6, i32 5}"},
{"= !{i32 1, i32 6}", "= !{!\"ps\", i32 6, i32 6}"},
"opcode 'CreateHandle' should only be used in "
"'Shader model 6.5 and below'");
RewriteAssemblyCheckMsg(
L"..\\CodeGenHLSL\\basic.hlsl", "lib_6_5",
{"call %dx.types.Handle "
"@\"dx.op.createHandleForLib.class.Buffer<vector<float, 4> >\"\\(i32 "
"160, %\"class.Buffer<vector<float, 4> >\" %[0-9]+\\)",
"declare %dx.types.Handle "
"@\"dx.op.createHandleForLib.class.Buffer<vector<float, 4> >\"\\(i32, "
"%\"class.Buffer<vector<float, 4> >\"\\) #1"},
{"call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 0, "
"i1 false)",
"declare %dx.types.Handle @dx.op.createHandle(i32, i8, i32, i32, i1) "
"#1"},
"opcode 'CreateHandle' should only be used in 'non-library targets'",
true);
}
// Check for validation errors for various const dests to atomics
TEST_F(ValidationTest, AtomicsConsts) {
if (m_ver.SkipDxilVersion(1, 7))
return;
std::vector<LPCWSTR> pArguments = {L"-HV", L"2021", L"-Zi"};
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %rw_structbuf_UAV_structbuf"},
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %ro_structbuf_texture_structbuf"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %rw_structbuf_UAV_structbuf"},
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %ro_structbuf_texture_structbuf"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %rw_buf_UAV_buf"},
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %ro_buf_texture_buf"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %rw_buf_UAV_buf"},
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %ro_buf_texture_buf"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %rw_tex_UAV_1d"},
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %ro_tex_texture_1d"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %rw_tex_UAV_1d"},
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %ro_tex_texture_1d"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\atomics.hlsl", "cs_6_0", pArguments.data(), 3,
nullptr, 0,
{"call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle "
"%rw_buf_UAV_buf"},
{"call i32 @dx.op.atomicBinOp.i32(i32 78, %dx.types.Handle %CB_cbuffer"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %rw_buf_UAV_buf"},
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %CB_cbuffer"},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %rw_buf_UAV_buf"},
{"call i32 @dx.op.atomicBinOp.i32(i32 78, "
"%dx.types.Handle %\"$Globals_cbuffer\""},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %rw_buf_UAV_buf"},
{"call i32 @dx.op.atomicCompareExchange.i32(i32 79, "
"%dx.types.Handle %\"$Globals_cbuffer\""},
"Non-UAV destination to atomic intrinsic.", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\atomics.hlsl", "cs_6_0", pArguments.data(), 3,
nullptr, 0, {"atomicrmw add i32 addrspace(3)* @\"\\01?gs_var@@3IA\""},
{"atomicrmw add i32 addrspace(3)* @\"\\01?cgs_var@@3IB\""},
"Constant destination to atomic.", false);
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\atomics.hlsl", "cs_6_0",
pArguments.data(), 3, nullptr, 0,
{"cmpxchg i32 addrspace(3)* @\"\\01?gs_var@@3IA\""},
{"cmpxchg i32 addrspace(3)* @\"\\01?cgs_var@@3IB\""},
"Constant destination to atomic.", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\atomics.hlsl", "cs_6_0", pArguments.data(), 3,
nullptr, 0,
{"%([a-zA-Z0-9]+) = getelementptr \\[3 x i32\\], \\[3 x i32\\] "
"addrspace\\(3\\)\\* @\"\\\\01\\?cgs_arr@@3QBIB\"([^\n]*)"},
{"%\\1 = getelementptr \\[3 x i32\\], \\[3 x i32\\] addrspace\\(3\\)\\* "
"@\"\\\\01\\?cgs_arr@@3QBIB\"\\2\n"
"%dummy = atomicrmw add i32 addrspace\\(3\\)\\* %\\1, i32 1 seq_cst, "
"!dbg !104 ; line:51 col:3"},
"Constant destination to atomic.", true);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\atomics.hlsl", "cs_6_0", pArguments.data(), 3,
nullptr, 0,
{"%([a-zA-Z0-9]+) = getelementptr \\[3 x i32\\], \\[3 x i32\\] "
"addrspace\\(3\\)\\* @\"\\\\01\\?cgs_arr@@3QBIB\"([^\n]*)"},
{"%\\1 = getelementptr \\[3 x i32\\], \\[3 x i32\\] addrspace\\(3\\)\\* "
"@\"\\\\01\\?cgs_arr@@3QBIB\"\\2\n"
"%dummy = cmpxchg i32 addrspace\\(3\\)\\* %\\1, i32 1, i32 2 seq_cst "
"seq_cst, !dbg !105 ;"},
"Constant destination to atomic.", true);
}
// Check validation error for non-groupshared dest
TEST_F(ValidationTest, AtomicsInvalidDests) {
// Technically, an error is generated for validator version 1.7, however,
// the error message was updated in validator version 1.8, so this test now
// requires version 1.8.
if (m_ver.SkipDxilVersion(1, 8))
return;
std::vector<LPCWSTR> pArguments = {L"-HV", L"2021", L"-Zi"};
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\atomics.hlsl", "lib_6_3", pArguments.data(), 2,
nullptr, 0, {"atomicrmw add i32 addrspace(3)* @\"\\01?gs_var@@3IA\""},
{"atomicrmw add i32* %res"},
"Non-groupshared or node record destination to atomic operation.", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\atomics.hlsl", "lib_6_3", pArguments.data(), 2,
nullptr, 0, {"cmpxchg i32 addrspace(3)* @\"\\01?gs_var@@3IA\""},
{"cmpxchg i32* %res"},
"Non-groupshared or node record destination to atomic operation.", false);
}
// Errors are expected for compute shaders when:
// - a broadcasting node has an input record and/or output records
// - the launch type is not broadcasting
// This test operates by changing the [Shader("node")] metadata entry
// to [Shader("compute")] for each shader in turn.
// It also changes the coalescing to thread in the 2nd to last test case,
// after swapping out the shader kind to compute.
TEST_F(ValidationTest, ComputeNodeCompatibility) {
if (m_ver.SkipDxilVersion(1, 7))
return;
std::vector<LPCWSTR> pArguments = {L"-HV", L"2021"};
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\compute_node_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!11 = !{i32 8, i32 15"}, // original: node shader
{"!11 = !{i32 8, i32 5"}, // changed to: compute shader
"Compute entry 'node01' has unexpected node shader metadata", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\compute_node_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!19 = !{i32 8, i32 15"}, // original: node shader
{"!19 = !{i32 8, i32 5"}, // changed to: compute shader
"Compute entry 'node02' has unexpected node shader metadata", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\compute_node_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!25 = !{i32 8, i32 15"}, // original: node shader
{"!25 = !{i32 8, i32 5"}, // changed to: compute shader
"Compute entry 'node03' has unexpected node shader metadata", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\compute_node_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!32 = !{i32 8, i32 15"}, // original: node shader
{"!32 = !{i32 8, i32 5"}, // changed to: compute shader
"Compute entry 'node04' has unexpected node shader metadata", false);
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\compute_node_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!32 = !{i32 8, i32 15, i32 13, i32 2"}, // original: node shader,
// coalesing launch type
{"!32 = !{i32 8, i32 5, i32 13, i32 3"}, // changed to: compute shader,
// thread launch type
"Compute entry 'node04' has unexpected node shader metadata", false);
}
// Check validation error for incompatible node input record types
TEST_F(ValidationTest, NodeInputCompatibility) {
if (m_ver.SkipDxilVersion(1, 7))
return;
std::vector<LPCWSTR> pArguments = {L"-HV", L"2021"};
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!13 = !{i32 1, i32 97"}, // DispatchNodeInputRecord
{"!13 = !{i32 1, i32 65"}, // GroupNodeInputRecords
"broadcasting node shader 'node01' has incompatible input record type "
"(should be {RW}DispatchNodeInputRecord)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!13 = !{i32 1, i32 97"}, // DispatchNodeInputRecord
{"!13 = !{i32 1, i32 69"}, // RWGroupNodeInputRecords
"broadcasting node shader 'node01' has incompatible input record type "
"(should be {RW}DispatchNodeInputRecord)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!13 = !{i32 1, i32 97"}, // DispatchNodeInputRecord
{"!13 = !{i32 1, i32 33"}, // ThreadNodeInputRecord
"broadcasting node shader 'node01' has incompatible input record type "
"(should be {RW}DispatchNodeInputRecord)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!13 = !{i32 1, i32 97"}, // DispatchNodeInputRecord
{"!13 = !{i32 1, i32 37"}, // RWThreadNodeInputRecord
"broadcasting node shader 'node01' has incompatible input record type "
"(should be {RW}DispatchNodeInputRecord)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!20 = !{i32 1, i32 65"}, // GroupNodeInputRecords
{"!20 = !{i32 1, i32 97"}, // DispatchNodeInputRecord
"coalescing node shader 'node02' has incompatible input record type "
"(should be {RW}GroupNodeInputRecords or EmptyNodeInput)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!20 = !{i32 1, i32 65"}, // GroupNodeInputRecords
{"!20 = !{i32 1, i32 101"}, // RWDispatchNodeInputRecord
"coalescing node shader 'node02' has incompatible input record type "
"(should be {RW}GroupNodeInputRecords or EmptyNodeInput)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!20 = !{i32 1, i32 65"}, // GroupNodeInputRecords
{"!20 = !{i32 1, i32 33"}, // ThreadNodeInputRecord
"coalescing node shader 'node02' has incompatible input record type "
"(should be {RW}GroupNodeInputRecords or EmptyNodeInput)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!20 = !{i32 1, i32 65"}, // GroupNodeInputRecords
{"!20 = !{i32 1, i32 37"}, // RWThreadNodeInputRecord
"coalescing node shader 'node02' has incompatible input record type "
"(should be {RW}GroupNodeInputRecords or EmptyNodeInput)");
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\node_input_compatibility.hlsl",
"lib_6_8", pArguments.data(), 2, nullptr, 0,
{"!25 = !{i32 1, i32 33"}, // ThreadNodeInputRecord
{"!25 = !{i32 1, i32 97"}, // DispatchNodeInputRecord
"thread node shader 'node03' has incompatible input "
"record type (should be {RW}ThreadNodeInputRecord)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!25 = !{i32 1, i32 33"}, // ThreadNodeInputRecord
{"!25 = !{i32 1, i32 101"}, // RWDispatchNodeInputRecord
"thread node shader 'node03' has incompatible input record type (should "
"be {RW}ThreadNodeInputRecord)");
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\node_input_compatibility.hlsl",
"lib_6_8", pArguments.data(), 2, nullptr, 0,
{"!25 = !{i32 1, i32 33"}, // ThreadNodeInputRecord
{"!25 = !{i32 1, i32 65"}, // GroupNodeInputRecords
"thread node shader 'node03' has incompatible input "
"record type (should be {RW}ThreadNodeInputRecord)");
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\node_input_compatibility.hlsl",
"lib_6_8", pArguments.data(), 2, nullptr, 0,
{"!25 = !{i32 1, i32 33"}, // ThreadNodeInputRecord
{"!25 = !{i32 1, i32 69"}, // RWGroupNodeInputRecords
"thread node shader 'node03' has incompatible input "
"record type (should be {RW}ThreadNodeInputRecord)");
RewriteAssemblyCheckMsg(L"..\\DXILValidation\\node_input_compatibility.hlsl",
"lib_6_8", pArguments.data(), 2, nullptr, 0,
{"!25 = !{i32 1, i32 33"}, // ThreadNodeInputRecord
{"!25 = !{i32 1, i32 69"}, // RWGroupNodeInputRecords
"thread node shader 'node03' has incompatible input "
"record type (should be {RW}ThreadNodeInputRecord)");
}
// Check validation error for multiple input nodes of different types
TEST_F(ValidationTest, NodeInputMultiplicity) {
if (m_ver.SkipDxilVersion(1, 7))
return;
std::vector<LPCWSTR> pArguments = {L"-HV", L"2021"};
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!12 = !{!13}", // input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n"}, // end of output
{"!12 = !{!13, !100}", // multiple input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n!100 = !{i32 1, i32 97, i32 2, "
"!14}"}, // extra DispatchNodeInputRecord
"node shader 'node01' may not have more than one input record (2 are "
"declared)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!12 = !{!13}", // input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n"}, // end of output
{"!12 = !{!13, !100}", // multiple input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n!100 = !{i32 1, i32 9, i32 2, "
"!14}"}, // extra EmptyNodeInput
"node shader 'node01' may not have more than one input record (2 are "
"declared)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!19 = !{!20}", // input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n"}, // end of output
{"!19 = !{!20, !100}", // multiple input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n!100 = !{i32 1, i32 65, i32 2, "
"!14}"}, // extra GroupNodeInputRecords
"node shader 'node02' may not have more than one input record (2 are "
"declared)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!19 = !{!20}", // input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n"}, // end of output
{"!19 = !{!20, !100}", // multiple input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n!100 = !{i32 1, i32 9, i32 2, "
"!14}"}, // extra EmptyNodeInput
"node shader 'node02' may not have more than one input record (2 are "
"declared)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!24 = !{!25}", // input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n"}, // end of output
{"!24 = !{!25, !100}", // multiple input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n!100 = !{i32 1, i32 33, i32 2, "
"!14}"}, // extra ThreadNodeInputRecord
"node shader 'node03' may not have more than one input record (2 are "
"declared)");
RewriteAssemblyCheckMsg(
L"..\\DXILValidation\\node_input_compatibility.hlsl", "lib_6_8",
pArguments.data(), 2, nullptr, 0,
{"!24 = !{!25}", // input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n"}, // end of output
{"!24 = !{!25, !100}", // multiple input records
"!25 = !{i32 1, i32 33, i32 2, !14}\n!100 = !{i32 1, i32 9, i32 2, "
"!14}"}, // extra EmptyNodeInput
"node shader 'node03' may not have more than one input record (2 are "
"declared)");
}
TEST_F(ValidationTest, CacheInitWithMinPrec) {
if (!m_ver.m_InternalValidator)
if (m_ver.SkipDxilVersion(1, 8))
return;
// Ensures type cache is property initialized when in min-precision mode
TestCheck(L"..\\DXILValidation\\val-dx-type-minprec.ll");
}
TEST_F(ValidationTest, CacheInitWithLowPrec) {
if (!m_ver.m_InternalValidator)
if (m_ver.SkipDxilVersion(1, 8))
return;
// Ensures type cache is property initialized when in exact low-precision mode
TestCheck(L"..\\DXILValidation\\val-dx-type-lowprec.ll");
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/FunctionTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// FunctionTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// The testing is done primarily through the compiler interface to avoid //
// linking the full Clang libraries. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Test/CompilationResult.h"
#include "dxc/Test/HLSLTestData.h"
#include <memory>
#include <string>
#include <vector>
#undef _read
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/Support/Global.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HlslTestUtils.h"
#ifdef _WIN32
class FunctionTest {
#else
class FunctionTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(FunctionTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_METHOD(AllowedStorageClass)
TEST_METHOD(AllowedInParamUsesClass)
TEST_METHOD(ParseRootSignature)
dxc::DxcDllSupport m_support;
std::vector<char> rootSigText;
std::string BuildSampleFunction(const char *StorageClassKeyword) {
char result[128];
sprintf_s(result, _countof(result), "%s float ps(float o) { return o; }",
StorageClassKeyword);
return std::string(result);
}
void CheckCompiles(const std::string &text, bool expected) {
CheckCompiles(text.c_str(), text.size(), expected);
}
void CheckCompiles(const char *text, size_t textLen, bool expected) {
CompilationResult result(
CompilationResult::CreateForProgram(text, textLen));
EXPECT_EQ(expected, result.ParseSucceeded()); // << "for program " << text;
}
void TestHLSLRootSignatureVerCase(const char *pStr,
const std::wstring &forceVer,
HRESULT expected) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
CComPtr<IDxcLibrary> pLibrary;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcOperationResult> pResult;
CComPtr<IDxcBlobEncoding> pSource;
HRESULT resultStatus;
CComPtr<IDxcIncludeHandler> pIncludeHandler;
VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
const char pFormat[] = "[RootSignature(\"%s\")]\r\n"
"float4 main() : SV_Target { return 0; }";
size_t len = strlen(pStr) + strlen(pFormat) +
1; // Actually bigger than needed because of '%s'
rootSigText.resize(len);
sprintf_s(rootSigText.data(), rootSigText.size(), pFormat, pStr);
Utf8ToBlob(m_support, rootSigText.data(), &pSource);
VERIFY_SUCCEEDED(pLibrary->CreateIncludeHandler(&pIncludeHandler));
VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcCompiler, &pCompiler));
std::vector<LPCWSTR> flags;
if (!forceVer.empty()) {
flags.push_back(L"/force_rootsig_ver");
flags.push_back(forceVer.c_str());
}
VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
L"ps_6_0", flags.data(), flags.size(),
nullptr, 0, pIncludeHandler, &pResult));
VERIFY_SUCCEEDED(pResult->GetStatus(&resultStatus));
if (expected != resultStatus && FAILED(resultStatus)) {
// Unexpected failure, log results.
CComPtr<IDxcBlobEncoding> pErrors;
pResult->GetErrorBuffer(&pErrors);
std::string text = BlobToUtf8(pErrors);
CA2W textW(text.c_str());
WEX::Logging::Log::Comment(textW.m_psz);
}
VERIFY_ARE_EQUAL(expected, resultStatus);
if (SUCCEEDED(resultStatus)) {
CComPtr<IDxcContainerReflection> pReflection;
CComPtr<IDxcBlob> pContainer;
VERIFY_SUCCEEDED(pResult->GetResult(&pContainer));
VERIFY_SUCCEEDED(
m_support.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
VERIFY_SUCCEEDED(pReflection->Load(pContainer));
UINT count;
bool found = false;
VERIFY_SUCCEEDED(pReflection->GetPartCount(&count));
for (UINT i = 0; i < count; ++i) {
UINT kind;
VERIFY_SUCCEEDED(pReflection->GetPartKind(i, &kind));
if (kind == hlsl::DFCC_RootSignature) {
found = true;
break;
}
}
VERIFY_IS_TRUE(found);
}
}
void TestHLSLRootSignature10Case(const char *pStr, HRESULT hr) {
TestHLSLRootSignatureVerCase(pStr, L"rootsig_1_0", hr);
}
void TestHLSLRootSignature11Case(const char *pStr, HRESULT hr) {
TestHLSLRootSignatureVerCase(pStr, L"rootsig_1_1", hr);
}
void TestHLSLRootSignatureCase(const char *pStr, HRESULT hr) {
TestHLSLRootSignatureVerCase(pStr, L"", hr);
TestHLSLRootSignature10Case(pStr, hr);
TestHLSLRootSignature11Case(pStr, hr);
}
};
TEST_F(FunctionTest, AllowedStorageClass) {
for (const auto &sc : StorageClassData) {
CheckCompiles(BuildSampleFunction(sc.Keyword), sc.IsValid);
}
}
TEST_F(FunctionTest, AllowedInParamUsesClass) {
const char *fragments[] = {"f", "1.0f"};
for (const auto &iop : InOutParameterModifierData) {
for (unsigned i = 0; i < _countof(fragments); i++) {
char program[256];
sprintf_s(program, _countof(program),
"float ps(%s float o) { return o; }\n"
"void caller() { float f; ps(%s); }",
iop.Keyword, fragments[i]);
bool callerIsRef = i == 0;
bool expectedSucceeds =
(callerIsRef == iop.ActsAsReference) || !iop.ActsAsReference;
CheckCompiles(program, strlen(program), expectedSucceeds);
}
}
}
TEST_F(FunctionTest, ParseRootSignature) {
#ifdef _WIN32 // - dxil.dll can only be found on Windows
struct AutoModule {
HMODULE m_module;
AutoModule(const wchar_t *pName) { m_module = LoadLibraryW(pName); }
~AutoModule() {
if (m_module != NULL)
FreeLibrary(m_module);
}
};
AutoModule dxilAM(
L"dxil.dll"); // Pin this if available to avoid reloading on each compile.
#endif // _WIN32 - dxil.dll can only be found on Windows
VERIFY_SUCCEEDED(m_support.Initialize());
// Empty
TestHLSLRootSignatureCase("", S_OK);
TestHLSLRootSignatureCase(" ", S_OK);
TestHLSLRootSignatureCase(" 324 ;jk ", E_FAIL);
// Flags
TestHLSLRootSignatureCase("RootFlags( 0 )", S_OK);
TestHLSLRootSignatureCase("RootFlags( 20 )", E_FAIL);
TestHLSLRootSignatureCase("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)",
S_OK);
TestHLSLRootSignatureCase("RootFlags(ALLOW_STREAM_OUTPUT)", S_OK);
TestHLSLRootSignatureCase("RootFlags(LOCAL_ROOT_SIGNATURE)", E_FAIL);
TestHLSLRootSignatureCase("RootFlags( LLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)",
E_FAIL);
TestHLSLRootSignatureCase(
" RootFlags ( ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT ) ", S_OK);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | "
"DENY_VERTEX_SHADER_ROOT_ACCESS | DENY_HULL_SHADER_ROOT_ACCESS | "
"DENY_DOMAIN_SHADER_ROOT_ACCESS | DENY_GEOMETRY_SHADER_ROOT_ACCESS | "
"DENY_PIXEL_SHADER_ROOT_ACCESS)",
S_OK);
TestHLSLRootSignatureCase("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT & "
"DENY_VERTEX_SHADER_ROOT_ACCESS)",
E_FAIL);
TestHLSLRootSignatureCase("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | 7)",
E_FAIL);
// RootConstants: RootConstants(num32BitConstants=3, b2 [, space = 5] )
TestHLSLRootSignatureCase("RootConstants( num32BitConstants=3, b2)", S_OK);
TestHLSLRootSignatureCase(
"RootConstants( num32BitConstants=3, b2, space = 5)", S_OK);
TestHLSLRootSignatureCase(
"RootConstants( b2, num32BitConstants=3, space = 5)", S_OK);
TestHLSLRootSignatureCase("RootConstants( num32BitConstants=3, b2, "
"visibility=SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase("RootConstants( num32BitConstants=3, b2, space = "
"5, visibility = SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase(
"RootConstants( visibility = SHADER_VISIBILITY_PIXEL, space = 5, "
"num32BitConstants=3, b2)",
S_OK);
TestHLSLRootSignatureCase(
"RootConstants( visibility = SHADER_VISIBILITY_PIXEL, space = 5, "
"num32BitConstants=3, b2, visibility = SHADER_VISIBILITY_ALL)",
E_FAIL);
TestHLSLRootSignatureCase(
"RootConstants( visibility = SHADER_VISIBILITY_PIXEL, space = 5, space = "
"5, num32BitConstants=3, b2)",
E_FAIL);
TestHLSLRootSignatureCase(
"RootConstants( num32BitConstants=7, visibility = "
"SHADER_VISIBILITY_PIXEL, space = 5, num32BitConstants=3, b2)",
E_FAIL);
TestHLSLRootSignatureCase(
"RootConstants( b10, visibility = SHADER_VISIBILITY_PIXEL, space = 5, "
"num32BitConstants=3, b2)",
E_FAIL);
// RS CBV: CBV(b0 [, space=3, flags=0, visibility = SHADER_VISIBILITY_ALL ] )
TestHLSLRootSignatureCase("CBV(b2)", S_OK);
TestHLSLRootSignatureCase("CBV(t2)", E_FAIL);
TestHLSLRootSignatureCase("CBV(u2)", E_FAIL);
TestHLSLRootSignatureCase("CBV(s2)", E_FAIL);
TestHLSLRootSignatureCase("CBV(b4294967295)", S_OK);
TestHLSLRootSignatureCase("CBV(b2, space = 5)", S_OK);
TestHLSLRootSignatureCase("CBV(b2, space = 4294967279)", S_OK);
TestHLSLRootSignatureCase("CBV(b2, visibility = SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase(
"CBV(b2, space = 5, visibility = SHADER_VISIBILITY_PIXEL)", S_OK);
TestHLSLRootSignatureCase(
"CBV(space = 5, visibility = SHADER_VISIBILITY_PIXEL, b2)", S_OK);
TestHLSLRootSignatureCase(
"CBV(b2, space = 5, b2, visibility = SHADER_VISIBILITY_PIXEL)", E_FAIL);
TestHLSLRootSignatureCase(
"CBV(space = 4, b2, space = 5, visibility = SHADER_VISIBILITY_PIXEL)",
E_FAIL);
TestHLSLRootSignatureCase("CBV(b2, visibility = SHADER_VISIBILITY_PIXEL, "
"space = 5, visibility = SHADER_VISIBILITY_PIXEL)",
E_FAIL);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), CBV(b2, space = 5, "
"visibility = SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), "
"CBV(b2, space = 5, visibility = SHADER_VISIBILITY_PIXEL), "
"CBV(b4, space = 7, visibility = SHADER_VISIBILITY_VERTEX)",
S_OK);
// RS SRV: SRV(t0 [, space=3, flags=0, visibility = SHADER_VISIBILITY_ALL ] )
TestHLSLRootSignatureCase("SRV(t2)", S_OK);
TestHLSLRootSignatureCase("SRV(b2)", E_FAIL);
TestHLSLRootSignatureCase("SRV(u2)", E_FAIL);
TestHLSLRootSignatureCase("SRV(s2)", E_FAIL);
TestHLSLRootSignatureCase("SRV(t2, space = 5)", S_OK);
TestHLSLRootSignatureCase("SRV(t2, visibility = SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase(
"SRV(t2, space = 5, visibility = SHADER_VISIBILITY_PIXEL)", S_OK);
TestHLSLRootSignatureCase(
"SRV(space = 5, visibility = SHADER_VISIBILITY_PIXEL, t2)", S_OK);
TestHLSLRootSignatureCase(
"SRV(t2, space = 5, t2, visibility = SHADER_VISIBILITY_PIXEL)", E_FAIL);
TestHLSLRootSignatureCase(
"SRV(space = 4, t2, space = 5, visibility = SHADER_VISIBILITY_PIXEL)",
E_FAIL);
TestHLSLRootSignatureCase("SRV(t2, visibility = SHADER_VISIBILITY_PIXEL, "
"space = 5, visibility = SHADER_VISIBILITY_PIXEL)",
E_FAIL);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), SRV(t2, space = 5, "
"visibility = SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), "
"SRV(t2, space = 5, visibility = SHADER_VISIBILITY_PIXEL), "
"SRV(t4, space = 7, visibility = SHADER_VISIBILITY_VERTEX)",
S_OK);
// RS UAV: UAV(u0 [, space=3, flags=0, visibility = SHADER_VISIBILITY_ALL ] )
TestHLSLRootSignatureCase("UAV(u2)", S_OK);
TestHLSLRootSignatureCase("UAV(b2)", E_FAIL);
TestHLSLRootSignatureCase("UAV(t2)", E_FAIL);
TestHLSLRootSignatureCase("UAV(s2)", E_FAIL);
TestHLSLRootSignatureCase("UAV(u2, space = 5)", S_OK);
TestHLSLRootSignatureCase("UAV(u2, visibility = SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase(
"UAV(u2, space = 5, visibility = SHADER_VISIBILITY_PIXEL)", S_OK);
TestHLSLRootSignatureCase(
"UAV(space = 5, visibility = SHADER_VISIBILITY_PIXEL, u2)", S_OK);
TestHLSLRootSignatureCase(
"UAV(u2, space = 5, u2, visibility = SHADER_VISIBILITY_PIXEL)", E_FAIL);
TestHLSLRootSignatureCase(
"UAV(space = 4, u2, space = 5, visibility = SHADER_VISIBILITY_PIXEL)",
E_FAIL);
TestHLSLRootSignatureCase("UAV(u2, visibility = SHADER_VISIBILITY_PIXEL, "
"space = 5, visibility = SHADER_VISIBILITY_PIXEL)",
E_FAIL);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), "
"UAV(u2, space = 5, visibility = SHADER_VISIBILITY_PIXEL)",
S_OK);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), "
"UAV(u2, space = 5, visibility = SHADER_VISIBILITY_PIXEL), "
"UAV(u4, space = 7, visibility = SHADER_VISIBILITY_VERTEX)",
S_OK);
// RS1.1 root descriptor flags.
TestHLSLRootSignature11Case("CBV(b2, flags=0)", S_OK);
TestHLSLRootSignature11Case("CBV(b2, flags=DATA_VOLATILE)", S_OK);
TestHLSLRootSignature11Case("SRV(t2, flags=DATA_STATIC)", S_OK);
TestHLSLRootSignature11Case("UAV(u2, flags=DATA_STATIC_WHILE_SET_AT_EXECUTE)",
S_OK);
TestHLSLRootSignature11Case(
"UAV(u2, flags=DATA_STATIC_WHILE_SET_AT_EXECUTE, space = 5)", S_OK);
TestHLSLRootSignature10Case("CBV(b2, flags=0)", E_FAIL);
TestHLSLRootSignature10Case("CBV(b2, flags=DATA_VOLATILE)", E_FAIL);
TestHLSLRootSignature10Case("SRV(t2, flags=DATA_STATIC)", E_FAIL);
TestHLSLRootSignature10Case("UAV(u2, flags=DATA_STATIC_WHILE_SET_AT_EXECUTE)",
E_FAIL);
TestHLSLRootSignature11Case("CBV(b2, flags=DATA_VOLATILE | DATA_STATIC)",
E_FAIL);
TestHLSLRootSignature11Case(
"CBV(b2, flags=DATA_STATIC_WHILE_SET_AT_EXECUTE| DATA_STATIC)", E_FAIL);
TestHLSLRootSignature11Case(
"CBV(b2, flags=DATA_STATIC_WHILE_SET_AT_EXECUTE|DATA_VOLATILE)", E_FAIL);
TestHLSLRootSignature11Case(
"UAV(u2, flags=DATA_STATIC_WHILE_SET_AT_EXECUTE, )", E_FAIL);
// DT: DescriptorTable( SRV(t2, numDescriptors=6), UAV(u0, numDescriptors=4,
// offset = 17), visibility = SHADER_VISIBILITY_ALL )
TestHLSLRootSignatureCase("DescriptorTable(CBV(b2))", S_OK);
TestHLSLRootSignatureCase("DescriptorTable(CBV(t2))", E_FAIL);
TestHLSLRootSignatureCase("DescriptorTable(CBV(u2))", E_FAIL);
TestHLSLRootSignatureCase("DescriptorTable(CBV(s2))", E_FAIL);
TestHLSLRootSignatureCase("DescriptorTable(SRV(t2))", S_OK);
TestHLSLRootSignatureCase("DescriptorTable(UAV(u2))", S_OK);
TestHLSLRootSignatureCase("DescriptorTable(Sampler(s2))", S_OK);
TestHLSLRootSignatureCase("DescriptorTable(CBV(b2, numDescriptors = 4))",
S_OK);
TestHLSLRootSignatureCase("DescriptorTable(CBV(b2, space=3))", S_OK);
TestHLSLRootSignatureCase("DescriptorTable(CBV(b2, offset=17))", S_OK);
TestHLSLRootSignatureCase("DescriptorTable(CBV(b2, numDescriptors = 4))",
S_OK);
TestHLSLRootSignatureCase(
"DescriptorTable(CBV(b2, numDescriptors = 4, space=3))", S_OK);
TestHLSLRootSignatureCase(
"DescriptorTable(CBV(b2, numDescriptors = 4, offset = 17))", S_OK);
TestHLSLRootSignatureCase(
"DescriptorTable(Sampler(s2, numDescriptors = 4, space=3, offset =17))",
S_OK);
TestHLSLRootSignatureCase(
"DescriptorTable(Sampler(offset =17, numDescriptors = 4, s2, space=3))",
S_OK);
TestHLSLRootSignatureCase("DescriptorTable(Sampler(offset =17, "
"numDescriptors = unbounded, s2, space=3))",
S_OK);
TestHLSLRootSignatureCase("DescriptorTable(Sampler(offset =17, "
"numDescriptors = 4, offset = 1, s2, space=3))",
E_FAIL);
TestHLSLRootSignatureCase("DescriptorTable(Sampler(s1, offset =17, "
"numDescriptors = 4, s2, space=3))",
E_FAIL);
TestHLSLRootSignatureCase(
"DescriptorTable(Sampler(offset =17, numDescriptors = 4, s2, space=3, "
"numDescriptors =1))",
E_FAIL);
TestHLSLRootSignatureCase("DescriptorTable(Sampler(offset =17, "
"numDescriptors = 4, s2, space=3, space=4))",
E_FAIL);
TestHLSLRootSignatureCase("DescriptorTable(CBV(b2), UAV(u3))", S_OK);
TestHLSLRootSignatureCase(
"DescriptorTable(CBV(b2), UAV(u3), visibility = SHADER_VISIBILITY_HULL)",
S_OK);
TestHLSLRootSignatureCase(
"DescriptorTable(CBV(b2), visibility = shader_visibility_hull, UAV(u3))",
S_OK);
TestHLSLRootSignatureCase(
"DescriptorTable(CBV(b2), visibility = SHADER_VISIBILITY_HULL, UAV(u3), "
"visibility = SHADER_VISIBILITY_HULL)",
E_FAIL);
// RS1.1 descriptor range flags.
TestHLSLRootSignature11Case("DescriptorTable(CBV(b2, flags = 0))", S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(SRV(t2, flags = DESCRIPTORS_VOLATILE))", S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(SRV(t2, flags = DESCRIPTORS_VOLATILE | DATA_VOLATILE))",
S_OK);
TestHLSLRootSignature11Case("DescriptorTable(UAV(u2, flags = DATA_VOLATILE))",
S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(UAV(u2, flags = DATA_STATIC_WHILE_SET_AT_EXECUTE))",
S_OK);
TestHLSLRootSignature11Case("DescriptorTable(UAV(u2, flags = DATA_STATIC))",
S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(UAV(u2, flags = DESCRIPTORS_VOLATILE | DATA_VOLATILE))",
S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(UAV(u2, flags = DESCRIPTORS_VOLATILE | "
"DATA_STATIC_WHILE_SET_AT_EXECUTE))",
S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(Sampler(s2, flags = DESCRIPTORS_VOLATILE))", S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(UAV(u2, flags = DESCRIPTORS_VOLATILE | "
"DATA_STATIC_WHILE_SET_AT_EXECUTE, offset =17))",
S_OK);
TestHLSLRootSignature11Case(
"DescriptorTable(UAV(u2, flags = "
"DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS))",
S_OK);
TestHLSLRootSignature10Case("DescriptorTable(CBV(b2, flags = 0))", E_FAIL);
TestHLSLRootSignature10Case(
"DescriptorTable(SRV(t2, flags = DESCRIPTORS_VOLATILE))", E_FAIL);
TestHLSLRootSignature10Case("DescriptorTable(UAV(u2, flags = DATA_VOLATILE))",
E_FAIL);
TestHLSLRootSignature10Case(
"DescriptorTable(UAV(u2, flags = DATA_STATIC_WHILE_SET_AT_EXECUTE))",
E_FAIL);
TestHLSLRootSignature10Case("DescriptorTable(UAV(u2, flags = DATA_STATIC))",
E_FAIL);
TestHLSLRootSignature10Case(
"DescriptorTable(Sampler(s2, flags = DESCRIPTORS_VOLATILE))", E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(Sampler(s2, flags = DATA_VOLATILE))", E_FAIL);
TestHLSLRootSignature11Case("DescriptorTable(Sampler(s2, flags = "
"DESCRIPTORS_VOLATILE | DATA_VOLATILE))",
E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(Sampler(s2, flags = DATA_STATIC_WHILE_SET_AT_EXECUTE))",
E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(Sampler(s2, flags = DATA_STATIC))", E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(UAV(u2, flags = DESCRIPTORS_VOLATILE | DATA_VOLATILE | "
"DATA_STATIC_WHILE_SET_AT_EXECUTE))",
E_FAIL);
TestHLSLRootSignature11Case("DescriptorTable(CBV(b2, flags = DATA_VOLATILE | "
"DATA_STATIC_WHILE_SET_AT_EXECUTE))",
E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(CBV(b2, flags = DATA_VOLATILE | DATA_STATIC))", E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(CBV(b2, flags = DATA_STATIC_WHILE_SET_AT_EXECUTE | "
"DATA_STATIC))",
E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(CBV(b2, flags = DESCRIPTORS_VOLATILE | DATA_STATIC))",
E_FAIL);
TestHLSLRootSignature11Case(
"DescriptorTable(UAV(u2, flags = DESCRIPTORS_VOLATILE | "
"DATA_STATIC_WHILE_SET_AT_EXECUTE, ))",
E_FAIL);
// StaticSampler( s0,
// [ Filter = FILTER_ANISOTROPIC,
// AddressU = TEXTURE_ADDRESS_WRAP,
// AddressV = TEXTURE_ADDRESS_WRAP,
// AddressW = TEXTURE_ADDRESS_WRAP,
// MaxAnisotropy = 16,
// ComparisonFunc = COMPARISON_LESS_EQUAL,
// BorderColor = STATIC_BORDER_COLOR_OPAQUE_WHITE,
// space = 0,
// visibility = SHADER_VISIBILITY_ALL ] )
// SReg
TestHLSLRootSignatureCase("StaticSampler(s2)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(t2)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(b2)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(u2)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s0, s2)", E_FAIL);
// Filter
TestHLSLRootSignatureCase(
"StaticSampler(filter = FILTER_MIN_MAG_MIP_POINT, s2)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MIN_MAG_POINT_MIP_LINEAR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MIN_POINT_MAG_MIP_LINEAR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MIN_LINEAR_MAG_MIP_POINT)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MIN_MAG_LINEAR_MIP_POINT)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MIN_MAG_MIP_LINEAR)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, filter = FILTER_ANISOTROPIC)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_COMPARISON_MIN_MAG_MIP_POINT)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, filter = "
"FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = "
"FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_COMPARISON_MIN_MAG_MIP_LINEAR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_COMPARISON_ANISOTROPIC)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MINIMUM_MIN_MAG_MIP_POINT)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, filter = "
"FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, filter = "
"FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MINIMUM_MIN_MAG_MIP_LINEAR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MINIMUM_ANISOTROPIC)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MAXIMUM_MIN_MAG_MIP_POINT)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, filter = "
"FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, filter = "
"FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, filter = FILTER_MAXIMUM_ANISOTROPIC)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(filter = FILTER_MAXIMUM_ANISOTROPIC, s2, filter = "
"FILTER_MAXIMUM_ANISOTROPIC)",
E_FAIL);
// AddressU
TestHLSLRootSignatureCase(
"StaticSampler(addressU = TEXTURE_ADDRESS_WRAP, s2)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressU = TEXTURE_ADDRESS_MIRROR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressU = TEXTURE_ADDRESS_CLAMP)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressU = TEXTURE_ADDRESS_BORDER)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressU = TEXTURE_ADDRESS_MIRROR_ONCE)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(addressU = TEXTURE_ADDRESS_MIRROR, "
"s2, addressU = TEXTURE_ADDRESS_BORDER)",
E_FAIL);
// AddressV
TestHLSLRootSignatureCase(
"StaticSampler(addressV = TEXTURE_ADDRESS_WRAP, s2)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressV = TEXTURE_ADDRESS_MIRROR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressV = TEXTURE_ADDRESS_CLAMP)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressV = TEXTURE_ADDRESS_BORDER)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressV = TEXTURE_ADDRESS_MIRROR_ONCE)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(addressV = TEXTURE_ADDRESS_MIRROR, "
"s2, addressV = TEXTURE_ADDRESS_BORDER)",
E_FAIL);
// AddressW
TestHLSLRootSignatureCase(
"StaticSampler(addressW = TEXTURE_ADDRESS_WRAP, s2)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressW = TEXTURE_ADDRESS_MIRROR)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressW = TEXTURE_ADDRESS_CLAMP)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressW = TEXTURE_ADDRESS_BORDER)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, addressW = TEXTURE_ADDRESS_MIRROR_ONCE)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(addressW = TEXTURE_ADDRESS_MIRROR, "
"s2, addressW = TEXTURE_ADDRESS_BORDER)",
E_FAIL);
// Mixed address
TestHLSLRootSignatureCase(
"StaticSampler(addressW = TEXTURE_ADDRESS_MIRROR, s2, addressU = "
"TEXTURE_ADDRESS_CLAMP, addressV = TEXTURE_ADDRESS_MIRROR_ONCE)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(addressW = TEXTURE_ADDRESS_MIRROR, s2, addressU = "
"TEXTURE_ADDRESS_CLAMP, addressU = TEXTURE_ADDRESS_CLAMP, addressV = "
"TEXTURE_ADDRESS_MIRROR_ONCE)",
E_FAIL);
// MipLODBias
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=0)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-0)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=+0)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=0.)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=0.f)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=0.0)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=0.0f)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=0.1)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=+0.1)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-0.1)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=.1)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=2)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-2)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=2.3)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=+2.3)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-2.3)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=2.3f)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=sdfgsdf)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=--2)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-+2)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=.)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-.)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=+.)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=.e2)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=.1e)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=.1e.4)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=2e100)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-2e100)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=2e100000)", E_FAIL);
TestHLSLRootSignatureCase("StaticSampler(s2, mipLODBias=-2e100000)", E_FAIL);
// MaxAnisotropy
TestHLSLRootSignatureCase("StaticSampler(s2, maxAnisotropy=2)", S_OK);
// Comparison function
TestHLSLRootSignatureCase(
"StaticSampler(ComparisonFunc = COMPARISON_NEVER, s2)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, ComparisonFunc = COMPARISON_LESS)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, ComparisonFunc = COMPARISON_EQUAL)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, ComparisonFunc = COMPARISON_LESS_EQUAL)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, ComparisonFunc = COMPARISON_GREATER)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, ComparisonFunc = COMPARISON_NOT_EQUAL)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, ComparisonFunc = COMPARISON_GREATER_EQUAL)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, ComparisonFunc = COMPARISON_ALWAYS)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(ComparisonFunc = COMPARISON_NOT_EQUAL, s2, ComparisonFunc "
"= COMPARISON_ALWAYS)",
E_FAIL);
// Border color
TestHLSLRootSignatureCase(
"StaticSampler(BorderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK, s2)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, BorderColor = STATIC_BORDER_COLOR_OPAQUE_BLACK)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, BorderColor = STATIC_BORDER_COLOR_OPAQUE_WHITE)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, BorderColor = STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, BorderColor = STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT)",
S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(BorderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK, s2, "
"BorderColor = STATIC_BORDER_COLOR_OPAQUE_WHITE)",
E_FAIL);
// MinLOD
TestHLSLRootSignatureCase("StaticSampler(s2, minLOD=-4.5)", S_OK);
// MinLOD
TestHLSLRootSignatureCase("StaticSampler(s2, maxLOD=5.77)", S_OK);
// Space
TestHLSLRootSignatureCase("StaticSampler(s2, space=7)", S_OK);
TestHLSLRootSignatureCase("StaticSampler(s2, space=7, space=9)", E_FAIL);
// Visibility
TestHLSLRootSignatureCase(
"StaticSampler(s2, visibility=SHADER_visibility_ALL)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(visibility=SHADER_VISIBILITY_VERTEX, s2)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, visibility=SHADER_VISIBILITY_HULL)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, visibility=SHADER_VISIBILITY_DOMAIN)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, visibility=SHADER_VISIBILITY_GEOMETRY)", S_OK);
TestHLSLRootSignatureCase(
"StaticSampler(s2, visibility=SHADER_VISIBILITY_PIXEL)", S_OK);
// StaticSampler complex
TestHLSLRootSignatureCase(
"StaticSampler(s2, "
" Filter = FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR, "
" AddressU = TEXTURE_ADDRESS_WRAP, "
" AddressV = TEXTURE_ADDRESS_CLAMP, "
" AddressW = TEXTURE_ADDRESS_MIRROR_ONCE, "
" MaxAnisotropy = 8, "
" ComparisonFunc = COMPARISON_NOT_EQUAL, "
" BorderColor = STATIC_BORDER_COLOR_OPAQUE_BLACK, "
" space = 3, "
" visibility = SHADER_VISIBILITY_PIXEL), "
"StaticSampler(s7, "
" Filter = FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR, "
" AddressU = TEXTURE_ADDRESS_MIRROR_ONCE, "
" AddressV = TEXTURE_ADDRESS_WRAP, "
" AddressW = TEXTURE_ADDRESS_CLAMP, "
" MaxAnisotropy = 1, "
" ComparisonFunc = COMPARISON_ALWAYS, "
" BorderColor = STATIC_BORDER_COLOR_OPAQUE_BLACK, "
" space = 3, "
" visibility = SHADER_VISIBILITY_HULL), ",
S_OK);
// Mixed
TestHLSLRootSignatureCase("RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), "
"DescriptorTable(CBV(b2), "
"CBV(b3, numDescriptors = 4, space=3), "
"SRV(t4, numDescriptors=3), "
"visibility = SHADER_VISIBILITY_HULL), "
"UAV(u1, visibility = SHADER_VISIBILITY_PIXEL), "
"RootConstants( num32BitConstants=3, b2, space = "
"5, visibility = SHADER_VISIBILITY_PIXEL), "
"DescriptorTable(CBV(b20, space=4)), "
"DescriptorTable(CBV(b20, space=9)), "
"RootConstants( num32BitConstants=8, b2, "
"visibility = SHADER_VISIBILITY_PIXEL), "
"SRV(t9, space = 0)",
S_OK);
TestHLSLRootSignatureCase(
"RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), "
"DescriptorTable(CBV(b2), "
"CBV(b3, numDescriptors = 4, space=3), "
"SRV(t4, numDescriptors=3), "
"visibility = SHADER_VISIBILITY_HULL), "
"UAV(u1, visibility = SHADER_VISIBILITY_PIXEL), "
"RootConstants( num32BitConstants=3, b2, space = 5, visibility = "
"SHADER_VISIBILITY_PIXEL), "
"DescriptorTable(CBV(b20, space=4, numDescriptors = unbounded)), "
"DescriptorTable(CBV(b20, space=9)), "
"RootConstants( num32BitConstants=8, b2, visibility = "
"SHADER_VISIBILITY_PIXEL), "
"SRV(t9, space = 0), "
"StaticSampler(s7, "
" Filter = FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR, "
" AddressU = TEXTURE_ADDRESS_MIRROR_ONCE, "
" AddressV = TEXTURE_ADDRESS_WRAP, "
" AddressW = TEXTURE_ADDRESS_CLAMP, "
" MaxAnisotropy = 12, "
" ComparisonFunc = COMPARISON_ALWAYS, "
" BorderColor = STATIC_BORDER_COLOR_OPAQUE_BLACK, "
" space = 3, "
" visibility = SHADER_VISIBILITY_HULL), ",
S_OK);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/PixTestUtils.h
|
///////////////////////////////////////////////////////////////////////////////
// //
// PixTestUtils.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides utility functions for PIX tests. //
// //
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcpix.h"
#include <memory>
#include <string>
#include <vector>
namespace dxc {
class DxcDllSupport;
}
namespace pix_test {
std::vector<std::string> SplitAndPreserveEmptyLines(std::string const &str,
char delimeter);
CComPtr<IDxcBlob> GetDebugPart(dxc::DxcDllSupport &dllSupport,
IDxcBlob *container);
void CreateBlobFromText(dxc::DxcDllSupport &dllSupport, const char *pText,
IDxcBlobEncoding **ppBlob);
HRESULT CreateCompiler(dxc::DxcDllSupport &dllSupport, IDxcCompiler **ppResult);
CComPtr<IDxcBlob> Compile(dxc::DxcDllSupport &dllSupport, const char *hlsl,
const wchar_t *target,
std::vector<const wchar_t *> extraArgs = {},
const wchar_t *entry = L"main");
void CompileAndLogErrors(dxc::DxcDllSupport &dllSupport, LPCSTR pText,
LPCWSTR pTargetProfile, std::vector<LPCWSTR> &args,
IDxcIncludeHandler *includer,
_Outptr_ IDxcBlob **ppResult);
CComPtr<IDxcBlob> WrapInNewContainer(dxc::DxcDllSupport &dllSupport,
IDxcBlob *part);
struct ValueLocation {
int base;
int count;
};
struct PassOutput {
CComPtr<IDxcBlob> blob;
std::vector<ValueLocation> valueLocations;
std::vector<std::string> lines;
};
PassOutput RunAnnotationPasses(dxc::DxcDllSupport &dllSupport, IDxcBlob *dxil,
int startingLineNumber = 0);
struct DebuggerInterfaces {
CComPtr<IDxcPixDxilDebugInfo> debugInfo;
CComPtr<IDxcPixCompilationInfo> compilationInfo;
};
class InstructionOffsetSeeker {
public:
virtual ~InstructionOffsetSeeker() {}
virtual DWORD FindInstructionOffsetForLabel(const wchar_t *label) = 0;
};
std::unique_ptr<pix_test::InstructionOffsetSeeker>
GatherDebugLocLabelsFromDxcUtils(DebuggerInterfaces &debuggerInterfaces);
} // namespace pix_test
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/DxilResourceTests.cpp
|
//===- unittests/DXIL/DxilResourceTests.cpp ----- Tests for DXIL Resource -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilResource.h"
#include "dxc/Support/WinIncludes.h"
#include "dxc/Test/HlslTestUtils.h"
using namespace hlsl;
using namespace hlsl::DXIL;
#ifdef _WIN32
class DxilResourceTest {
#else
class DxilResourceTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(DxilResourceTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_METHOD(KindChecks)
};
struct KindTestCase {
ResourceKind Kind;
bool IsTexture;
bool IsTextureArray;
bool IsTextureCube;
bool IsFeedbackTexture;
bool IsArray;
};
KindTestCase Kinds[] = {
{ResourceKind::Invalid, false, false, false, false, false},
{ResourceKind::Texture1D, true, false, false, false, false},
{ResourceKind::Texture2D, true, false, false, false, false},
{ResourceKind::Texture2DMS, true, false, false, false, false},
{ResourceKind::Texture3D, true, false, false, false, false},
{ResourceKind::TextureCube, true, false, true, false, false},
{ResourceKind::Texture1DArray, true, true, false, false, true},
{ResourceKind::Texture2DArray, true, true, false, false, true},
{ResourceKind::Texture2DMSArray, true, true, false, false, true},
{ResourceKind::TextureCubeArray, true, true, true, false, true},
{ResourceKind::TypedBuffer, false, false, false, false, false},
{ResourceKind::RawBuffer, false, false, false, false, false},
{ResourceKind::StructuredBuffer, false, false, false, false, false},
{ResourceKind::CBuffer, false, false, false, false, false},
{ResourceKind::Sampler, false, false, false, false, false},
{ResourceKind::TBuffer, false, false, false, false, false},
{ResourceKind::RTAccelerationStructure, false, false, false, false, false},
{ResourceKind::FeedbackTexture2D, false, false, false, true, false},
{ResourceKind::FeedbackTexture2DArray, false, false, false, true, true}};
static_assert(sizeof(Kinds) / sizeof(KindTestCase) ==
(int)ResourceKind::NumEntries,
"There is a missing resoure type in the test cases!");
TEST_F(DxilResourceTest, KindChecks) {
for (int Idx = 0; Idx < (int)ResourceKind::NumEntries; ++Idx) {
EXPECT_EQ(IsAnyTexture(Kinds[Idx].Kind), Kinds[Idx].IsTexture);
EXPECT_EQ(IsAnyArrayTexture(Kinds[Idx].Kind), Kinds[Idx].IsTextureArray);
EXPECT_EQ(IsAnyTextureCube(Kinds[Idx].Kind), Kinds[Idx].IsTextureCube);
EXPECT_EQ(IsFeedbackTexture(Kinds[Idx].Kind), Kinds[Idx].IsFeedbackTexture);
EXPECT_EQ(IsArrayKind(Kinds[Idx].Kind), Kinds[Idx].IsArray);
// Also test the entries through the DxilResource class, these tests should
// be redundant, but historically DxilResource had its own implementations.
EXPECT_EQ(DxilResource::IsAnyTexture(Kinds[Idx].Kind),
Kinds[Idx].IsTexture);
EXPECT_EQ(DxilResource::IsAnyArrayTexture(Kinds[Idx].Kind),
Kinds[Idx].IsTextureArray);
EXPECT_EQ(DxilResource::IsAnyTextureCube(Kinds[Idx].Kind),
Kinds[Idx].IsTextureCube);
EXPECT_EQ(DxilResource::IsFeedbackTexture(Kinds[Idx].Kind),
Kinds[Idx].IsFeedbackTexture);
EXPECT_EQ(DxilResource::IsArrayKind(Kinds[Idx].Kind), Kinds[Idx].IsArray);
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/DxilModuleTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// DxilModuleTest.cpp //
// //
// Provides unit tests for DxilModule. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DxilContainer/DxilContainer.h"
#include "dxc/HLSL/HLOperationLowerExtension.h"
#include "dxc/HlslIntrinsicOp.h"
#include "dxc/Support/microcom.h"
#include "dxc/Test/CompilationResult.h"
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/dxcapi.internal.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Regex.h"
using namespace hlsl;
using namespace llvm;
///////////////////////////////////////////////////////////////////////////////
// DxilModule unit tests.
#ifdef _WIN32
class DxilModuleTest {
#else
class DxilModuleTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(DxilModuleTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
// Basic loading tests.
TEST_METHOD(LoadDxilModule_1_0)
TEST_METHOD(LoadDxilModule_1_1)
TEST_METHOD(LoadDxilModule_1_2)
// Precise query tests.
TEST_METHOD(Precise1)
TEST_METHOD(Precise2)
TEST_METHOD(Precise3)
TEST_METHOD(Precise4)
TEST_METHOD(Precise5)
TEST_METHOD(Precise6)
TEST_METHOD(Precise7)
TEST_METHOD(CSGetNumThreads)
TEST_METHOD(MSGetNumThreads)
TEST_METHOD(ASGetNumThreads)
TEST_METHOD(SetValidatorVersion)
TEST_METHOD(PayloadQualifier)
TEST_METHOD(CanonicalSystemValueSemantic)
void VerifyValidatorVersionFails(LPCWSTR shaderModel,
const std::vector<LPCWSTR> &arguments,
const std::vector<LPCSTR> &expectedErrors);
void VerifyValidatorVersionMatches(LPCWSTR shaderModel,
const std::vector<LPCWSTR> &arguments,
unsigned expectedMajor = UINT_MAX,
unsigned expectedMinor = UINT_MAX);
};
bool DxilModuleTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Compilation and dxil module loading support.
namespace {
class Compiler {
public:
Compiler(dxc::DxcDllSupport &dll)
: m_dllSupport(dll), m_msf(CreateMSFileSystem()), m_pts(m_msf.get()) {
m_ver.Initialize(m_dllSupport);
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
}
bool SkipDxil_Test(unsigned major, unsigned minor) {
return m_ver.SkipDxilVersion(major, minor);
}
IDxcOperationResult *Compile(const char *program,
LPCWSTR shaderModel = L"ps_6_0") {
return Compile(program, shaderModel, {}, {});
}
IDxcOperationResult *Compile(const char *program, LPCWSTR shaderModel,
const std::vector<LPCWSTR> &arguments,
const std::vector<DxcDefine> defs) {
Utf8ToBlob(m_dllSupport, program, &pCodeBlob);
VERIFY_SUCCEEDED(pCompiler->Compile(
pCodeBlob, L"hlsl.hlsl", L"main", shaderModel,
const_cast<LPCWSTR *>(arguments.data()), arguments.size(), defs.data(),
defs.size(), nullptr, &pCompileResult));
return pCompileResult;
}
std::string Disassemble() {
CComPtr<IDxcBlob> pBlob;
CheckOperationSucceeded(pCompileResult, &pBlob);
return DisassembleProgram(m_dllSupport, pBlob);
}
DxilModule &GetDxilModule() {
// Make sure we compiled successfully.
CComPtr<IDxcBlob> pBlob;
CheckOperationSucceeded(pCompileResult, &pBlob);
// Verify we have a valid dxil container.
const DxilContainerHeader *pContainer =
IsDxilContainerLike(pBlob->GetBufferPointer(), pBlob->GetBufferSize());
VERIFY_IS_NOT_NULL(pContainer);
VERIFY_IS_TRUE(IsValidDxilContainer(pContainer, pBlob->GetBufferSize()));
// Get Dxil part from container.
DxilPartIterator it = std::find_if(begin(pContainer), end(pContainer),
DxilPartIsType(DFCC_DXIL));
VERIFY_IS_FALSE(it == end(pContainer));
const DxilProgramHeader *pProgramHeader =
reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(*it));
VERIFY_IS_TRUE(IsValidDxilProgramHeader(pProgramHeader, (*it)->PartSize));
// Get a pointer to the llvm bitcode.
const char *pIL;
uint32_t pILLength;
GetDxilProgramBitcode(pProgramHeader, &pIL, &pILLength);
// Parse llvm bitcode into a module.
std::unique_ptr<llvm::MemoryBuffer> pBitcodeBuf(
llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(pIL, pILLength), "",
false));
llvm::ErrorOr<std::unique_ptr<llvm::Module>> pModule(
llvm::parseBitcodeFile(pBitcodeBuf->getMemBufferRef(), m_llvmContext));
if (std::error_code ec = pModule.getError()) {
VERIFY_FAIL();
}
m_module = std::move(pModule.get());
// Grab the dxil module;
DxilModule *DM = DxilModule::TryGetDxilModule(m_module.get());
VERIFY_IS_NOT_NULL(DM);
return *DM;
}
public:
static ::llvm::sys::fs::MSFileSystem *CreateMSFileSystem() {
::llvm::sys::fs::MSFileSystem *msfPtr;
VERIFY_SUCCEEDED(CreateMSFileSystemForDisk(&msfPtr));
return msfPtr;
}
dxc::DxcDllSupport &m_dllSupport;
VersionSupportInfo m_ver;
CComPtr<IDxcCompiler> pCompiler;
CComPtr<IDxcBlobEncoding> pCodeBlob;
CComPtr<IDxcOperationResult> pCompileResult;
llvm::LLVMContext m_llvmContext;
std::unique_ptr<llvm::Module> m_module;
std::unique_ptr<::llvm::sys::fs::MSFileSystem> m_msf;
::llvm::sys::fs::AutoPerThreadSystem m_pts;
};
} // namespace
///////////////////////////////////////////////////////////////////////////////
// Unit Test Implementation
TEST_F(DxilModuleTest, LoadDxilModule_1_0) {
Compiler c(m_dllSupport);
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
L"ps_6_0");
// Basic sanity check on dxil version in dxil module.
DxilModule &DM = c.GetDxilModule();
unsigned vMajor, vMinor;
DM.GetDxilVersion(vMajor, vMinor);
VERIFY_IS_TRUE(vMajor == 1);
VERIFY_IS_TRUE(vMinor == 0);
}
TEST_F(DxilModuleTest, LoadDxilModule_1_1) {
Compiler c(m_dllSupport);
if (c.SkipDxil_Test(1, 1))
return;
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
L"ps_6_1");
// Basic sanity check on dxil version in dxil module.
DxilModule &DM = c.GetDxilModule();
unsigned vMajor, vMinor;
DM.GetDxilVersion(vMajor, vMinor);
VERIFY_IS_TRUE(vMajor == 1);
VERIFY_IS_TRUE(vMinor == 1);
}
TEST_F(DxilModuleTest, LoadDxilModule_1_2) {
Compiler c(m_dllSupport);
if (c.SkipDxil_Test(1, 2))
return;
c.Compile("float4 main() : SV_Target {\n"
" return 0;\n"
"}\n",
L"ps_6_2");
// Basic sanity check on dxil version in dxil module.
DxilModule &DM = c.GetDxilModule();
unsigned vMajor, vMinor;
DM.GetDxilVersion(vMajor, vMinor);
VERIFY_IS_TRUE(vMajor == 1);
VERIFY_IS_TRUE(vMinor == 2);
}
TEST_F(DxilModuleTest, Precise1) {
Compiler c(m_dllSupport);
c.Compile("precise float main(float x : X, float y : Y) : SV_Target {\n"
" return sqrt(x) + y;\n"
"}\n");
// Make sure sqrt and add are marked precise.
DxilModule &DM = c.GetDxilModule();
Function *F = DM.GetEntryFunction();
int numChecks = 0;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *Inst = &*I;
if (DxilInst_Sqrt(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
} else if (LlvmInst_FAdd(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
}
}
VERIFY_ARE_EQUAL(numChecks, 2);
}
TEST_F(DxilModuleTest, Precise2) {
Compiler c(m_dllSupport);
c.Compile("float main(float x : X, float y : Y) : SV_Target {\n"
" return sqrt(x) + y;\n"
"}\n");
// Make sure sqrt and add are not marked precise.
DxilModule &DM = c.GetDxilModule();
Function *F = DM.GetEntryFunction();
int numChecks = 0;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *Inst = &*I;
if (DxilInst_Sqrt(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
} else if (LlvmInst_FAdd(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
}
}
VERIFY_ARE_EQUAL(numChecks, 2);
}
TEST_F(DxilModuleTest, Precise3) {
// TODO: Enable this test when precise metadata is inserted for Gis.
if (const bool GisIsBroken = true)
return;
Compiler c(m_dllSupport);
c.Compile("float main(float x : X, float y : Y) : SV_Target {\n"
" return sqrt(x) + y;\n"
"}\n",
L"ps_6_0", {L"/Gis"}, {});
// Make sure sqrt and add are marked precise.
DxilModule &DM = c.GetDxilModule();
Function *F = DM.GetEntryFunction();
int numChecks = 0;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *Inst = &*I;
if (DxilInst_Sqrt(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
} else if (LlvmInst_FAdd(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
}
}
VERIFY_ARE_EQUAL(numChecks, 2);
}
TEST_F(DxilModuleTest, Precise4) {
Compiler c(m_dllSupport);
c.Compile("float main(float x : X, float y : Y) : SV_Target {\n"
" precise float sx = 1 / sqrt(x);\n"
" return sx + y;\n"
"}\n");
// Make sure sqrt and div are marked precise, and add is not.
DxilModule &DM = c.GetDxilModule();
Function *F = DM.GetEntryFunction();
int numChecks = 0;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *Inst = &*I;
if (DxilInst_Sqrt(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
} else if (LlvmInst_FDiv(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
} else if (LlvmInst_FAdd(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
}
}
VERIFY_ARE_EQUAL(numChecks, 3);
}
TEST_F(DxilModuleTest, Precise5) {
Compiler c(m_dllSupport);
c.Compile("float C[10];\n"
"float main(float x : X, float y : Y, int i : I) : SV_Target {\n"
" float A[2];\n"
" A[0] = x;\n"
" A[1] = y;\n"
" return A[i] + C[i];\n"
"}\n");
// Make sure load and extract value are not reported as precise.
DxilModule &DM = c.GetDxilModule();
Function *F = DM.GetEntryFunction();
int numChecks = 0;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *Inst = &*I;
if (LlvmInst_ExtractValue(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
} else if (LlvmInst_Load(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
} else if (LlvmInst_FAdd(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
}
}
VERIFY_ARE_EQUAL(numChecks, 3);
}
TEST_F(DxilModuleTest, Precise6) {
Compiler c(m_dllSupport);
c.Compile("precise float2 main(float2 x : A, float2 y : B) : SV_Target {\n"
" return sqrt(x * y);\n"
"}\n");
// Make sure sqrt and mul are marked precise.
DxilModule &DM = c.GetDxilModule();
Function *F = DM.GetEntryFunction();
int numChecks = 0;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *Inst = &*I;
if (DxilInst_Sqrt(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
} else if (LlvmInst_FMul(Inst)) {
numChecks++;
VERIFY_IS_TRUE(DM.IsPrecise(Inst));
}
}
VERIFY_ARE_EQUAL(numChecks, 4);
}
TEST_F(DxilModuleTest, Precise7) {
Compiler c(m_dllSupport);
c.Compile("float2 main(float2 x : A, float2 y : B) : SV_Target {\n"
" return sqrt(x * y);\n"
"}\n");
// Make sure sqrt and mul are not marked precise.
DxilModule &DM = c.GetDxilModule();
Function *F = DM.GetEntryFunction();
int numChecks = 0;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *Inst = &*I;
if (DxilInst_Sqrt(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
} else if (LlvmInst_FMul(Inst)) {
numChecks++;
VERIFY_IS_FALSE(DM.IsPrecise(Inst));
}
}
VERIFY_ARE_EQUAL(numChecks, 4);
}
TEST_F(DxilModuleTest, CSGetNumThreads) {
Compiler c(m_dllSupport);
c.Compile("[numthreads(8, 4, 2)]\n"
"void main() {\n"
"}\n",
L"cs_6_0");
DxilModule &DM = c.GetDxilModule();
VERIFY_ARE_EQUAL(8u, DM.GetNumThreads(0));
VERIFY_ARE_EQUAL(4u, DM.GetNumThreads(1));
VERIFY_ARE_EQUAL(2u, DM.GetNumThreads(2));
}
TEST_F(DxilModuleTest, MSGetNumThreads) {
Compiler c(m_dllSupport);
if (c.SkipDxil_Test(1, 5))
return;
c.Compile("struct MeshPerVertex { float4 pos : SV_Position; };\n"
"[numthreads(8, 4, 2)]\n"
"[outputtopology(\"triangle\")]\n"
"void main(\n"
" out indices uint3 primIndices[1]\n"
") {\n"
" SetMeshOutputCounts(0, 0);\n"
"}\n",
L"ms_6_5");
DxilModule &DM = c.GetDxilModule();
VERIFY_ARE_EQUAL(8u, DM.GetNumThreads(0));
VERIFY_ARE_EQUAL(4u, DM.GetNumThreads(1));
VERIFY_ARE_EQUAL(2u, DM.GetNumThreads(2));
}
TEST_F(DxilModuleTest, ASGetNumThreads) {
Compiler c(m_dllSupport);
if (c.SkipDxil_Test(1, 5))
return;
c.Compile("struct Payload { uint i; };\n"
"[numthreads(8, 4, 2)]\n"
"void main() {\n"
" Payload pld = {0};\n"
" DispatchMesh(1, 1, 1, pld);\n"
"}\n",
L"as_6_5");
DxilModule &DM = c.GetDxilModule();
VERIFY_ARE_EQUAL(8u, DM.GetNumThreads(0));
VERIFY_ARE_EQUAL(4u, DM.GetNumThreads(1));
VERIFY_ARE_EQUAL(2u, DM.GetNumThreads(2));
}
void DxilModuleTest::VerifyValidatorVersionFails(
LPCWSTR shaderModel, const std::vector<LPCWSTR> &arguments,
const std::vector<LPCSTR> &expectedErrors) {
LPCSTR shader = "[shader(\"pixel\")]"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n";
Compiler c(m_dllSupport);
c.Compile(shader, shaderModel, arguments, {});
CheckOperationResultMsgs(c.pCompileResult, expectedErrors, false, false);
}
void DxilModuleTest::VerifyValidatorVersionMatches(
LPCWSTR shaderModel, const std::vector<LPCWSTR> &arguments,
unsigned expectedMajor, unsigned expectedMinor) {
LPCSTR shader = "[shader(\"pixel\")]"
"float4 main() : SV_Target {\n"
" return 0;\n"
"}\n";
Compiler c(m_dllSupport);
c.Compile(shader, shaderModel, arguments, {});
DxilModule &DM = c.GetDxilModule();
unsigned vMajor, vMinor;
DM.GetValidatorVersion(vMajor, vMinor);
if (expectedMajor == UINT_MAX) {
// Expect current version
VERIFY_ARE_EQUAL(vMajor, c.m_ver.m_ValMajor);
VERIFY_ARE_EQUAL(vMinor, c.m_ver.m_ValMinor);
} else {
VERIFY_ARE_EQUAL(vMajor, expectedMajor);
VERIFY_ARE_EQUAL(vMinor, expectedMinor);
}
}
TEST_F(DxilModuleTest, SetValidatorVersion) {
Compiler c(m_dllSupport);
if (c.SkipDxil_Test(1, 4))
return;
// Current version
VerifyValidatorVersionMatches(L"ps_6_2", {});
VerifyValidatorVersionMatches(L"lib_6_3", {});
// Current version, with validation disabled
VerifyValidatorVersionMatches(L"ps_6_2", {L"-Vd"});
VerifyValidatorVersionMatches(L"lib_6_3", {L"-Vd"});
// Override validator version
VerifyValidatorVersionMatches(L"ps_6_2", {L"-validator-version", L"1.2"}, 1,
2);
VerifyValidatorVersionMatches(L"lib_6_3", {L"-validator-version", L"1.3"}, 1,
3);
// Override validator version, with validation disabled
VerifyValidatorVersionMatches(L"ps_6_2",
{L"-Vd", L"-validator-version", L"1.2"}, 1, 2);
VerifyValidatorVersionMatches(L"lib_6_3",
{L"-Vd", L"-validator-version", L"1.3"}, 1, 3);
// Never can validate (version 0,0):
VerifyValidatorVersionMatches(L"lib_6_1", {L"-Vd"}, 0, 0);
VerifyValidatorVersionMatches(L"lib_6_2", {L"-Vd"}, 0, 0);
VerifyValidatorVersionMatches(L"lib_6_2",
{L"-Vd", L"-validator-version", L"0.0"}, 0, 0);
VerifyValidatorVersionMatches(L"lib_6_x", {}, 0, 0);
VerifyValidatorVersionMatches(L"lib_6_x", {L"-validator-version", L"0.0"}, 0,
0);
// Failure cases:
VerifyValidatorVersionFails(
L"ps_6_2", {L"-validator-version", L"1.1"},
{"validator version 1,1 does not support target profile."});
VerifyValidatorVersionFails(
L"lib_6_2", {L"-Tlib_6_2"},
{"Must disable validation for unsupported lib_6_1 or lib_6_2 targets"});
VerifyValidatorVersionFails(L"lib_6_2",
{L"-Vd", L"-validator-version", L"1.2"},
{"-validator-version cannot be used with library "
"profiles lib_6_1 or lib_6_2."});
VerifyValidatorVersionFails(L"lib_6_x", {L"-validator-version", L"1.3"},
{"Offline library profile cannot be used with "
"non-zero -validator-version."});
}
TEST_F(DxilModuleTest, PayloadQualifier) {
if (m_ver.SkipDxilVersion(1, 6))
return;
std::vector<LPCWSTR> arguments = {L"-enable-payload-qualifiers"};
Compiler c(m_dllSupport);
LPCSTR shader = "struct [raypayload] Payload\n"
"{\n"
" double a : read(caller, closesthit, anyhit) : "
"write(caller, miss, closesthit);\n"
"};\n\n"
"[shader(\"miss\")]\n"
"void Miss( inout Payload payload ) { payload.a = 4.2; }\n";
c.Compile(shader, L"lib_6_6", arguments, {});
DxilModule &DM = c.GetDxilModule();
const DxilTypeSystem &DTS = DM.GetTypeSystem();
for (auto &p : DTS.GetPayloadAnnotationMap()) {
const DxilPayloadAnnotation &plAnnotation = *p.second;
for (unsigned i = 0; i < plAnnotation.GetNumFields(); ++i) {
const DxilPayloadFieldAnnotation &fieldAnnotation =
plAnnotation.GetFieldAnnotation(i);
VERIFY_IS_TRUE(fieldAnnotation.HasAnnotations());
VERIFY_ARE_EQUAL(DXIL::PayloadAccessQualifier::ReadWrite,
fieldAnnotation.GetPayloadFieldQualifier(
DXIL::PayloadAccessShaderStage::Caller));
VERIFY_ARE_EQUAL(DXIL::PayloadAccessQualifier::ReadWrite,
fieldAnnotation.GetPayloadFieldQualifier(
DXIL::PayloadAccessShaderStage::Closesthit));
VERIFY_ARE_EQUAL(DXIL::PayloadAccessQualifier::Write,
fieldAnnotation.GetPayloadFieldQualifier(
DXIL::PayloadAccessShaderStage::Miss));
VERIFY_ARE_EQUAL(DXIL::PayloadAccessQualifier::Read,
fieldAnnotation.GetPayloadFieldQualifier(
DXIL::PayloadAccessShaderStage::Anyhit));
}
}
}
TEST_F(DxilModuleTest, CanonicalSystemValueSemantic) {
// Verify that the semantic name is canonicalized.
// This is difficult to do from a FileCheck test because system value
// semantics get canonicallized during the metadata emit. However, having a
// non-canonical semantic name at earlier stages can lead to inconsistency
// between the strings used earlier and the final canonicalized version. This
// makes sure the string gets canonicalized when the signature elsement is
// created.
std::unique_ptr<hlsl::DxilSignatureElement> newElt =
std::make_unique<hlsl::DxilSignatureElement>(
hlsl::DXIL::SigPointKind::VSOut);
newElt->Initialize("sV_pOsItIoN", hlsl::CompType::getF32(),
hlsl::InterpolationMode(
hlsl::DXIL::InterpolationMode::LinearNoperspective),
1, 4, 0, 0, 0, {0});
VERIFY_ARE_EQUAL_STR("SV_Position", newElt->GetSemanticName().data());
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/MSFileSysTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// MSFileSysTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Provides tests for the file system abstraction API. //
// //
///////////////////////////////////////////////////////////////////////////////
// clang-format off
// Includes on Windows are highly order dependent.
#include <stdint.h>
#include "dxc/Support/WinIncludes.h"
#include "dxc/Test/HlslTestUtils.h"
#include "llvm/Support/MSFileSystem.h"
#include "llvm/Support/Atomic.h"
#include <d3dcommon.h>
#include "dxc/dxcapi.internal.h"
#include <algorithm>
#include <vector>
#include <memory>
// clang-format on
using namespace llvm;
using namespace llvm::sys;
using namespace llvm::sys::fs;
const GUID DECLSPEC_SELECTANY GUID_NULL = {0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}};
#define SIMPLE_IUNKNOWN_IMPL1(_IFACE_) \
private: \
volatile std::atomic<llvm::sys::cas_flag> m_dwRef; \
\
public: \
ULONG STDMETHODCALLTYPE AddRef() override { return (ULONG)++m_dwRef; } \
ULONG STDMETHODCALLTYPE Release() override { \
ULONG result = (ULONG)--m_dwRef; \
if (result == 0) \
delete this; \
return result; \
} \
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) \
override { \
if (ppvObject == nullptr) \
return E_POINTER; \
if (IsEqualIID(iid, __uuidof(IUnknown)) || \
IsEqualIID(iid, __uuidof(INoMarshal)) || \
IsEqualIID(iid, __uuidof(_IFACE_))) { \
*ppvObject = reinterpret_cast<_IFACE_ *>(this); \
reinterpret_cast<_IFACE_ *>(this)->AddRef(); \
return S_OK; \
} \
return E_NOINTERFACE; \
}
class MSFileSysTest {
public:
BEGIN_TEST_CLASS(MSFileSysTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_METHOD(CreationWhenInvokedThenNonNull)
TEST_METHOD(FindFirstWhenInvokedThenHasFile)
TEST_METHOD(FindFirstWhenInvokedThenFailsIfNoMatch)
TEST_METHOD(FindNextWhenLastThenNoMatch)
TEST_METHOD(FindNextWhenExistsThenMatch)
TEST_METHOD(OpenWhenNewThenZeroSize)
};
static LPWSTR CoTaskMemDup(LPCWSTR text) {
if (text == nullptr)
return nullptr;
size_t len = wcslen(text) + 1;
LPWSTR result = (LPWSTR)CoTaskMemAlloc(sizeof(wchar_t) * len);
StringCchCopyW(result, len, text);
return result;
}
class FixedEnumSTATSTG : public IEnumSTATSTG {
SIMPLE_IUNKNOWN_IMPL1(IEnumSTATSTG)
private:
std::vector<STATSTG> m_items;
unsigned m_index;
public:
FixedEnumSTATSTG(const STATSTG *items, unsigned itemCount) {
m_dwRef = 0;
m_index = 0;
m_items.reserve(itemCount);
for (unsigned i = 0; i < itemCount; ++i) {
m_items.push_back(items[i]);
m_items[i].pwcsName = CoTaskMemDup(m_items[i].pwcsName);
}
}
virtual ~FixedEnumSTATSTG() {
for (auto &item : m_items)
CoTaskMemFree(item.pwcsName);
}
HRESULT STDMETHODCALLTYPE Next(ULONG celt, STATSTG *rgelt,
ULONG *pceltFetched) override {
if (celt != 1 || pceltFetched == nullptr)
return E_NOTIMPL;
if (m_index >= m_items.size()) {
*pceltFetched = 0;
return S_FALSE;
}
*pceltFetched = 1;
*rgelt = m_items[m_index];
(*rgelt).pwcsName = CoTaskMemDup((*rgelt).pwcsName);
++m_index;
return S_OK;
}
HRESULT STDMETHODCALLTYPE Skip(ULONG celt) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE Reset(void) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE Clone(IEnumSTATSTG **) override {
return E_NOTIMPL;
}
};
class MockDxcSystemAccess : public IDxcSystemAccess {
SIMPLE_IUNKNOWN_IMPL1(IDxcSystemAccess)
public:
unsigned findCount;
MockDxcSystemAccess() : m_dwRef(0), findCount(1) {}
virtual ~MockDxcSystemAccess() {}
static HRESULT Create(MockDxcSystemAccess **pResult) {
*pResult = new (std::nothrow) MockDxcSystemAccess();
if (*pResult == nullptr)
return E_OUTOFMEMORY;
(*pResult)->AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE EnumFiles(LPCWSTR fileName,
IEnumSTATSTG **pResult) override {
wchar_t hlslName[] = L"filename.hlsl";
wchar_t fxName[] = L"filename2.fx";
STATSTG items[] = {{hlslName,
STGTY_STREAM,
{{0, 0}},
{0, 0},
{0, 0},
{0, 0},
0,
0,
GUID_NULL,
0,
0},
{fxName,
STGTY_STREAM,
{{0, 0}},
{0, 0},
{0, 0},
{0, 0},
0,
0,
GUID_NULL,
0,
0}};
unsigned testCount = (unsigned)std::size(items);
FixedEnumSTATSTG *resultEnum = new (std::nothrow)
FixedEnumSTATSTG(items, std::min(testCount, findCount));
if (resultEnum == nullptr) {
*pResult = nullptr;
return E_OUTOFMEMORY;
}
resultEnum->AddRef();
*pResult = resultEnum;
return S_OK;
}
HRESULT STDMETHODCALLTYPE OpenStorage(LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
IUnknown **pResult) override {
*pResult = SHCreateMemStream(nullptr, 0);
return (*pResult == nullptr) ? E_OUTOFMEMORY : S_OK;
}
HRESULT STDMETHODCALLTYPE
SetStorageTime(IUnknown *storage, const FILETIME *lpCreationTime,
const FILETIME *lpLastAccessTime,
const FILETIME *lpLastWriteTime) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetFileInformationForStorage(
IUnknown *storage,
LPBY_HANDLE_FILE_INFORMATION lpFileInformation) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetFileTypeForStorage(IUnknown *storage,
DWORD *fileType) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CreateHardLinkInStorage(
LPCWSTR lpFileName, LPCWSTR lpExistingFileName) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE MoveStorage(LPCWSTR lpExistingFileName,
LPCWSTR lpNewFileName,
DWORD dwFlags) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE
GetFileAttributesForStorage(LPCWSTR lpFileName, DWORD *pResult) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE DeleteStorage(LPCWSTR lpFileName) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE
RemoveDirectoryStorage(LPCWSTR lpFileName) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE
CreateDirectoryStorage(LPCWSTR lpPathName) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetCurrentDirectoryForStorage(DWORD nBufferLength,
LPWSTR lpBuffer,
DWORD *len) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetMainModuleFileNameW(DWORD nBufferLength,
LPWSTR lpBuffer,
DWORD *len) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetTempStoragePath(DWORD nBufferLength,
LPWSTR lpBuffer,
DWORD *len) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE SupportsCreateSymbolicLink(BOOL *pResult) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CreateSymbolicLinkInStorage(
LPCWSTR lpSymlinkFileName, LPCWSTR lpTargetFileName,
DWORD dwFlags) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CreateStorageMapping(IUnknown *hFile,
DWORD flProtect,
DWORD dwMaximumSizeHigh,
DWORD dwMaximumSizeLow,
IUnknown **pResult) override {
return E_NOTIMPL;
}
HRESULT MapViewOfFile(IUnknown *hFileMappingObject, DWORD dwDesiredAccess,
DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow,
SIZE_T dwNumberOfBytesToMap,
ID3D10Blob **pResult) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE OpenStdStorage(int standardFD,
IUnknown **pResult) override {
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE GetStreamDisplay(ITextFont **textFont,
unsigned *columnCount) override {
return E_NOTIMPL;
}
};
void MSFileSysTest::CreationWhenInvokedThenNonNull() {
CComPtr<MockDxcSystemAccess> access;
VERIFY_SUCCEEDED(MockDxcSystemAccess::Create(&access));
MSFileSystem *fileSystem;
VERIFY_SUCCEEDED(CreateMSFileSystemForIface(access, &fileSystem));
VERIFY_IS_NOT_NULL(fileSystem);
delete fileSystem;
}
void MSFileSysTest::FindFirstWhenInvokedThenHasFile() {
CComPtr<MockDxcSystemAccess> access;
MockDxcSystemAccess::Create(&access);
MSFileSystem *fileSystem;
CreateMSFileSystemForIface(access, &fileSystem);
WIN32_FIND_DATAW findData;
HANDLE h = fileSystem->FindFirstFileW(L"foobar", &findData);
VERIFY_ARE_EQUAL_WSTR(L"filename.hlsl", findData.cFileName);
VERIFY_ARE_NOT_EQUAL(INVALID_HANDLE_VALUE, h);
fileSystem->FindClose(h);
delete fileSystem;
}
void MSFileSysTest::FindFirstWhenInvokedThenFailsIfNoMatch() {
CComPtr<MockDxcSystemAccess> access;
MockDxcSystemAccess::Create(&access);
access->findCount = 0;
MSFileSystem *fileSystem;
CreateMSFileSystemForIface(access, &fileSystem);
WIN32_FIND_DATAW findData;
HANDLE h = fileSystem->FindFirstFileW(L"foobar", &findData);
VERIFY_ARE_EQUAL(ERROR_FILE_NOT_FOUND, (long)GetLastError());
VERIFY_ARE_EQUAL(INVALID_HANDLE_VALUE, h);
VERIFY_ARE_EQUAL_WSTR(L"", findData.cFileName);
delete fileSystem;
}
void MSFileSysTest::FindNextWhenLastThenNoMatch() {
CComPtr<MockDxcSystemAccess> access;
MockDxcSystemAccess::Create(&access);
MSFileSystem *fileSystem;
CreateMSFileSystemForIface(access, &fileSystem);
WIN32_FIND_DATAW findData;
HANDLE h = fileSystem->FindFirstFileW(L"foobar", &findData);
VERIFY_ARE_NOT_EQUAL(INVALID_HANDLE_VALUE, h);
BOOL findNext = fileSystem->FindNextFileW(h, &findData);
VERIFY_IS_FALSE(findNext);
VERIFY_ARE_EQUAL(ERROR_FILE_NOT_FOUND, (long)GetLastError());
fileSystem->FindClose(h);
delete fileSystem;
}
void MSFileSysTest::FindNextWhenExistsThenMatch() {
CComPtr<MockDxcSystemAccess> access;
MockDxcSystemAccess::Create(&access);
access->findCount = 2;
MSFileSystem *fileSystem;
CreateMSFileSystemForIface(access, &fileSystem);
WIN32_FIND_DATAW findData;
HANDLE h = fileSystem->FindFirstFileW(L"foobar", &findData);
VERIFY_ARE_NOT_EQUAL(INVALID_HANDLE_VALUE, h);
BOOL findNext = fileSystem->FindNextFileW(h, &findData);
VERIFY_IS_TRUE(findNext);
VERIFY_ARE_EQUAL_WSTR(L"filename2.fx", findData.cFileName);
VERIFY_IS_FALSE(fileSystem->FindNextFileW(h, &findData));
fileSystem->FindClose(h);
delete fileSystem;
}
void MSFileSysTest::OpenWhenNewThenZeroSize() {
CComPtr<MockDxcSystemAccess> access;
MockDxcSystemAccess::Create(&access);
MSFileSystem *fileSystem;
CreateMSFileSystemForIface(access, &fileSystem);
HANDLE h = fileSystem->CreateFileW(L"new.hlsl", 0, 0, 0, 0);
VERIFY_ARE_NOT_EQUAL(INVALID_HANDLE_VALUE, h);
char buf[4];
DWORD bytesRead;
VERIFY_IS_TRUE(fileSystem->ReadFile(h, buf, _countof(buf), &bytesRead));
VERIFY_ARE_EQUAL(0u, bytesRead);
fileSystem->CloseHandle(h);
delete fileSystem;
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/SystemValueTest.cpp
|
///////////////////////////////////////////////////////////////////////////////
// //
// SystemValueTest.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Test system values at various signature points //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "dxc/dxcapi.h"
#include <algorithm>
#include <cassert>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "dxc/Test/DxcTestUtils.h"
#include "dxc/Test/HlslTestUtils.h"
#include "dxc/Support/Global.h"
#include "dxc/Support/HLSLOptions.h"
#include "dxc/Support/Unicode.h"
#include "dxc/Support/dxcapi.use.h"
#include "llvm/Support/raw_os_ostream.h"
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilSemantic.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DXIL/DxilSigPoint.h"
#include <fstream>
using namespace std;
using namespace hlsl_test;
using namespace hlsl;
#ifdef _WIN32
class SystemValueTest {
#else
class SystemValueTest : public ::testing::Test {
#endif
public:
BEGIN_TEST_CLASS(SystemValueTest)
TEST_CLASS_PROPERTY(L"Parallel", L"true")
TEST_METHOD_PROPERTY(L"Priority", L"0")
END_TEST_CLASS()
TEST_CLASS_SETUP(InitSupport);
TEST_METHOD(VerifyArbitrarySupport)
TEST_METHOD(VerifyNotAvailableFail)
TEST_METHOD(VerifySVAsArbitrary)
TEST_METHOD(VerifySVAsSV)
TEST_METHOD(VerifySGV)
TEST_METHOD(VerifySVNotPacked)
TEST_METHOD(VerifySVNotInSig)
TEST_METHOD(VerifyVertexPacking)
TEST_METHOD(VerifyPatchConstantPacking)
TEST_METHOD(VerifyTargetPacking)
TEST_METHOD(VerifyTessFactors)
TEST_METHOD(VerifyShadowEntries)
TEST_METHOD(VerifyVersionedSemantics)
TEST_METHOD(VerifyMissingSemanticFailure)
void CompileHLSLTemplate(CComPtr<IDxcOperationResult> &pResult,
DXIL::SigPointKind sigPointKind,
DXIL::SemanticKind semKind, bool addArb,
unsigned Major = 0, unsigned Minor = 0) {
const Semantic *sem = Semantic::Get(semKind);
const char *pSemName = sem->GetName();
std::wstring sigDefValue(L"");
if (semKind < DXIL::SemanticKind::Invalid && pSemName) {
if (Semantic::HasSVPrefix(pSemName))
pSemName += 3;
CA2W semNameW(pSemName);
sigDefValue = L"Def_";
sigDefValue += semNameW;
}
if (addArb) {
if (!sigDefValue.empty())
sigDefValue += L" ";
sigDefValue += L"Def_Arb(uint, arb0, ARB0)";
}
return CompileHLSLTemplate(pResult, sigPointKind, sigDefValue, Major,
Minor);
}
void CompileHLSLTemplate(CComPtr<IDxcOperationResult> &pResult,
DXIL::SigPointKind sigPointKind,
const std::wstring &sigDefValue, unsigned Major = 0,
unsigned Minor = 0) {
const SigPoint *sigPoint = SigPoint::GetSigPoint(sigPointKind);
DXIL::ShaderKind shaderKind = sigPoint->GetShaderKind();
std::wstring path = hlsl_test::GetPathToHlslDataFile(L"system-values.hlsl");
CComPtr<IDxcCompiler> pCompiler;
VERIFY_SUCCEEDED(
m_dllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
if (!m_pSource) {
CComPtr<IDxcLibrary> library;
IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
IFT(library->CreateBlobFromFile(path.c_str(), nullptr, &m_pSource));
}
LPCWSTR entry, profile;
wchar_t profile_buf[] = L"vs_6_1";
switch (shaderKind) {
case DXIL::ShaderKind::Vertex:
entry = L"VSMain";
profile = L"vs_6_1";
break;
case DXIL::ShaderKind::Pixel:
entry = L"PSMain";
profile = L"ps_6_1";
break;
case DXIL::ShaderKind::Geometry:
entry = L"GSMain";
profile = L"gs_6_1";
break;
case DXIL::ShaderKind::Hull:
entry = L"HSMain";
profile = L"hs_6_1";
break;
case DXIL::ShaderKind::Domain:
entry = L"DSMain";
profile = L"ds_6_1";
break;
case DXIL::ShaderKind::Compute:
entry = L"CSMain";
profile = L"cs_6_1";
break;
case DXIL::ShaderKind::Mesh:
entry = L"MSMain";
profile = L"ms_6_5";
break;
case DXIL::ShaderKind::Amplification:
entry = L"ASMain";
profile = L"as_6_5";
break;
case DXIL::ShaderKind::Library:
case DXIL::ShaderKind::Invalid:
assert(!"invalid shaderKind");
break;
}
if (Major == 0) {
Major = m_HighestMajor;
Minor = m_HighestMinor;
}
if (Major != 6 || Minor != 1) {
profile_buf[0] = profile[0];
profile_buf[3] = L'0' + (wchar_t)Major;
profile_buf[5] = L'0' + (wchar_t)Minor;
profile = profile_buf;
}
CA2W sigPointNameW(sigPoint->GetName());
// Strip SV_ from semantic name
std::wstring sigDefName(sigPointNameW);
sigDefName += L"_Defs";
DxcDefine define;
define.Name = sigDefName.c_str();
define.Value = sigDefValue.c_str();
VERIFY_SUCCEEDED(pCompiler->Compile(m_pSource, path.c_str(), entry, profile,
nullptr, 0, &define, 1, nullptr,
&pResult));
}
void CheckAnyOperationResultMsg(IDxcOperationResult *pResult,
const char **pErrorMsgArray = nullptr,
unsigned ErrorMsgCount = 0) {
HRESULT status;
VERIFY_SUCCEEDED(pResult->GetStatus(&status));
if (pErrorMsgArray == nullptr || ErrorMsgCount == 0) {
VERIFY_SUCCEEDED(status);
return;
}
VERIFY_FAILED(status);
CComPtr<IDxcBlobEncoding> text;
VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&text));
const char *pStart = (const char *)text->GetBufferPointer();
const char *pEnd = pStart + text->GetBufferSize();
bool bMessageFound = false;
for (unsigned i = 0; i < ErrorMsgCount; i++) {
const char *pErrorMsg = pErrorMsgArray[i];
const char *pMatch =
std::search(pStart, pEnd, pErrorMsg, pErrorMsg + strlen(pErrorMsg));
if (pEnd != pMatch)
bMessageFound = true;
}
VERIFY_IS_TRUE(bMessageFound);
}
dxc::DxcDllSupport m_dllSupport;
VersionSupportInfo m_ver;
unsigned m_HighestMajor, m_HighestMinor; // Shader Model Supported
CComPtr<IDxcBlobEncoding> m_pSource;
};
bool SystemValueTest::InitSupport() {
if (!m_dllSupport.IsEnabled()) {
VERIFY_SUCCEEDED(m_dllSupport.Initialize());
m_ver.Initialize(m_dllSupport);
m_HighestMajor = 6;
m_HighestMinor = 0;
if ((m_ver.m_DxilMajor > 1 ||
(m_ver.m_DxilMajor == 1 && m_ver.m_DxilMinor > 1)) &&
(m_ver.m_ValMajor > 1 ||
(m_ver.m_ValMajor == 1 && m_ver.m_ValMinor > 1))) {
m_HighestMinor = 1;
}
}
return true;
}
static bool ArbAllowed(DXIL::SigPointKind sp) {
switch (sp) {
case DXIL::SigPointKind::VSIn:
case DXIL::SigPointKind::VSOut:
case DXIL::SigPointKind::GSVIn:
case DXIL::SigPointKind::GSOut:
case DXIL::SigPointKind::HSCPIn:
case DXIL::SigPointKind::HSCPOut:
case DXIL::SigPointKind::PCOut:
case DXIL::SigPointKind::DSCPIn:
case DXIL::SigPointKind::DSIn:
case DXIL::SigPointKind::DSOut:
case DXIL::SigPointKind::PSIn:
case DXIL::SigPointKind::MSOut:
case DXIL::SigPointKind::MSPOut:
return true;
default:
return false;
}
return false;
}
TEST_F(SystemValueTest, VerifyArbitrarySupport) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, DXIL::SemanticKind::Invalid, true);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
if (ArbAllowed(sp)) {
CheckAnyOperationResultMsg(pResult);
} else {
// TODO: We should probably improve this error message since it pertains
// to a parameter at a particular signature point, not necessarily the
// whole shader model. These are a couple of possible errors: error:
// invalid semantic 'ARB' for <sm> error: Semantic ARB is invalid for
// shader model <sm> error: invalid semantic found in <sm>
const char *Errors[] = {
"error: Semantic ARB is invalid for shader model",
"error: invalid semantic 'ARB' for",
"error: invalid semantic found in CS",
};
CheckAnyOperationResultMsg(pResult, Errors, _countof(Errors));
}
}
}
TEST_F(SystemValueTest, VerifyNotAvailableFail) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
for (DXIL::SemanticKind sv =
(DXIL::SemanticKind)((unsigned)DXIL::SemanticKind::Arbitrary + 1);
sv < DXIL::SemanticKind::Invalid;
sv = (DXIL::SemanticKind)((unsigned)sv + 1)) {
if (sv == DXIL::SemanticKind::CullPrimitive) {
// TODO: add tests for CullPrimitive
continue;
}
DXIL::SemanticInterpretationKind interpretation =
hlsl::SigPoint::GetInterpretation(sv, sp, m_HighestMajor,
m_HighestMinor);
if (interpretation == DXIL::SemanticInterpretationKind::NA) {
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sv, false);
// error: Semantic SV_SampleIndex is invalid for shader model: vs
// error: invalid semantic 'SV_VertexID' for gs
// error: invalid semantic found in CS
const Semantic *pSemantic = Semantic::Get(sv);
const char *SemName = pSemantic->GetName();
std::string ErrorStrs[] = {
std::string("error: Semantic ") + SemName +
" is invalid for shader model:",
std::string("error: invalid semantic '") + SemName + "' for",
"error: invalid semantic found in CS",
};
const char *Errors[_countof(ErrorStrs)];
for (unsigned i = 0; i < _countof(ErrorStrs); i++)
Errors[i] = ErrorStrs[i].c_str();
CheckAnyOperationResultMsg(pResult, Errors, _countof(Errors));
}
}
}
}
TEST_F(SystemValueTest, VerifySVAsArbitrary) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
for (DXIL::SemanticKind sv =
(DXIL::SemanticKind)((unsigned)DXIL::SemanticKind::Arbitrary + 1);
sv < DXIL::SemanticKind::Invalid;
sv = (DXIL::SemanticKind)((unsigned)sv + 1)) {
DXIL::SemanticInterpretationKind interpretation =
hlsl::SigPoint::GetInterpretation(sv, sp, m_HighestMajor,
m_HighestMinor);
if (interpretation == DXIL::SemanticInterpretationKind::Arb) {
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sv, false);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
// TODO: Verify system value item is included in signature, treated as
// arbitrary,
// and that the element id is used in load input instruction.
}
}
}
}
TEST_F(SystemValueTest, VerifySVAsSV) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
for (DXIL::SemanticKind sv =
(DXIL::SemanticKind)((unsigned)DXIL::SemanticKind::Arbitrary + 1);
sv < DXIL::SemanticKind::Invalid;
sv = (DXIL::SemanticKind)((unsigned)sv + 1)) {
DXIL::SemanticInterpretationKind interpretation =
hlsl::SigPoint::GetInterpretation(sv, sp, m_HighestMajor,
m_HighestMinor);
if (interpretation == DXIL::SemanticInterpretationKind::SV ||
interpretation == DXIL::SemanticInterpretationKind::SGV) {
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sv, false);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
// TODO: Verify system value is included in signature, system value enum
// is appropriately set,
// and that the element id is used in load input instruction.
}
}
}
}
TEST_F(SystemValueTest, VerifySGV) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
for (DXIL::SemanticKind sv =
(DXIL::SemanticKind)((unsigned)DXIL::SemanticKind::Arbitrary + 1);
sv < DXIL::SemanticKind::Invalid;
sv = (DXIL::SemanticKind)((unsigned)sv + 1)) {
DXIL::SemanticInterpretationKind interpretation =
hlsl::SigPoint::GetInterpretation(sv, sp, m_HighestMajor,
m_HighestMinor);
if (interpretation == DXIL::SemanticInterpretationKind::SGV) {
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sv, true);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
// TODO: Verify system value is included in signature and arbitrary is
// packed before system value
// Or: verify failed when using greedy signature packing
// TODO: Verify warning about declaring the system value last for fxc
// HLSL compatibility.
}
}
}
}
TEST_F(SystemValueTest, VerifySVNotPacked) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
for (DXIL::SemanticKind sv =
(DXIL::SemanticKind)((unsigned)DXIL::SemanticKind::Arbitrary + 1);
sv < DXIL::SemanticKind::Invalid;
sv = (DXIL::SemanticKind)((unsigned)sv + 1)) {
DXIL::SemanticInterpretationKind interpretation =
hlsl::SigPoint::GetInterpretation(sv, sp, m_HighestMajor,
m_HighestMinor);
if (interpretation == DXIL::SemanticInterpretationKind::NotPacked) {
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sv, false);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
// TODO: Verify system value is included in signature and has packing
// location (-1, -1),
// and that the element id is used in load input instruction.
}
}
}
}
TEST_F(SystemValueTest, VerifySVNotInSig) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
for (DXIL::SemanticKind sv =
(DXIL::SemanticKind)((unsigned)DXIL::SemanticKind::Arbitrary + 1);
sv < DXIL::SemanticKind::Invalid;
sv = (DXIL::SemanticKind)((unsigned)sv + 1)) {
DXIL::SemanticInterpretationKind interpretation =
hlsl::SigPoint::GetInterpretation(sv, sp, m_HighestMajor,
m_HighestMinor);
if (interpretation == DXIL::SemanticInterpretationKind::NotInSig) {
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sv, false);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
// TODO: Verify system value is not included in signature,
// that intrinsic function is used, and that the element id is not used
// in load input instruction.
}
}
}
}
TEST_F(SystemValueTest, VerifyVertexPacking) {
// TODO: Implement
VERIFY_IS_TRUE("Not Implemented");
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
DXIL::PackingKind pk = SigPoint::GetSigPoint(sp)->GetPackingKind();
if (pk == DXIL::PackingKind::Vertex) {
// TBD: Test constraints here, or add constraints to validator and just
// generate cases to pack here, expecting success?
}
}
}
TEST_F(SystemValueTest, VerifyPatchConstantPacking) {
// TODO: Implement
VERIFY_IS_TRUE("Not Implemented");
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
DXIL::PackingKind pk = SigPoint::GetSigPoint(sp)->GetPackingKind();
if (pk == DXIL::PackingKind::PatchConstant) {
// TBD: Test constraints here, or add constraints to validator and just
// generate cases to pack here, expecting success?
}
}
}
TEST_F(SystemValueTest, VerifyTargetPacking) {
// TODO: Implement
VERIFY_IS_TRUE("Not Implemented");
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
DXIL::PackingKind pk = SigPoint::GetSigPoint(sp)->GetPackingKind();
if (pk == DXIL::PackingKind::Target) {
// TBD: Test constraints here, or add constraints to validator and just
// generate cases to pack here, expecting success?
}
}
}
TEST_F(SystemValueTest, VerifyTessFactors) {
// TODO: Implement
VERIFY_IS_TRUE("Not Implemented");
// TBD: Split between return and out params?
}
TEST_F(SystemValueTest, VerifyShadowEntries) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
for (DXIL::SemanticKind sv =
(DXIL::SemanticKind)((unsigned)DXIL::SemanticKind::Arbitrary + 1);
sv < DXIL::SemanticKind::Invalid;
sv = (DXIL::SemanticKind)((unsigned)sv + 1)) {
DXIL::SemanticInterpretationKind interpretation =
hlsl::SigPoint::GetInterpretation(sv, sp, m_HighestMajor,
m_HighestMinor);
if (interpretation == DXIL::SemanticInterpretationKind::Shadow) {
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sv, false);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
// TODO: Verify system value is included in corresponding signature
// (with fallback),
// that intrinsic function is used, and that the element id is not used
// in load input instruction.
}
}
}
}
TEST_F(SystemValueTest, VerifyVersionedSemantics) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
struct TestInfo {
DXIL::SigPointKind sp;
DXIL::SemanticKind sv;
unsigned Major, Minor;
};
const unsigned kNumTests = 13;
TestInfo info[kNumTests] = {
{DXIL::SigPointKind::PSIn, DXIL::SemanticKind::SampleIndex, 4, 1},
{DXIL::SigPointKind::PSIn, DXIL::SemanticKind::Coverage, 5, 0},
{DXIL::SigPointKind::PSOut, DXIL::SemanticKind::Coverage, 4, 1},
{DXIL::SigPointKind::PSIn, DXIL::SemanticKind::InnerCoverage, 5, 0},
{DXIL::SigPointKind::PSOut, DXIL::SemanticKind::DepthLessEqual, 5, 0},
{DXIL::SigPointKind::PSOut, DXIL::SemanticKind::DepthGreaterEqual, 5, 0},
{DXIL::SigPointKind::PSOut, DXIL::SemanticKind::StencilRef, 5, 0},
{DXIL::SigPointKind::VSIn, DXIL::SemanticKind::ViewID, 6, 1},
{DXIL::SigPointKind::HSIn, DXIL::SemanticKind::ViewID, 6, 1},
{DXIL::SigPointKind::PCIn, DXIL::SemanticKind::ViewID, 6, 1},
{DXIL::SigPointKind::DSIn, DXIL::SemanticKind::ViewID, 6, 1},
{DXIL::SigPointKind::GSIn, DXIL::SemanticKind::ViewID, 6, 1},
{DXIL::SigPointKind::PSIn, DXIL::SemanticKind::ViewID, 6, 1},
};
for (unsigned i = 0; i < kNumTests; i++) {
TestInfo &test = info[i];
unsigned MajorLower = test.Major, MinorLower = test.Minor;
if (MinorLower > 0)
MinorLower--;
else {
MajorLower--;
MinorLower = 1;
}
DXIL::SemanticInterpretationKind SI = hlsl::SigPoint::GetInterpretation(
test.sv, test.sp, test.Major, test.Minor);
VERIFY_IS_TRUE(SI != DXIL::SemanticInterpretationKind::NA);
DXIL::SemanticInterpretationKind SILower =
hlsl::SigPoint::GetInterpretation(test.sv, test.sp, MajorLower,
MinorLower);
VERIFY_IS_TRUE(SILower == DXIL::SemanticInterpretationKind::NA);
// Don't try compiling to pre-dxil targets:
if (MajorLower < 6)
continue;
// Don't try targets our compiler/validator combination do not support.
if (test.Major > m_HighestMajor || test.Minor > m_HighestMinor)
continue;
{
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, test.sp, test.sv, false, test.Major,
test.Minor);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_SUCCEEDED(result);
}
{
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, test.sp, test.sv, false, MajorLower,
MinorLower);
HRESULT result;
VERIFY_SUCCEEDED(pResult->GetStatus(&result));
VERIFY_FAILED(result);
const char *Errors[] = {"is invalid for shader model",
"error: invalid semantic"};
CheckAnyOperationResultMsg(pResult, Errors, _countof(Errors));
}
}
}
TEST_F(SystemValueTest, VerifyMissingSemanticFailure) {
WEX::TestExecution::SetVerifyOutput verifySettings(
WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
for (DXIL::SigPointKind sp = (DXIL::SigPointKind)0;
sp < DXIL::SigPointKind::Invalid;
sp = (DXIL::SigPointKind)((unsigned)sp + 1)) {
if (sp >= DXIL::SigPointKind::MSIn && sp <= DXIL::SigPointKind::ASIn) {
// TODO: add tests for mesh/amplification shaders to system-values.hlsl
continue;
}
std::wstring sigDefValue(L"Def_Arb_NoSem(uint, arb0)");
CComPtr<IDxcOperationResult> pResult;
CompileHLSLTemplate(pResult, sp, sigDefValue);
const char *Errors[] = {
"error: Semantic must be defined for all parameters of an entry "
"function or patch constant function",
"error: Semantic must be defined for all outputs of an entry function "
"or patch constant function"};
CheckAnyOperationResultMsg(pResult, Errors, _countof(Errors));
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/TestHeaders/TestPdbUtilsPathNormalizations.h
|
#pragma once
static const llvm::StringRef kTestPdbUtilsPathNormalizationsIR = R"x(
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
define void @main() {
entry:
call void @dx.op.storeOutput.f32(i32 5, i32 0, i32 0, i8 0, float 0.000000e+00), !dbg !30 ; line:2 col:28 ; StoreOutput(outputSigId,rowIndex,colIndex,value)
ret void, !dbg !30 ; line:2 col:28
}
; Function Attrs: nounwind
declare void @dx.op.storeOutput.f32(i32, i32, i32, i8, float) #0
attributes #0 = { nounwind }
!llvm.dbg.cu = !{!0}
!llvm.module.flags = !{!10, !11}
!llvm.ident = !{!12}
!dx.source.contents = !{!13, !14}
!dx.source.defines = !{!2}
!dx.source.mainFileName = !{!15}
!dx.source.args = !{!16}
!dx.version = !{!17}
!dx.valver = !{!18}
!dx.shaderModel = !{!19}
!dx.typeAnnotations = !{!20}
!dx.viewIdState = !{!23}
!dx.entryPoints = !{!24}
!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "dxc(private) 1.7.0.4135 (pdb_header_fix, 24cf4a146)", isOptimized: false, runtimeVersion: 0, emissionKind: 1, enums: !2, subprograms: !3)
!1 = !DIFile(filename: "<MAIN_FILE>", directory: "")
!2 = !{}
!3 = !{!4, !8}
!4 = !DISubprogram(name: "main", scope: !1, file: !1, line: 2, type: !5, isLocal: false, isDefinition: true, scopeLine: 2, flags: DIFlagPrototyped, isOptimized: false, function: void ()* @main)
!5 = !DISubroutineType(types: !6)
!6 = !{!7}
!7 = !DIBasicType(name: "float", size: 32, align: 32, encoding: DW_ATE_float)
!8 = !DISubprogram(name: "foo", linkageName: "\01?foo@@YAMXZ", scope: !9, file: !9, line: 1, type: !5, isLocal: false, isDefinition: true, scopeLine: 1, flags: DIFlagPrototyped, isOptimized: false)
!9 = !DIFile(filename: "<INCLUDE_FILE>", directory: "")
!10 = !{i32 2, !"Dwarf Version", i32 4}
!11 = !{i32 2, !"Debug Info Version", i32 3}
!12 = !{!"dxc(private) 1.7.0.4135 (pdb_header_fix, 24cf4a146)"}
!13 = !{!"<MAIN_FILE>", !"#include \22include.h\22\0D\0Afloat main() : SV_Target { return foo(); }\0D\0A"}
!14 = !{!"<INCLUDE_FILE>", !"float foo() {\0D\0A return 0;\0D\0A}\0D\0A"}
!15 = !{!"<MAIN_FILE>"}
!16 = !{!"-E", !"main", !"-T", !"ps_6_0", !"/Zi", !"-Qembed_debug"}
!17 = !{i32 1, i32 0}
!18 = !{i32 1, i32 8}
!19 = !{!"ps", i32 6, i32 0}
!20 = !{i32 1, void ()* @main, !21}
!21 = !{!22}
!22 = !{i32 0, !2, !2}
!23 = !{[2 x i32] [i32 0, i32 1]}
!24 = !{void ()* @main, !"main", !25, null, null}
!25 = !{null, !26, null}
!26 = !{!27}
!27 = !{i32 0, !"SV_Target", i8 9, i8 16, !28, i8 0, i32 1, i8 1, i32 0, i8 0, !29}
!28 = !{i32 0}
!29 = !{i32 3, i32 1}
!30 = !DILocation(line: 2, column: 28, scope: !4)
)x";
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL
|
repos/DirectXShaderCompiler/tools/clang/unittests/HLSL/TestHeaders/TestDxilWithEmptyDefine.h
|
#if 0
;
; Input signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; no parameters
;
; Output signature:
;
; Name Index Mask Register SysValue Format Used
; -------------------- ----- ------ -------- -------- ------- ------
; SV_Target 0 x 0 TARGET float x
;
; shader debug name: 21c11f2029d870c04dedb3fe6b46bf27.pdb
; shader hash: 21c11f2029d870c04dedb3fe6b46bf27
;
; Pipeline Runtime Information:
;
; Pixel Shader
; DepthOutput=0
; SampleFrequency=0
;
;
; Output signature:
;
; Name Index InterpMode DynIdx
; -------------------- ----- ---------------------- ------
; SV_Target 0
;
; Buffer Definitions:
;
;
; Resource Bindings:
;
; Name Type Format Dim ID HLSL Bind Count
; ------------------------------ ---------- ------- ----------- ------- -------------- ------
;
;
; ViewId state:
;
; Number of inputs: 0, outputs: 1
; Outputs dependent on ViewId: { }
; Inputs contributing to computation of Outputs:
;
target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"
target triple = "dxil-ms-dx"
define void @main() {
entry:
call void @dx.op.storeOutput.f32(i32 5, i32 0, i32 0, i8 0, float 0.000000e+00), !dbg !28 ; line:1 col:28 ; StoreOutput(outputSigId,rowIndex,colIndex,value)
ret void, !dbg !28 ; line:1 col:28
}
; Function Attrs: nounwind
declare void @dx.op.storeOutput.f32(i32, i32, i32, i8, float) #0
attributes #0 = { nounwind }
!llvm.dbg.cu = !{!0}
!llvm.module.flags = !{!8, !9}
!llvm.ident = !{!10}
!dx.source.contents = !{!11}
!dx.source.defines = !{!12}
!dx.source.mainFileName = !{!13}
!dx.source.args = !{!14}
!dx.version = !{!15}
!dx.valver = !{!16}
!dx.shaderModel = !{!17}
!dx.typeAnnotations = !{!18}
!dx.viewIdState = !{!21}
!dx.entryPoints = !{!22}
!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "dxc(private) 1.7.0.13784 (main, e93cb6343)", isOptimized: false, runtimeVersion: 0, emissionKind: 1, enums: !2, subprograms: !3)
!1 = !DIFile(filename: "F:\5Ctest\5Cbad.hlsl", directory: "")
!2 = !{}
!3 = !{!4}
!4 = !DISubprogram(name: "main", scope: !1, file: !1, line: 1, type: !5, isLocal: false, isDefinition: true, scopeLine: 1, flags: DIFlagPrototyped, isOptimized: false, function: void ()* @main)
!5 = !DISubroutineType(types: !6)
!6 = !{!7}
!7 = !DIBasicType(name: "float", size: 32, align: 32, encoding: DW_ATE_float)
!8 = !{i32 2, !"Dwarf Version", i32 4}
!9 = !{i32 2, !"Debug Info Version", i32 3}
!10 = !{!"dxc(private) 1.7.0.13784 (main, e93cb6343)"}
!11 = !{!"F:\5Ctest\5Cbad.hlsl", !"float main() : SV_Target { return 0; }\0D\0A"}
!12 = !{!"OTHER_DEFINE=1", !"OTHER_DEFINE=1"}
!13 = !{!"F:\5Ctest\5Cbad.hlsl"}
!14 = !{!"-E", !"main", !"-T", !"ps_6_0", !"/Zi", !"/Qstrip_reflect", !"/Qembed_debug", !"/D", !"", !"/D", !"OTHER_DEFINE=1", !"-D", !"OTHER_DEFINE=1"}
!15 = !{i32 1, i32 0}
!16 = !{i32 1, i32 5}
!17 = !{!"ps", i32 6, i32 0}
!18 = !{i32 1, void ()* @main, !19}
!19 = !{!20}
!20 = !{i32 0, !2, !2}
!21 = !{[2 x i32] [i32 0, i32 1]}
!22 = !{void ()* @main, !"main", !23, null, null}
!23 = !{null, !24, null}
!24 = !{!25}
!25 = !{i32 0, !"SV_Target", i8 9, i8 16, !26, i8 0, i32 1, i8 1, i32 0, i8 0, !27}
!26 = !{i32 0}
!27 = !{i32 3, i32 1}
!28 = !DILocation(line: 1, column: 28, scope: !4)
#endif
const unsigned char g_TestDxilWithEmptyDefine[] = {
0x44, 0x58, 0x42, 0x43, 0x3a, 0x12, 0x2e, 0xe6, 0x05, 0x8d, 0xbf, 0xab,
0xa6, 0xa9, 0x93, 0x31, 0x0d, 0xf0, 0x60, 0x11, 0x01, 0x00, 0x00, 0x00,
0x8e, 0x0b, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x50, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x9a, 0x00, 0x00, 0x00,
0xf2, 0x00, 0x00, 0x00, 0x02, 0x07, 0x00, 0x00, 0x36, 0x07, 0x00, 0x00,
0x52, 0x07, 0x00, 0x00, 0x53, 0x46, 0x49, 0x30, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x31,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x4f, 0x53, 0x47, 0x31, 0x32, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x53, 0x56, 0x5f, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x00, 0x50, 0x53,
0x56, 0x30, 0x50, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x10, 0x03, 0x00,
0x00, 0x00, 0x49, 0x4c, 0x44, 0x42, 0x08, 0x06, 0x00, 0x00, 0x60, 0x00,
0x00, 0x00, 0x82, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c, 0x00, 0x01,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0xf0, 0x05, 0x00, 0x00, 0x42, 0x43,
0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x79, 0x01, 0x00, 0x00, 0x0b, 0x82,
0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x07, 0x81,
0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39, 0x92, 0x01,
0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62, 0x80, 0x10,
0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0x84, 0x10, 0x32, 0x14, 0x38, 0x08,
0x18, 0x4b, 0x0a, 0x32, 0x42, 0x88, 0x48, 0x90, 0x14, 0x20, 0x43, 0x46,
0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90, 0x11, 0x22,
0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a, 0x04, 0x21,
0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x1b, 0x88,
0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0x00, 0x00, 0x49, 0x18,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x13, 0x82, 0x00, 0x00, 0x89, 0x20,
0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x32, 0x22, 0x08, 0x09, 0x20, 0x64,
0x85, 0x04, 0x13, 0x22, 0xa4, 0x84, 0x04, 0x13, 0x22, 0xe3, 0x84, 0xa1,
0x90, 0x14, 0x12, 0x4c, 0x88, 0x8c, 0x0b, 0x84, 0x84, 0x4c, 0x10, 0x28,
0x23, 0x00, 0x25, 0x00, 0x8a, 0x39, 0x02, 0x30, 0x98, 0x23, 0x40, 0x66,
0x00, 0x8a, 0x01, 0x33, 0x43, 0x45, 0x36, 0x10, 0x90, 0x02, 0x03, 0x00,
0x00, 0x00, 0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68,
0x87, 0x79, 0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d,
0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73,
0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9,
0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76,
0x40, 0x07, 0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76,
0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x06,
0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x81,
0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x10, 0x19, 0x11,
0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x9a, 0x22, 0x28,
0x84, 0x32, 0x28, 0x81, 0x11, 0x80, 0x52, 0x28, 0x06, 0xa2, 0x92, 0x28,
0x90, 0x11, 0x80, 0x12, 0xa0, 0x1c, 0x4b, 0x00, 0x02, 0x00, 0x79, 0x18,
0x00, 0x00, 0xad, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02,
0x13, 0x44, 0xc8, 0x48, 0x87, 0x8b, 0xae, 0x6c, 0x8e, 0x8e, 0x4b, 0x2c,
0x8c, 0xcc, 0x05, 0x8d, 0x6d, 0x8e, 0x6d, 0xd0, 0x00, 0x04, 0x00, 0xd5,
0x80, 0x0c, 0x6f, 0x0c, 0x05, 0x4e, 0x2e, 0xcd, 0x2e, 0x8c, 0xae, 0x2c,
0x05, 0x24, 0xc6, 0xe5, 0xc6, 0x05, 0xc6, 0x25, 0x66, 0xe6, 0x06, 0x87,
0x06, 0x04, 0xa5, 0x2d, 0x2c, 0xcd, 0x8d, 0x05, 0xa4, 0x2c, 0x67, 0x66,
0x4c, 0xcc, 0x66, 0x86, 0x66, 0x26, 0x65, 0x03, 0x40, 0xa2, 0x2d, 0x2c,
0xcd, 0x8d, 0x85, 0x19, 0xdb, 0x5b, 0x18, 0xdd, 0x1e, 0x03, 0x20, 0x03,
0x03, 0x0c, 0xc0, 0x80, 0xd8, 0x10, 0x1c, 0x9b, 0x06, 0x00, 0x40, 0x26,
0x08, 0x02, 0xb0, 0x6a, 0x02, 0x84, 0x02, 0x10, 0x82, 0x04, 0x08, 0x02,
0x00, 0x00, 0x40, 0x04, 0x50, 0x00, 0x00, 0xd8, 0x10, 0x2c, 0xa3, 0x9e,
0x80, 0x10, 0x06, 0x00, 0x00, 0x80, 0x80, 0x00, 0x18, 0x00, 0x00, 0x26,
0x08, 0x83, 0xc0, 0x86, 0xe8, 0x2e, 0x4c, 0xce, 0x0c, 0xc4, 0xaa, 0x4c,
0x6e, 0x2e, 0xed, 0xcd, 0x6d, 0x82, 0x30, 0x0c, 0x1b, 0x06, 0xe7, 0x81,
0x28, 0x11, 0x95, 0x89, 0xd5, 0x9d, 0x81, 0x24, 0xb9, 0x99, 0xbd, 0x81,
0x58, 0x95, 0xc9, 0xcd, 0xa5, 0xbd, 0xb9, 0x4d, 0x10, 0x06, 0x62, 0xc3,
0xe0, 0x48, 0xd3, 0x86, 0x60, 0x20, 0x1a, 0x98, 0xb1, 0xbd, 0x85, 0xd1,
0x81, 0xb4, 0x85, 0xa5, 0xb9, 0xa1, 0xa4, 0x80, 0xe8, 0x80, 0x4c, 0x59,
0x7d, 0x51, 0x85, 0xc9, 0x9d, 0x95, 0xd1, 0x81, 0xec, 0x81, 0xc8, 0x95,
0xd1, 0xd5, 0xc9, 0xb9, 0x81, 0xc0, 0xec, 0x80, 0xf4, 0x35, 0x28, 0x6c,
0x10, 0x02, 0x8b, 0xce, 0x13, 0x15, 0x52, 0x91, 0xd4, 0x17, 0x51, 0x91,
0x51, 0x92, 0x53, 0x51, 0x4f, 0xcc, 0x06, 0x01, 0xc3, 0x36, 0x04, 0x01,
0x85, 0x96, 0x22, 0x0a, 0x2d, 0x54, 0x34, 0xe0, 0xe6, 0xbe, 0x6c, 0xbe,
0x60, 0x38, 0xbc, 0x68, 0xa5, 0xf1, 0x79, 0x89, 0x9a, 0xa3, 0x93, 0x4b,
0x83, 0xfb, 0x92, 0x2b, 0x33, 0x63, 0x2b, 0x1b, 0xa3, 0x63, 0xf3, 0x12,
0x55, 0xd6, 0x26, 0x56, 0x46, 0xf6, 0x45, 0x56, 0x26, 0x56, 0x77, 0x46,
0xe1, 0x85, 0x88, 0x00, 0x85, 0x16, 0xa2, 0x0d, 0xcd, 0x56, 0x70, 0x9d,
0xf7, 0x81, 0x41, 0x18, 0x88, 0x41, 0x18, 0x60, 0x63, 0x80, 0x4d, 0x10,
0x86, 0x62, 0x82, 0x30, 0x18, 0x1b, 0x84, 0x32, 0x30, 0x83, 0x09, 0xc2,
0x70, 0x6c, 0x10, 0xca, 0x00, 0x0d, 0x28, 0xc0, 0xcd, 0x4d, 0x10, 0x06,
0x64, 0xc3, 0xa0, 0x06, 0x6b, 0x60, 0x06, 0x1b, 0x06, 0x33, 0x20, 0x88,
0x0d, 0x41, 0x1b, 0x6c, 0x18, 0xca, 0x40, 0x71, 0x83, 0x09, 0x42, 0xd2,
0x6c, 0x08, 0xe0, 0x80, 0xc9, 0x94, 0xd5, 0x17, 0x55, 0x98, 0xdc, 0x59,
0x19, 0xdd, 0x04, 0x81, 0x48, 0x26, 0x08, 0x84, 0xb2, 0x21, 0x30, 0x83,
0x09, 0x02, 0xb1, 0x4c, 0x10, 0x08, 0x66, 0x83, 0x30, 0x95, 0xc1, 0x86,
0xc5, 0x0c, 0xe4, 0x60, 0x0e, 0xe8, 0xa0, 0x0e, 0xec, 0xa0, 0x0c, 0xee,
0xc0, 0x0c, 0xec, 0x00, 0x0f, 0x36, 0x04, 0x79, 0xb0, 0x61, 0x00, 0xf4,
0x00, 0xd8, 0x50, 0x28, 0xc5, 0x1e, 0x00, 0x40, 0x17, 0x36, 0x36, 0xbb,
0x36, 0x17, 0x32, 0xb1, 0x33, 0x97, 0xb1, 0xba, 0x29, 0x01, 0xd3, 0x88,
0x8d, 0xcd, 0xae, 0xcd, 0xa5, 0xed, 0x8d, 0xac, 0x8e, 0xad, 0xcc, 0xc5,
0x8c, 0x2d, 0xec, 0x6c, 0x6e, 0x8a, 0x00, 0x4d, 0x55, 0xd8, 0xd8, 0xec,
0xda, 0x5c, 0xd2, 0xc8, 0xca, 0xdc, 0xe8, 0xa6, 0x04, 0x54, 0x25, 0x32,
0x3c, 0x97, 0xb9, 0xb7, 0x3a, 0xb9, 0xb1, 0x32, 0x97, 0xb1, 0x37, 0x37,
0xba, 0x32, 0x37, 0xba, 0xb9, 0x29, 0x81, 0xd5, 0x88, 0x0c, 0xcf, 0x65,
0xee, 0xad, 0x4e, 0x6e, 0xac, 0xcc, 0x85, 0xac, 0xcc, 0x2c, 0xcd, 0xad,
0x6c, 0x6e, 0x4a, 0x80, 0xd5, 0x22, 0xc3, 0x73, 0x99, 0x7b, 0xab, 0x93,
0x1b, 0x2b, 0x73, 0x69, 0x0b, 0x4b, 0x73, 0x33, 0x4a, 0x63, 0x2b, 0x73,
0x0a, 0x6b, 0x2b, 0x9b, 0x12, 0x64, 0x75, 0xc8, 0xf0, 0x5c, 0xe6, 0xde,
0xea, 0xe4, 0xc6, 0xca, 0x5c, 0xc2, 0xe4, 0xce, 0xe6, 0xa6, 0x04, 0x63,
0x50, 0x85, 0x0c, 0xcf, 0xc5, 0xae, 0x4c, 0x6e, 0x2e, 0xed, 0xcd, 0x6d,
0x4a, 0x60, 0x06, 0x4d, 0xc8, 0xf0, 0x5c, 0xec, 0xc2, 0xd8, 0xec, 0xca,
0xe4, 0xa6, 0x04, 0x68, 0x50, 0x87, 0x0c, 0xcf, 0x65, 0x0e, 0x2d, 0x8c,
0xac, 0x4c, 0xae, 0xe9, 0x8d, 0xac, 0x8c, 0x6d, 0x4a, 0xb0, 0x06, 0x95,
0xc8, 0xf0, 0x5c, 0xe8, 0xf2, 0xe0, 0xca, 0x82, 0xdc, 0xdc, 0xde, 0xe8,
0xc2, 0xe8, 0xd2, 0xde, 0xdc, 0xe6, 0xa6, 0x04, 0x6e, 0x50, 0x87, 0x0c,
0xcf, 0xc5, 0x2e, 0xad, 0xec, 0x2e, 0x89, 0x6c, 0x8a, 0x2e, 0x8c, 0xae,
0x6c, 0x4a, 0x00, 0x07, 0x75, 0xc8, 0xf0, 0x5c, 0xca, 0xdc, 0xe8, 0xe4,
0xf2, 0xa0, 0xde, 0xd2, 0xdc, 0xe8, 0xe6, 0xa6, 0x04, 0x7b, 0x00, 0x00,
0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x33, 0x08,
0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88, 0x43, 0x38,
0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73, 0x98, 0x71,
0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c,
0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d,
0x88, 0x43, 0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d,
0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b, 0x08, 0x07,
0x79, 0x48, 0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76, 0x78, 0x87,
0x70, 0x20, 0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30,
0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10,
0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66,
0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c,
0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07,
0x7b, 0x68, 0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37, 0x80, 0x87,
0x70, 0x90, 0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76, 0xf8, 0x05,
0x76, 0x78, 0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71, 0x18, 0x87,
0x72, 0x98, 0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0,
0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4,
0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca,
0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90, 0x43, 0x39,
0xc8, 0x43, 0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38,
0x94, 0x43, 0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c,
0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07,
0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19, 0xd1, 0x43,
0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10,
0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00,
0x00, 0x00, 0x71, 0x20, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x16, 0x50,
0x0d, 0x97, 0xef, 0x3c, 0xbe, 0x34, 0x39, 0x11, 0x81, 0x52, 0xd3, 0x43,
0x4d, 0x7e, 0x71, 0xdb, 0x06, 0x40, 0x30, 0x00, 0xd2, 0x00, 0x61, 0x20,
0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x13, 0x04, 0x41, 0x2c, 0x10, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x54, 0x23, 0x00, 0x00, 0x23, 0x06,
0x09, 0x00, 0x82, 0x60, 0x60, 0x38, 0x48, 0x92, 0x10, 0xc1, 0x8c, 0x01,
0x11, 0x70, 0x0b, 0x80, 0x13, 0x06, 0x40, 0x38, 0x10, 0x00, 0x02, 0x00,
0x00, 0x00, 0x07, 0x50, 0x10, 0xcd, 0x14, 0x61, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x4c, 0x44, 0x4e, 0x2c, 0x00,
0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x32, 0x31, 0x63, 0x31, 0x31, 0x66,
0x32, 0x30, 0x32, 0x39, 0x64, 0x38, 0x37, 0x30, 0x63, 0x30, 0x34, 0x64,
0x65, 0x64, 0x62, 0x33, 0x66, 0x65, 0x36, 0x62, 0x34, 0x36, 0x62, 0x66,
0x32, 0x37, 0x2e, 0x70, 0x64, 0x62, 0x00, 0x00, 0x00, 0x00, 0x48, 0x41,
0x53, 0x48, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0xc1,
0x1f, 0x20, 0x29, 0xd8, 0x70, 0xc0, 0x4d, 0xed, 0xb3, 0xfe, 0x6b, 0x46,
0xbf, 0x27, 0x44, 0x58, 0x49, 0x4c, 0x34, 0x04, 0x00, 0x00, 0x60, 0x00,
0x00, 0x00, 0x0d, 0x01, 0x00, 0x00, 0x44, 0x58, 0x49, 0x4c, 0x00, 0x01,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x04, 0x00, 0x00, 0x42, 0x43,
0xc0, 0xde, 0x21, 0x0c, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x0b, 0x82,
0x20, 0x00, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x07, 0x81,
0x23, 0x91, 0x41, 0xc8, 0x04, 0x49, 0x06, 0x10, 0x32, 0x39, 0x92, 0x01,
0x84, 0x0c, 0x25, 0x05, 0x08, 0x19, 0x1e, 0x04, 0x8b, 0x62, 0x80, 0x10,
0x45, 0x02, 0x42, 0x92, 0x0b, 0x42, 0x84, 0x10, 0x32, 0x14, 0x38, 0x08,
0x18, 0x4b, 0x0a, 0x32, 0x42, 0x88, 0x48, 0x90, 0x14, 0x20, 0x43, 0x46,
0x88, 0xa5, 0x00, 0x19, 0x32, 0x42, 0xe4, 0x48, 0x0e, 0x90, 0x11, 0x22,
0xc4, 0x50, 0x41, 0x51, 0x81, 0x8c, 0xe1, 0x83, 0xe5, 0x8a, 0x04, 0x21,
0x46, 0x06, 0x51, 0x18, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x1b, 0x88,
0xe0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x40, 0x02, 0x00, 0x00, 0x49, 0x18,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x13, 0x82, 0x00, 0x00, 0x89, 0x20,
0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x32, 0x22, 0x08, 0x09, 0x20, 0x64,
0x85, 0x04, 0x13, 0x22, 0xa4, 0x84, 0x04, 0x13, 0x22, 0xe3, 0x84, 0xa1,
0x90, 0x14, 0x12, 0x4c, 0x88, 0x8c, 0x0b, 0x84, 0x84, 0x4c, 0x10, 0x28,
0x23, 0x00, 0x25, 0x00, 0x8a, 0x39, 0x02, 0x30, 0x98, 0x23, 0x40, 0x66,
0x00, 0x8a, 0x01, 0x33, 0x43, 0x45, 0x36, 0x10, 0x90, 0x02, 0x03, 0x00,
0x00, 0x00, 0x13, 0x14, 0x72, 0xc0, 0x87, 0x74, 0x60, 0x87, 0x36, 0x68,
0x87, 0x79, 0x68, 0x03, 0x72, 0xc0, 0x87, 0x0d, 0xaf, 0x50, 0x0e, 0x6d,
0xd0, 0x0e, 0x7a, 0x50, 0x0e, 0x6d, 0x00, 0x0f, 0x7a, 0x30, 0x07, 0x72,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x71, 0xa0, 0x07, 0x73,
0x20, 0x07, 0x6d, 0x90, 0x0e, 0x78, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d,
0x90, 0x0e, 0x71, 0x60, 0x07, 0x7a, 0x30, 0x07, 0x72, 0xd0, 0x06, 0xe9,
0x30, 0x07, 0x72, 0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x90, 0x0e, 0x76,
0x40, 0x07, 0x7a, 0x60, 0x07, 0x74, 0xd0, 0x06, 0xe6, 0x10, 0x07, 0x76,
0xa0, 0x07, 0x73, 0x20, 0x07, 0x6d, 0x60, 0x0e, 0x73, 0x20, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xd0, 0x06, 0xe6, 0x60, 0x07, 0x74, 0xa0, 0x07, 0x76,
0x40, 0x07, 0x6d, 0xe0, 0x0e, 0x78, 0xa0, 0x07, 0x71, 0x60, 0x07, 0x7a,
0x30, 0x07, 0x72, 0xa0, 0x07, 0x76, 0x40, 0x07, 0x43, 0x9e, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x3c, 0x06,
0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x81,
0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x32, 0x1e, 0x98, 0x10, 0x19, 0x11,
0x4c, 0x90, 0x8c, 0x09, 0x26, 0x47, 0xc6, 0x04, 0x43, 0x9a, 0x12, 0x18,
0x01, 0x28, 0x85, 0x62, 0x28, 0x03, 0xa2, 0x92, 0x28, 0x90, 0x11, 0x80,
0x12, 0xa0, 0x1c, 0x4b, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x79, 0x18,
0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x1a, 0x03, 0x4c, 0x90, 0x46, 0x02,
0x13, 0x44, 0x35, 0x20, 0xc3, 0x1b, 0x43, 0x81, 0x93, 0x4b, 0xb3, 0x0b,
0xa3, 0x2b, 0x4b, 0x01, 0x89, 0x71, 0xb9, 0x71, 0x81, 0x71, 0x89, 0x99,
0xb9, 0xc1, 0xa1, 0x01, 0x41, 0x69, 0x0b, 0x4b, 0x73, 0x63, 0x01, 0x29,
0xcb, 0x99, 0x19, 0x13, 0xb3, 0x99, 0xa1, 0x99, 0x49, 0xd9, 0x10, 0x04,
0x13, 0x84, 0x41, 0x98, 0x20, 0x0c, 0xc3, 0x06, 0x61, 0x20, 0x26, 0x08,
0x03, 0xb1, 0x41, 0x18, 0x0c, 0x0a, 0x70, 0x73, 0x13, 0x84, 0xa1, 0xd8,
0x30, 0x20, 0x09, 0x31, 0x41, 0x48, 0x96, 0x0d, 0xc1, 0x32, 0x41, 0x10,
0x00, 0x12, 0x6d, 0x61, 0x69, 0x6e, 0x4c, 0xa6, 0xac, 0xbe, 0xa8, 0xc2,
0xe4, 0xce, 0xca, 0xe8, 0x26, 0x08, 0xc4, 0x31, 0x41, 0x20, 0x90, 0x0d,
0x01, 0x31, 0x41, 0x20, 0x92, 0x09, 0x02, 0xa1, 0x4c, 0x10, 0x06, 0x63,
0x83, 0x50, 0x0d, 0x1b, 0x16, 0xe2, 0x81, 0x22, 0x69, 0x1a, 0x28, 0x62,
0xb2, 0x36, 0x04, 0xd7, 0x86, 0x01, 0xc0, 0x80, 0x0d, 0x45, 0xe3, 0x64,
0x00, 0x50, 0x85, 0x8d, 0xcd, 0xae, 0xcd, 0x25, 0x8d, 0xac, 0xcc, 0x8d,
0x6e, 0x4a, 0x10, 0x54, 0x21, 0xc3, 0x73, 0xb1, 0x2b, 0x93, 0x9b, 0x4b,
0x7b, 0x73, 0x9b, 0x12, 0x10, 0x4d, 0xc8, 0xf0, 0x5c, 0xec, 0xc2, 0xd8,
0xec, 0xca, 0xe4, 0xa6, 0x04, 0x46, 0x1d, 0x32, 0x3c, 0x97, 0x39, 0xb4,
0x30, 0xb2, 0x32, 0xb9, 0xa6, 0x37, 0xb2, 0x32, 0xb6, 0x29, 0x41, 0x52,
0x87, 0x0c, 0xcf, 0xc5, 0x2e, 0xad, 0xec, 0x2e, 0x89, 0x6c, 0x8a, 0x2e,
0x8c, 0xae, 0x6c, 0x4a, 0xb0, 0xd4, 0x21, 0xc3, 0x73, 0x29, 0x73, 0xa3,
0x93, 0xcb, 0x83, 0x7a, 0x4b, 0x73, 0xa3, 0x9b, 0x9b, 0x12, 0x64, 0x00,
0x00, 0x00, 0x79, 0x18, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x33, 0x08,
0x80, 0x1c, 0xc4, 0xe1, 0x1c, 0x66, 0x14, 0x01, 0x3d, 0x88, 0x43, 0x38,
0x84, 0xc3, 0x8c, 0x42, 0x80, 0x07, 0x79, 0x78, 0x07, 0x73, 0x98, 0x71,
0x0c, 0xe6, 0x00, 0x0f, 0xed, 0x10, 0x0e, 0xf4, 0x80, 0x0e, 0x33, 0x0c,
0x42, 0x1e, 0xc2, 0xc1, 0x1d, 0xce, 0xa1, 0x1c, 0x66, 0x30, 0x05, 0x3d,
0x88, 0x43, 0x38, 0x84, 0x83, 0x1b, 0xcc, 0x03, 0x3d, 0xc8, 0x43, 0x3d,
0x8c, 0x03, 0x3d, 0xcc, 0x78, 0x8c, 0x74, 0x70, 0x07, 0x7b, 0x08, 0x07,
0x79, 0x48, 0x87, 0x70, 0x70, 0x07, 0x7a, 0x70, 0x03, 0x76, 0x78, 0x87,
0x70, 0x20, 0x87, 0x19, 0xcc, 0x11, 0x0e, 0xec, 0x90, 0x0e, 0xe1, 0x30,
0x0f, 0x6e, 0x30, 0x0f, 0xe3, 0xf0, 0x0e, 0xf0, 0x50, 0x0e, 0x33, 0x10,
0xc4, 0x1d, 0xde, 0x21, 0x1c, 0xd8, 0x21, 0x1d, 0xc2, 0x61, 0x1e, 0x66,
0x30, 0x89, 0x3b, 0xbc, 0x83, 0x3b, 0xd0, 0x43, 0x39, 0xb4, 0x03, 0x3c,
0xbc, 0x83, 0x3c, 0x84, 0x03, 0x3b, 0xcc, 0xf0, 0x14, 0x76, 0x60, 0x07,
0x7b, 0x68, 0x07, 0x37, 0x68, 0x87, 0x72, 0x68, 0x07, 0x37, 0x80, 0x87,
0x70, 0x90, 0x87, 0x70, 0x60, 0x07, 0x76, 0x28, 0x07, 0x76, 0xf8, 0x05,
0x76, 0x78, 0x87, 0x77, 0x80, 0x87, 0x5f, 0x08, 0x87, 0x71, 0x18, 0x87,
0x72, 0x98, 0x87, 0x79, 0x98, 0x81, 0x2c, 0xee, 0xf0, 0x0e, 0xee, 0xe0,
0x0e, 0xf5, 0xc0, 0x0e, 0xec, 0x30, 0x03, 0x62, 0xc8, 0xa1, 0x1c, 0xe4,
0xa1, 0x1c, 0xcc, 0xa1, 0x1c, 0xe4, 0xa1, 0x1c, 0xdc, 0x61, 0x1c, 0xca,
0x21, 0x1c, 0xc4, 0x81, 0x1d, 0xca, 0x61, 0x06, 0xd6, 0x90, 0x43, 0x39,
0xc8, 0x43, 0x39, 0x98, 0x43, 0x39, 0xc8, 0x43, 0x39, 0xb8, 0xc3, 0x38,
0x94, 0x43, 0x38, 0x88, 0x03, 0x3b, 0x94, 0xc3, 0x2f, 0xbc, 0x83, 0x3c,
0xfc, 0x82, 0x3b, 0xd4, 0x03, 0x3b, 0xb0, 0xc3, 0x0c, 0xc4, 0x21, 0x07,
0x7c, 0x70, 0x03, 0x7a, 0x28, 0x87, 0x76, 0x80, 0x87, 0x19, 0xd1, 0x43,
0x0e, 0xf8, 0xe0, 0x06, 0xe4, 0x20, 0x0e, 0xe7, 0xe0, 0x06, 0xf6, 0x10,
0x0e, 0xf2, 0xc0, 0x0e, 0xe1, 0x90, 0x0f, 0xef, 0x50, 0x0f, 0xf4, 0x00,
0x00, 0x00, 0x71, 0x20, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x16, 0x50,
0x0d, 0x97, 0xef, 0x3c, 0xbe, 0x34, 0x39, 0x11, 0x81, 0x52, 0xd3, 0x43,
0x4d, 0x7e, 0x71, 0xdb, 0x06, 0x40, 0x30, 0x00, 0xd2, 0x00, 0x61, 0x20,
0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x13, 0x04, 0x41, 0x2c, 0x10, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x54, 0x23, 0x00, 0x00, 0x23, 0x06,
0x09, 0x00, 0x82, 0x60, 0x60, 0x30, 0x89, 0xa2, 0x10, 0x01, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RefactoringTest.cpp
|
//===- unittest/Tooling/RefactoringTest.cpp - Refactoring unit tests ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "RewriterTestContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Path.h"
#include "gtest/gtest.h"
namespace clang {
namespace tooling {
class ReplacementTest : public ::testing::Test {
protected:
Replacement createReplacement(SourceLocation Start, unsigned Length,
llvm::StringRef ReplacementText) {
return Replacement(Context.Sources, Start, Length, ReplacementText);
}
RewriterTestContext Context;
};
TEST_F(ReplacementTest, CanDeleteAllText) {
FileID ID = Context.createInMemoryFile("input.cpp", "text");
SourceLocation Location = Context.getLocation(ID, 1, 1);
Replacement Replace(createReplacement(Location, 4, ""));
EXPECT_TRUE(Replace.apply(Context.Rewrite));
EXPECT_EQ("", Context.getRewrittenText(ID));
}
TEST_F(ReplacementTest, CanDeleteAllTextInTextWithNewlines) {
FileID ID = Context.createInMemoryFile("input.cpp", "line1\nline2\nline3");
SourceLocation Location = Context.getLocation(ID, 1, 1);
Replacement Replace(createReplacement(Location, 17, ""));
EXPECT_TRUE(Replace.apply(Context.Rewrite));
EXPECT_EQ("", Context.getRewrittenText(ID));
}
TEST_F(ReplacementTest, CanAddText) {
FileID ID = Context.createInMemoryFile("input.cpp", "");
SourceLocation Location = Context.getLocation(ID, 1, 1);
Replacement Replace(createReplacement(Location, 0, "result"));
EXPECT_TRUE(Replace.apply(Context.Rewrite));
EXPECT_EQ("result", Context.getRewrittenText(ID));
}
TEST_F(ReplacementTest, CanReplaceTextAtPosition) {
FileID ID = Context.createInMemoryFile("input.cpp",
"line1\nline2\nline3\nline4");
SourceLocation Location = Context.getLocation(ID, 2, 3);
Replacement Replace(createReplacement(Location, 12, "x"));
EXPECT_TRUE(Replace.apply(Context.Rewrite));
EXPECT_EQ("line1\nlixne4", Context.getRewrittenText(ID));
}
TEST_F(ReplacementTest, CanReplaceTextAtPositionMultipleTimes) {
FileID ID = Context.createInMemoryFile("input.cpp",
"line1\nline2\nline3\nline4");
SourceLocation Location1 = Context.getLocation(ID, 2, 3);
Replacement Replace1(createReplacement(Location1, 12, "x\ny\n"));
EXPECT_TRUE(Replace1.apply(Context.Rewrite));
EXPECT_EQ("line1\nlix\ny\nne4", Context.getRewrittenText(ID));
// Since the original source has not been modified, the (4, 4) points to the
// 'e' in the original content.
SourceLocation Location2 = Context.getLocation(ID, 4, 4);
Replacement Replace2(createReplacement(Location2, 1, "f"));
EXPECT_TRUE(Replace2.apply(Context.Rewrite));
EXPECT_EQ("line1\nlix\ny\nnf4", Context.getRewrittenText(ID));
}
TEST_F(ReplacementTest, ApplyFailsForNonExistentLocation) {
Replacement Replace("nonexistent-file.cpp", 0, 1, "");
EXPECT_FALSE(Replace.apply(Context.Rewrite));
}
TEST_F(ReplacementTest, CanRetrivePath) {
Replacement Replace("/path/to/file.cpp", 0, 1, "");
EXPECT_EQ("/path/to/file.cpp", Replace.getFilePath());
}
TEST_F(ReplacementTest, ReturnsInvalidPath) {
Replacement Replace1(Context.Sources, SourceLocation(), 0, "");
EXPECT_TRUE(Replace1.getFilePath().empty());
Replacement Replace2;
EXPECT_TRUE(Replace2.getFilePath().empty());
}
TEST_F(ReplacementTest, CanApplyReplacements) {
FileID ID = Context.createInMemoryFile("input.cpp",
"line1\nline2\nline3\nline4");
Replacements Replaces;
Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
5, "replaced"));
Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 3, 1),
5, "other"));
EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
}
// FIXME: Remove this test case when Replacements is implemented as std::vector
// instead of std::set. The other ReplacementTest tests will need to be updated
// at that point as well.
TEST_F(ReplacementTest, VectorCanApplyReplacements) {
FileID ID = Context.createInMemoryFile("input.cpp",
"line1\nline2\nline3\nline4");
std::vector<Replacement> Replaces;
Replaces.push_back(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
5, "replaced"));
Replaces.push_back(
Replacement(Context.Sources, Context.getLocation(ID, 3, 1), 5, "other"));
EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
}
TEST_F(ReplacementTest, SkipsDuplicateReplacements) {
FileID ID = Context.createInMemoryFile("input.cpp",
"line1\nline2\nline3\nline4");
Replacements Replaces;
Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
5, "replaced"));
Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
5, "replaced"));
Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
5, "replaced"));
EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
}
TEST_F(ReplacementTest, ApplyAllFailsIfOneApplyFails) {
// This test depends on the value of the file name of an invalid source
// location being in the range ]a, z[.
FileID IDa = Context.createInMemoryFile("a.cpp", "text");
FileID IDz = Context.createInMemoryFile("z.cpp", "text");
Replacements Replaces;
Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDa, 1, 1),
4, "a"));
Replaces.insert(Replacement(Context.Sources, SourceLocation(),
5, "2"));
Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDz, 1, 1),
4, "z"));
EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
EXPECT_EQ("a", Context.getRewrittenText(IDa));
EXPECT_EQ("z", Context.getRewrittenText(IDz));
}
TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
Replacements Replaces;
Replaces.insert(Replacement("", 0, 1, ""));
Replaces.insert(Replacement("", 4, 3, " "));
// Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int i;
EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); // |nt i;
EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); // i|t i;
EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); // in| i;
EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); // int| i;
EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); // int | i;
EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); // int |i;
EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); // int |;
EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); // int i|
}
// FIXME: Remove this test case when Replacements is implemented as std::vector
// instead of std::set. The other ReplacementTest tests will need to be updated
// at that point as well.
TEST(ShiftedCodePositionTest, VectorFindsNewCodePositionWithInserts) {
std::vector<Replacement> Replaces;
Replaces.push_back(Replacement("", 0, 1, ""));
Replaces.push_back(Replacement("", 4, 3, " "));
// Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int i;
EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); // |nt i;
EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); // i|t i;
EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); // in| i;
EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); // int| i;
EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); // int | i;
EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); // int |i;
EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); // int |;
EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); // int i|
}
TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
Replacements Replaces;
Replaces.insert(Replacement("", 4, 0, "\"\n\""));
// Assume '"12345678"' is turned into '"1234"\n"5678"'.
EXPECT_EQ(4u, shiftedCodePosition(Replaces, 4)); // "123|5678"
EXPECT_EQ(8u, shiftedCodePosition(Replaces, 5)); // "1234|678"
}
class FlushRewrittenFilesTest : public ::testing::Test {
public:
FlushRewrittenFilesTest() {}
~FlushRewrittenFilesTest() override {
for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
E = TemporaryFiles.end();
I != E; ++I) {
llvm::StringRef Name = I->second;
std::error_code EC = llvm::sys::fs::remove(Name);
(void)EC;
assert(!EC);
}
}
FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
SmallString<1024> Path;
int FD;
std::error_code EC = llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
assert(!EC);
(void)EC;
llvm::raw_fd_ostream OutStream(FD, true);
OutStream << Content;
OutStream.close();
const FileEntry *File = Context.Files.getFile(Path);
assert(File != nullptr);
StringRef Found =
TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
assert(Found == Path);
(void)Found;
return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
}
std::string getFileContentFromDisk(llvm::StringRef Name) {
std::string Path = TemporaryFiles.lookup(Name);
assert(!Path.empty());
// We need to read directly from the FileManager without relaying through
// a FileEntry, as otherwise we'd read through an already opened file
// descriptor, which might not see the changes made.
// FIXME: Figure out whether there is a way to get the SourceManger to
// reopen the file.
auto FileBuffer = Context.Files.getBufferForFile(Path);
return (*FileBuffer)->getBuffer();
}
llvm::StringMap<std::string> TemporaryFiles;
RewriterTestContext Context;
};
TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
Replacements Replaces;
Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
5, "replaced"));
EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
EXPECT_EQ("line1\nreplaced\nline3\nline4",
getFileContentFromDisk("input.cpp"));
}
namespace {
template <typename T>
class TestVisitor : public clang::RecursiveASTVisitor<T> {
public:
bool runOver(StringRef Code) {
return runToolOnCode(new TestAction(this), Code);
}
protected:
clang::SourceManager *SM;
clang::ASTContext *Context;
private:
class FindConsumer : public clang::ASTConsumer {
public:
FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
void HandleTranslationUnit(clang::ASTContext &Context) override {
Visitor->TraverseDecl(Context.getTranslationUnitDecl());
}
private:
TestVisitor *Visitor;
};
class TestAction : public clang::ASTFrontendAction {
public:
TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &compiler,
llvm::StringRef dummy) override {
Visitor->SM = &compiler.getSourceManager();
Visitor->Context = &compiler.getASTContext();
/// TestConsumer will be deleted by the framework calling us.
return llvm::make_unique<FindConsumer>(Visitor);
}
private:
TestVisitor *Visitor;
};
};
} // end namespace
void expectReplacementAt(const Replacement &Replace,
StringRef File, unsigned Offset, unsigned Length) {
ASSERT_TRUE(Replace.isApplicable());
EXPECT_EQ(File, Replace.getFilePath());
EXPECT_EQ(Offset, Replace.getOffset());
EXPECT_EQ(Length, Replace.getLength());
}
class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
public:
bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
if (Record->getName() == "X") {
Replace = Replacement(*SM, Record, "");
}
return true;
}
Replacement Replace;
};
TEST(Replacement, CanBeConstructedFromNode) {
ClassDeclXVisitor ClassDeclX;
EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
}
TEST(Replacement, ReplacesAtSpellingLocation) {
ClassDeclXVisitor ClassDeclX;
EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
}
class CallToFVisitor : public TestVisitor<CallToFVisitor> {
public:
bool VisitCallExpr(CallExpr *Call) {
if (Call->getDirectCallee()->getName() == "F") {
Replace = Replacement(*SM, Call, "");
}
return true;
}
Replacement Replace;
};
TEST(Replacement, FunctionCall) {
CallToFVisitor CallToF;
EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
}
TEST(Replacement, TemplatedFunctionCall) {
CallToFVisitor CallToF;
EXPECT_TRUE(CallToF.runOver(
"template <typename T> void F(); void G() { F<int>(); }"));
expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
}
class NestedNameSpecifierAVisitor
: public TestVisitor<NestedNameSpecifierAVisitor> {
public:
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLoc) {
if (NNSLoc.getNestedNameSpecifier()) {
if (const NamespaceDecl* NS = NNSLoc.getNestedNameSpecifier()->getAsNamespace()) {
if (NS->getName() == "a") {
Replace = Replacement(*SM, &NNSLoc, "", Context->getLangOpts());
}
}
}
return TestVisitor<NestedNameSpecifierAVisitor>::TraverseNestedNameSpecifierLoc(
NNSLoc);
}
Replacement Replace;
};
TEST(Replacement, ColonColon) {
NestedNameSpecifierAVisitor VisitNNSA;
EXPECT_TRUE(VisitNNSA.runOver("namespace a { void f() { ::a::f(); } }"));
expectReplacementAt(VisitNNSA.Replace, "input.cc", 25, 5);
}
TEST(Range, overlaps) {
EXPECT_TRUE(Range(10, 10).overlapsWith(Range(0, 11)));
EXPECT_TRUE(Range(0, 11).overlapsWith(Range(10, 10)));
EXPECT_FALSE(Range(10, 10).overlapsWith(Range(0, 10)));
EXPECT_FALSE(Range(0, 10).overlapsWith(Range(10, 10)));
EXPECT_TRUE(Range(0, 10).overlapsWith(Range(2, 6)));
EXPECT_TRUE(Range(2, 6).overlapsWith(Range(0, 10)));
}
TEST(Range, contains) {
EXPECT_TRUE(Range(0, 10).contains(Range(0, 10)));
EXPECT_TRUE(Range(0, 10).contains(Range(2, 6)));
EXPECT_FALSE(Range(2, 6).contains(Range(0, 10)));
EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
}
TEST(DeduplicateTest, removesDuplicates) {
std::vector<Replacement> Input;
Input.push_back(Replacement("fileA", 50, 0, " foo "));
Input.push_back(Replacement("fileA", 10, 3, " bar "));
Input.push_back(Replacement("fileA", 10, 2, " bar ")); // Length differs
Input.push_back(Replacement("fileA", 9, 3, " bar ")); // Offset differs
Input.push_back(Replacement("fileA", 50, 0, " foo ")); // Duplicate
Input.push_back(Replacement("fileA", 51, 3, " bar "));
Input.push_back(Replacement("fileB", 51, 3, " bar ")); // Filename differs!
Input.push_back(Replacement("fileB", 60, 1, " bar "));
Input.push_back(Replacement("fileA", 60, 2, " bar "));
Input.push_back(Replacement("fileA", 51, 3, " moo ")); // Replacement text
// differs!
std::vector<Replacement> Expected;
Expected.push_back(Replacement("fileA", 9, 3, " bar "));
Expected.push_back(Replacement("fileA", 10, 2, " bar "));
Expected.push_back(Replacement("fileA", 10, 3, " bar "));
Expected.push_back(Replacement("fileA", 50, 0, " foo "));
Expected.push_back(Replacement("fileA", 51, 3, " bar "));
Expected.push_back(Replacement("fileA", 51, 3, " moo "));
Expected.push_back(Replacement("fileB", 60, 1, " bar "));
Expected.push_back(Replacement("fileA", 60, 2, " bar "));
std::vector<Range> Conflicts; // Ignored for this test
deduplicate(Input, Conflicts);
EXPECT_EQ(3U, Conflicts.size());
EXPECT_EQ(Expected, Input);
}
TEST(DeduplicateTest, detectsConflicts) {
{
std::vector<Replacement> Input;
Input.push_back(Replacement("fileA", 0, 5, " foo "));
Input.push_back(Replacement("fileA", 0, 5, " foo ")); // Duplicate not a
// conflict.
Input.push_back(Replacement("fileA", 2, 6, " bar "));
Input.push_back(Replacement("fileA", 7, 3, " moo "));
std::vector<Range> Conflicts;
deduplicate(Input, Conflicts);
// One duplicate is removed and the remaining three items form one
// conflicted range.
ASSERT_EQ(3u, Input.size());
ASSERT_EQ(1u, Conflicts.size());
ASSERT_EQ(0u, Conflicts.front().getOffset());
ASSERT_EQ(3u, Conflicts.front().getLength());
}
{
std::vector<Replacement> Input;
// Expected sorted order is shown. It is the sorted order to which the
// returned conflict info refers to.
Input.push_back(Replacement("fileA", 0, 5, " foo ")); // 0
Input.push_back(Replacement("fileA", 5, 5, " bar ")); // 1
Input.push_back(Replacement("fileA", 6, 0, " bar ")); // 3
Input.push_back(Replacement("fileA", 5, 5, " moo ")); // 2
Input.push_back(Replacement("fileA", 7, 2, " bar ")); // 4
Input.push_back(Replacement("fileA", 15, 5, " golf ")); // 5
Input.push_back(Replacement("fileA", 16, 5, " bag ")); // 6
Input.push_back(Replacement("fileA", 10, 3, " club ")); // 7
// #3 is special in that it is completely contained by another conflicting
// Replacement. #4 ensures #3 hasn't messed up the conflicting range size.
std::vector<Range> Conflicts;
deduplicate(Input, Conflicts);
// No duplicates
ASSERT_EQ(8u, Input.size());
ASSERT_EQ(2u, Conflicts.size());
ASSERT_EQ(1u, Conflicts[0].getOffset());
ASSERT_EQ(4u, Conflicts[0].getLength());
ASSERT_EQ(6u, Conflicts[1].getOffset());
ASSERT_EQ(2u, Conflicts[1].getLength());
}
}
} // end namespace tooling
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/CommentHandlerTest.cpp
|
//===- unittest/Tooling/CommentHandlerTest.cpp -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "TestVisitor.h"
#include "clang/Lex/Preprocessor.h"
namespace clang {
struct Comment {
Comment(const std::string &Message, unsigned Line, unsigned Col)
: Message(Message), Line(Line), Col(Col) { }
std::string Message;
unsigned Line, Col;
};
class CommentVerifier;
typedef std::vector<Comment> CommentList;
class CommentHandlerVisitor : public TestVisitor<CommentHandlerVisitor>,
public CommentHandler {
typedef TestVisitor<CommentHandlerVisitor> base;
public:
CommentHandlerVisitor() : base(), PP(nullptr), Verified(false) {}
~CommentHandlerVisitor() override {
EXPECT_TRUE(Verified) << "CommentVerifier not accessed";
}
bool HandleComment(Preprocessor &PP, SourceRange Loc) override {
assert(&PP == this->PP && "Preprocessor changed!");
SourceLocation Start = Loc.getBegin();
SourceManager &SM = PP.getSourceManager();
std::string C(SM.getCharacterData(Start),
SM.getCharacterData(Loc.getEnd()));
bool Invalid;
unsigned CLine = SM.getSpellingLineNumber(Start, &Invalid);
EXPECT_TRUE(!Invalid) << "Invalid line number on comment " << C;
unsigned CCol = SM.getSpellingColumnNumber(Start, &Invalid);
EXPECT_TRUE(!Invalid) << "Invalid column number on comment " << C;
Comments.push_back(Comment(C, CLine, CCol));
return false;
}
CommentVerifier GetVerifier();
protected:
ASTFrontendAction *CreateTestAction() override {
return new CommentHandlerAction(this);
}
private:
Preprocessor *PP;
CommentList Comments;
bool Verified;
class CommentHandlerAction : public base::TestAction {
public:
CommentHandlerAction(CommentHandlerVisitor *Visitor)
: TestAction(Visitor) { }
bool BeginSourceFileAction(CompilerInstance &CI,
StringRef FileName) override {
CommentHandlerVisitor *V =
static_cast<CommentHandlerVisitor*>(this->Visitor);
V->PP = &CI.getPreprocessor();
V->PP->addCommentHandler(V);
return true;
}
void EndSourceFileAction() override {
CommentHandlerVisitor *V =
static_cast<CommentHandlerVisitor*>(this->Visitor);
V->PP->removeCommentHandler(V);
}
};
};
class CommentVerifier {
CommentList::const_iterator Current;
CommentList::const_iterator End;
Preprocessor *PP;
public:
CommentVerifier(const CommentList &Comments, Preprocessor *PP)
: Current(Comments.begin()), End(Comments.end()), PP(PP)
{ }
~CommentVerifier() {
if (Current != End) {
EXPECT_TRUE(Current == End) << "Unexpected comment \""
<< Current->Message << "\" at line " << Current->Line << ", column "
<< Current->Col;
}
}
void Match(const char *Message, unsigned Line, unsigned Col) {
EXPECT_TRUE(Current != End) << "Comment " << Message << " not found";
if (Current == End) return;
const Comment &C = *Current;
EXPECT_TRUE(C.Message == Message && C.Line == Line && C.Col == Col)
<< "Expected comment \"" << Message
<< "\" at line " << Line << ", column " << Col
<< "\nActual comment \"" << C.Message
<< "\" at line " << C.Line << ", column " << C.Col;
++Current;
}
};
CommentVerifier CommentHandlerVisitor::GetVerifier() {
Verified = true;
return CommentVerifier(Comments, PP);
}
TEST(CommentHandlerTest, BasicTest1) {
CommentHandlerVisitor Visitor;
EXPECT_TRUE(Visitor.runOver("class X {}; int main() { return 0; }"));
CommentVerifier Verifier = Visitor.GetVerifier();
}
TEST(CommentHandlerTest, BasicTest2) {
CommentHandlerVisitor Visitor;
EXPECT_TRUE(Visitor.runOver(
"class X {}; int main() { /* comment */ return 0; }"));
CommentVerifier Verifier = Visitor.GetVerifier();
Verifier.Match("/* comment */", 1, 26);
}
TEST(CommentHandlerTest, BasicTest3) {
CommentHandlerVisitor Visitor;
EXPECT_TRUE(Visitor.runOver(
"class X {}; // comment 1\n"
"int main() {\n"
" // comment 2\n"
" return 0;\n"
"}"));
CommentVerifier Verifier = Visitor.GetVerifier();
Verifier.Match("// comment 1", 1, 13);
Verifier.Match("// comment 2", 3, 3);
}
TEST(CommentHandlerTest, IfBlock1) {
CommentHandlerVisitor Visitor;
EXPECT_TRUE(Visitor.runOver(
"#if 0\n"
"// ignored comment\n"
"#endif\n"
"// visible comment\n"));
CommentVerifier Verifier = Visitor.GetVerifier();
Verifier.Match("// visible comment", 4, 1);
}
TEST(CommentHandlerTest, IfBlock2) {
CommentHandlerVisitor Visitor;
EXPECT_TRUE(Visitor.runOver(
"#define TEST // visible_1\n"
"#ifndef TEST // visible_2\n"
" // ignored_3\n"
"# ifdef UNDEFINED // ignored_4\n"
"# endif // ignored_5\n"
"#elif defined(TEST) // visible_6\n"
"# if 1 // visible_7\n"
" // visible_8\n"
"# else // visible_9\n"
" // ignored_10\n"
"# ifndef TEST // ignored_11\n"
"# endif // ignored_12\n"
"# endif // visible_13\n"
"#endif // visible_14\n"));
CommentVerifier Verifier = Visitor.GetVerifier();
Verifier.Match("// visible_1", 1, 21);
Verifier.Match("// visible_2", 2, 21);
Verifier.Match("// visible_6", 6, 21);
Verifier.Match("// visible_7", 7, 21);
Verifier.Match("// visible_8", 8, 21);
Verifier.Match("// visible_9", 9, 21);
Verifier.Match("// visible_13", 13, 21);
Verifier.Match("// visible_14", 14, 21);
}
TEST(CommentHandlerTest, IfBlock3) {
const char *Source =
"/* commented out ...\n"
"#if 0\n"
"// enclosed\n"
"#endif */";
CommentHandlerVisitor Visitor;
EXPECT_TRUE(Visitor.runOver(Source));
CommentVerifier Verifier = Visitor.GetVerifier();
Verifier.Match(Source, 1, 1);
}
TEST(CommentHandlerTest, PPDirectives) {
CommentHandlerVisitor Visitor;
EXPECT_TRUE(Visitor.runOver(
"#warning Y // ignored_1\n" // #warning takes whole line as message
"#undef MACRO // visible_2\n"
"#line 1 // visible_3\n"));
CommentVerifier Verifier = Visitor.GetVerifier();
Verifier.Match("// visible_2", 2, 14);
Verifier.Match("// visible_3", 3, 14);
}
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RecursiveASTVisitorTestCallVisitor.cpp
|
//===- unittest/Tooling/RecursiveASTVisitorTestCallVisitor.cpp ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "TestVisitor.h"
#include <stack>
using namespace clang;
namespace {
class CXXMemberCallVisitor
: public ExpectedLocationVisitor<CXXMemberCallVisitor> {
public:
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *Call) {
Match(Call->getMethodDecl()->getQualifiedNameAsString(),
Call->getLocStart());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsCallInTemplateInstantiation) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("Y::x", 3, 3);
EXPECT_TRUE(Visitor.runOver(
"struct Y { void x(); };\n"
"template<typename T> void y(T t) {\n"
" t.x();\n"
"}\n"
"void foo() { y<Y>(Y()); }"));
}
TEST(RecursiveASTVisitor, VisitsCallInNestedFunctionTemplateInstantiation) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("Y::x", 4, 5);
EXPECT_TRUE(Visitor.runOver(
"struct Y { void x(); };\n"
"template<typename T> struct Z {\n"
" template<typename U> static void f() {\n"
" T().x();\n"
" }\n"
"};\n"
"void foo() { Z<Y>::f<int>(); }"));
}
TEST(RecursiveASTVisitor, VisitsCallInNestedClassTemplateInstantiation) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("A::x", 5, 7);
EXPECT_TRUE(Visitor.runOver(
"template <typename T1> struct X {\n"
" template <typename T2> struct Y {\n"
" void f() {\n"
" T2 y;\n"
" y.x();\n"
" }\n"
" };\n"
"};\n"
"struct A { void x(); };\n"
"int main() {\n"
" (new X<A>::Y<A>())->f();\n"
"}"));
}
TEST(RecursiveASTVisitor, VisitsCallInPartialTemplateSpecialization) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("A::x", 6, 20);
EXPECT_TRUE(Visitor.runOver(
"template <typename T1> struct X {\n"
" template <typename T2, bool B> struct Y { void g(); };\n"
"};\n"
"template <typename T1> template <typename T2>\n"
"struct X<T1>::Y<T2, true> {\n"
" void f() { T2 y; y.x(); }\n"
"};\n"
"struct A { void x(); };\n"
"int main() {\n"
" (new X<A>::Y<A, true>())->f();\n"
"}\n"));
}
TEST(RecursiveASTVisitor, VisitsExplicitTemplateSpecialization) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("A::f", 4, 5);
EXPECT_TRUE(Visitor.runOver(
"struct A {\n"
" void f() const {}\n"
" template<class T> void g(const T& t) const {\n"
" t.f();\n"
" }\n"
"};\n"
"template void A::g(const A& a) const;\n"));
}
class CXXOperatorCallExprTraverser
: public ExpectedLocationVisitor<CXXOperatorCallExprTraverser> {
public:
// Use Traverse, not Visit, to check that data recursion optimization isn't
// bypassing the call of this function.
bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
Match(getOperatorSpelling(CE->getOperator()), CE->getExprLoc());
return ExpectedLocationVisitor<CXXOperatorCallExprTraverser>::
TraverseCXXOperatorCallExpr(CE);
}
};
TEST(RecursiveASTVisitor, TraversesOverloadedOperator) {
CXXOperatorCallExprTraverser Visitor;
Visitor.ExpectMatch("()", 4, 9);
EXPECT_TRUE(Visitor.runOver(
"struct A {\n"
" int operator()();\n"
"} a;\n"
"int k = a();\n"));
}
} // end anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RewriterTest.cpp
|
//===- unittest/Tooling/RewriterTest.cpp ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "RewriterTestContext.h"
#include "clang/Tooling/Core/Replacement.h"
#include "gtest/gtest.h"
namespace clang {
namespace tooling {
namespace {
TEST(Rewriter, OverwritesChangedFiles) {
RewriterTestContext Context;
FileID ID = Context.createOnDiskFile("t.cpp", "line1\nline2\nline3\nline4");
Context.Rewrite.ReplaceText(Context.getLocation(ID, 2, 1), 5, "replaced");
EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
EXPECT_EQ("line1\nreplaced\nline3\nline4",
Context.getFileContentFromDisk("t.cpp"));
}
TEST(Rewriter, ContinuesOverwritingFilesOnError) {
RewriterTestContext Context;
FileID FailingID = Context.createInMemoryFile("invalid/failing.cpp", "test");
Context.Rewrite.ReplaceText(Context.getLocation(FailingID, 1, 2), 1, "other");
FileID WorkingID = Context.createOnDiskFile(
"working.cpp", "line1\nline2\nline3\nline4");
Context.Rewrite.ReplaceText(Context.getLocation(WorkingID, 2, 1), 5,
"replaced");
EXPECT_TRUE(Context.Rewrite.overwriteChangedFiles());
EXPECT_EQ("line1\nreplaced\nline3\nline4",
Context.getFileContentFromDisk("working.cpp"));
}
TEST(Rewriter, AdjacentInsertAndDelete) {
Replacements Replaces;
Replaces.insert(Replacement("<file>", 6, 6, ""));
Replaces.insert(Replacement("<file>", 6, 0, "replaced\n"));
EXPECT_EQ("line1\nreplaced\nline3\nline4",
applyAllReplacements("line1\nline2\nline3\nline4", Replaces));
}
} // end namespace
} // end namespace tooling
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/CMakeLists.txt
|
set(LLVM_LINK_COMPONENTS
Support
)
add_clang_unittest(ToolingTests
CommentHandlerTest.cpp
CompilationDatabaseTest.cpp
ToolingTest.cpp
RecursiveASTVisitorTest.cpp
RecursiveASTVisitorTestCallVisitor.cpp
RecursiveASTVisitorTestDeclVisitor.cpp
RecursiveASTVisitorTestExprVisitor.cpp
RecursiveASTVisitorTestTypeLocVisitor.cpp
RefactoringTest.cpp
RewriterTest.cpp
RefactoringCallbacksTest.cpp
ReplacementsYamlTest.cpp
)
target_link_libraries(ToolingTests
clangAST
clangASTMatchers
clangBasic
clangFrontend
clangLex
clangRewrite
clangTooling
clangToolingCore
)
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/TestVisitor.h
|
//===--- TestVisitor.h ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines utility templates for RecursiveASTVisitor related tests.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_UNITTESTS_TOOLING_TESTVISITOR_H
#define LLVM_CLANG_UNITTESTS_TOOLING_TESTVISITOR_H
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
#include <vector>
namespace clang {
/// \brief Base class for simple RecursiveASTVisitor based tests.
///
/// This is a drop-in replacement for RecursiveASTVisitor itself, with the
/// additional capability of running it over a snippet of code.
///
/// Visits template instantiations and implicit code by default.
template <typename T>
class TestVisitor : public RecursiveASTVisitor<T> {
public:
TestVisitor() { }
virtual ~TestVisitor() { }
enum Language {
Lang_C,
Lang_CXX98,
Lang_CXX11,
Lang_OBJC,
Lang_OBJCXX11,
Lang_CXX = Lang_CXX98
};
/// \brief Runs the current AST visitor over the given code.
bool runOver(StringRef Code, Language L = Lang_CXX) {
std::vector<std::string> Args;
switch (L) {
case Lang_C: Args.push_back("-std=c99"); break;
case Lang_CXX98: Args.push_back("-std=c++98"); break;
case Lang_CXX11: Args.push_back("-std=c++11"); break;
case Lang_OBJC: Args.push_back("-ObjC"); break;
case Lang_OBJCXX11:
Args.push_back("-ObjC++");
Args.push_back("-std=c++11");
Args.push_back("-fblocks");
break;
}
return tooling::runToolOnCodeWithArgs(CreateTestAction(), Code, Args);
}
bool shouldVisitTemplateInstantiations() const {
return true;
}
bool shouldVisitImplicitCode() const {
return true;
}
protected:
virtual ASTFrontendAction* CreateTestAction() {
return new TestAction(this);
}
class FindConsumer : public ASTConsumer {
public:
FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
void HandleTranslationUnit(clang::ASTContext &Context) override {
Visitor->Context = &Context;
Visitor->TraverseDecl(Context.getTranslationUnitDecl());
}
private:
TestVisitor *Visitor;
};
class TestAction : public ASTFrontendAction {
public:
TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(CompilerInstance &, llvm::StringRef dummy) override {
/// TestConsumer will be deleted by the framework calling us.
return llvm::make_unique<FindConsumer>(Visitor);
}
protected:
TestVisitor *Visitor;
};
ASTContext *Context;
};
/// \brief A RecursiveASTVisitor to check that certain matches are (or are
/// not) observed during visitation.
///
/// This is a RecursiveASTVisitor for testing the RecursiveASTVisitor itself,
/// and allows simple creation of test visitors running matches on only a small
/// subset of the Visit* methods.
template <typename T, template <typename> class Visitor = TestVisitor>
class ExpectedLocationVisitor : public Visitor<T> {
public:
/// \brief Expect 'Match' *not* to occur at the given 'Line' and 'Column'.
///
/// Any number of matches can be disallowed.
void DisallowMatch(Twine Match, unsigned Line, unsigned Column) {
DisallowedMatches.push_back(MatchCandidate(Match, Line, Column));
}
/// \brief Expect 'Match' to occur at the given 'Line' and 'Column'.
///
/// Any number of expected matches can be set by calling this repeatedly.
/// Each is expected to be matched exactly once.
void ExpectMatch(Twine Match, unsigned Line, unsigned Column) {
ExpectedMatches.push_back(ExpectedMatch(Match, Line, Column));
}
/// \brief Checks that all expected matches have been found.
~ExpectedLocationVisitor() override {
for (typename std::vector<ExpectedMatch>::const_iterator
It = ExpectedMatches.begin(), End = ExpectedMatches.end();
It != End; ++It) {
It->ExpectFound();
}
}
protected:
/// \brief Checks an actual match against expected and disallowed matches.
///
/// Implementations are required to call this with appropriate values
/// for 'Name' during visitation.
void Match(StringRef Name, SourceLocation Location) {
const FullSourceLoc FullLocation = this->Context->getFullLoc(Location);
for (typename std::vector<MatchCandidate>::const_iterator
It = DisallowedMatches.begin(), End = DisallowedMatches.end();
It != End; ++It) {
EXPECT_FALSE(It->Matches(Name, FullLocation))
<< "Matched disallowed " << *It;
}
for (typename std::vector<ExpectedMatch>::iterator
It = ExpectedMatches.begin(), End = ExpectedMatches.end();
It != End; ++It) {
It->UpdateFor(Name, FullLocation, this->Context->getSourceManager());
}
}
private:
struct MatchCandidate {
std::string ExpectedName;
unsigned LineNumber;
unsigned ColumnNumber;
MatchCandidate(Twine Name, unsigned LineNumber, unsigned ColumnNumber)
: ExpectedName(Name.str()), LineNumber(LineNumber),
ColumnNumber(ColumnNumber) {
}
bool Matches(StringRef Name, FullSourceLoc const &Location) const {
return MatchesName(Name) && MatchesLocation(Location);
}
bool PartiallyMatches(StringRef Name, FullSourceLoc const &Location) const {
return MatchesName(Name) || MatchesLocation(Location);
}
bool MatchesName(StringRef Name) const {
return Name == ExpectedName;
}
bool MatchesLocation(FullSourceLoc const &Location) const {
return Location.isValid() &&
Location.getSpellingLineNumber() == LineNumber &&
Location.getSpellingColumnNumber() == ColumnNumber;
}
friend std::ostream &operator<<(std::ostream &Stream,
MatchCandidate const &Match) {
return Stream << Match.ExpectedName
<< " at " << Match.LineNumber << ":" << Match.ColumnNumber;
}
};
struct ExpectedMatch {
ExpectedMatch(Twine Name, unsigned LineNumber, unsigned ColumnNumber)
: Candidate(Name, LineNumber, ColumnNumber), Found(false) {}
void UpdateFor(StringRef Name, FullSourceLoc Location, SourceManager &SM) {
if (Candidate.Matches(Name, Location)) {
EXPECT_TRUE(!Found);
Found = true;
} else if (!Found && Candidate.PartiallyMatches(Name, Location)) {
llvm::raw_string_ostream Stream(PartialMatches);
Stream << ", partial match: \"" << Name << "\" at ";
Location.print(Stream, SM);
}
}
void ExpectFound() const {
EXPECT_TRUE(Found)
<< "Expected \"" << Candidate.ExpectedName
<< "\" at " << Candidate.LineNumber
<< ":" << Candidate.ColumnNumber << PartialMatches;
}
MatchCandidate Candidate;
std::string PartialMatches;
bool Found;
};
std::vector<MatchCandidate> DisallowedMatches;
std::vector<ExpectedMatch> ExpectedMatches;
};
}
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RecursiveASTVisitorTest.cpp
|
//===- unittest/Tooling/RecursiveASTVisitorTest.cpp -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "TestVisitor.h"
#include <stack>
using namespace clang;
namespace {
class LambdaExprVisitor : public ExpectedLocationVisitor<LambdaExprVisitor> {
public:
bool VisitLambdaExpr(LambdaExpr *Lambda) {
PendingBodies.push(Lambda);
Match("", Lambda->getIntroducerRange().getBegin());
return true;
}
/// For each call to VisitLambdaExpr, we expect a subsequent call (with
/// proper nesting) to TraverseLambdaBody.
bool TraverseLambdaBody(LambdaExpr *Lambda) {
EXPECT_FALSE(PendingBodies.empty());
EXPECT_EQ(PendingBodies.top(), Lambda);
PendingBodies.pop();
return TraverseStmt(Lambda->getBody());
}
/// Determine whether TraverseLambdaBody has been called for every call to
/// VisitLambdaExpr.
bool allBodiesHaveBeenTraversed() const {
return PendingBodies.empty();
}
private:
std::stack<LambdaExpr *> PendingBodies;
};
TEST(RecursiveASTVisitor, VisitsLambdaExpr) {
LambdaExprVisitor Visitor;
Visitor.ExpectMatch("", 1, 12);
EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }",
LambdaExprVisitor::Lang_CXX11));
}
TEST(RecursiveASTVisitor, TraverseLambdaBodyCanBeOverridden) {
LambdaExprVisitor Visitor;
EXPECT_TRUE(Visitor.runOver("void f() { []{ return; }(); }",
LambdaExprVisitor::Lang_CXX11));
EXPECT_TRUE(Visitor.allBodiesHaveBeenTraversed());
}
// Matches the (optional) capture-default of a lambda-introducer.
class LambdaDefaultCaptureVisitor
: public ExpectedLocationVisitor<LambdaDefaultCaptureVisitor> {
public:
bool VisitLambdaExpr(LambdaExpr *Lambda) {
if (Lambda->getCaptureDefault() != LCD_None) {
Match("", Lambda->getCaptureDefaultLoc());
}
return true;
}
};
TEST(RecursiveASTVisitor, HasCaptureDefaultLoc) {
LambdaDefaultCaptureVisitor Visitor;
Visitor.ExpectMatch("", 1, 20);
EXPECT_TRUE(Visitor.runOver("void f() { int a; [=]{a;}; }",
LambdaDefaultCaptureVisitor::Lang_CXX11));
}
// Checks for lambda classes that are not marked as implicitly-generated.
// (There should be none.)
class ClassVisitor : public ExpectedLocationVisitor<ClassVisitor> {
public:
ClassVisitor() : SawNonImplicitLambdaClass(false) {}
bool VisitCXXRecordDecl(CXXRecordDecl* record) {
if (record->isLambda() && !record->isImplicit())
SawNonImplicitLambdaClass = true;
return true;
}
bool sawOnlyImplicitLambdaClasses() const {
return !SawNonImplicitLambdaClass;
}
private:
bool SawNonImplicitLambdaClass;
};
TEST(RecursiveASTVisitor, LambdaClosureTypesAreImplicit) {
ClassVisitor Visitor;
EXPECT_TRUE(Visitor.runOver("auto lambda = []{};",
ClassVisitor::Lang_CXX11));
EXPECT_TRUE(Visitor.sawOnlyImplicitLambdaClasses());
}
// Check to ensure that attributes and expressions within them are being
// visited.
class AttrVisitor : public ExpectedLocationVisitor<AttrVisitor> {
public:
bool VisitMemberExpr(MemberExpr *ME) {
Match(ME->getMemberDecl()->getNameAsString(), ME->getLocStart());
return true;
}
bool VisitAttr(Attr *A) {
Match("Attr", A->getLocation());
return true;
}
bool VisitGuardedByAttr(GuardedByAttr *A) {
Match("guarded_by", A->getLocation());
return true;
}
};
TEST(RecursiveASTVisitor, AttributesAreVisited) {
AttrVisitor Visitor;
Visitor.ExpectMatch("Attr", 4, 24);
Visitor.ExpectMatch("guarded_by", 4, 24);
Visitor.ExpectMatch("mu1", 4, 35);
Visitor.ExpectMatch("Attr", 5, 29);
Visitor.ExpectMatch("mu1", 5, 54);
Visitor.ExpectMatch("mu2", 5, 59);
EXPECT_TRUE(Visitor.runOver(
"class Foo {\n"
" int mu1;\n"
" int mu2;\n"
" int a __attribute__((guarded_by(mu1)));\n"
" void bar() __attribute__((exclusive_locks_required(mu1, mu2)));\n"
"};\n"));
}
} // end anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RefactoringCallbacksTest.cpp
|
//===- unittest/Tooling/RefactoringCallbacksTest.cpp ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/RefactoringCallbacks.h"
#include "RewriterTestContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "gtest/gtest.h"
namespace clang {
namespace tooling {
using namespace ast_matchers;
template <typename T>
void expectRewritten(const std::string &Code,
const std::string &Expected,
const T &AMatcher,
RefactoringCallback &Callback) {
MatchFinder Finder;
Finder.addMatcher(AMatcher, &Callback);
std::unique_ptr<tooling::FrontendActionFactory> Factory(
tooling::newFrontendActionFactory(&Finder));
ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), Code))
<< "Parsing error in \"" << Code << "\"";
RewriterTestContext Context;
FileID ID = Context.createInMemoryFile("input.cc", Code);
EXPECT_TRUE(tooling::applyAllReplacements(Callback.getReplacements(),
Context.Rewrite));
EXPECT_EQ(Expected, Context.getRewrittenText(ID));
}
TEST(RefactoringCallbacksTest, ReplacesStmtsWithString) {
std::string Code = "void f() { int i = 1; }";
std::string Expected = "void f() { ; }";
ReplaceStmtWithText Callback("id", ";");
expectRewritten(Code, Expected, id("id", declStmt()), Callback);
}
TEST(RefactoringCallbacksTest, ReplacesStmtsInCalledMacros) {
std::string Code = "#define A void f() { int i = 1; }\nA";
std::string Expected = "#define A void f() { ; }\nA";
ReplaceStmtWithText Callback("id", ";");
expectRewritten(Code, Expected, id("id", declStmt()), Callback);
}
TEST(RefactoringCallbacksTest, IgnoresStmtsInUncalledMacros) {
std::string Code = "#define A void f() { int i = 1; }";
std::string Expected = "#define A void f() { int i = 1; }";
ReplaceStmtWithText Callback("id", ";");
expectRewritten(Code, Expected, id("id", declStmt()), Callback);
}
TEST(RefactoringCallbacksTest, ReplacesInteger) {
std::string Code = "void f() { int i = 1; }";
std::string Expected = "void f() { int i = 2; }";
ReplaceStmtWithText Callback("id", "2");
expectRewritten(Code, Expected, id("id", expr(integerLiteral())),
Callback);
}
TEST(RefactoringCallbacksTest, ReplacesStmtWithStmt) {
std::string Code = "void f() { int i = false ? 1 : i * 2; }";
std::string Expected = "void f() { int i = i * 2; }";
ReplaceStmtWithStmt Callback("always-false", "should-be");
expectRewritten(Code, Expected,
id("always-false", conditionalOperator(
hasCondition(boolLiteral(equals(false))),
hasFalseExpression(id("should-be", expr())))),
Callback);
}
TEST(RefactoringCallbacksTest, ReplacesIfStmt) {
std::string Code = "bool a; void f() { if (a) f(); else a = true; }";
std::string Expected = "bool a; void f() { f(); }";
ReplaceIfStmtWithItsBody Callback("id", true);
expectRewritten(Code, Expected,
id("id", ifStmt(
hasCondition(implicitCastExpr(hasSourceExpression(
declRefExpr(to(varDecl(hasName("a"))))))))),
Callback);
}
TEST(RefactoringCallbacksTest, RemovesEntireIfOnEmptyElse) {
std::string Code = "void f() { if (false) int i = 0; }";
std::string Expected = "void f() { }";
ReplaceIfStmtWithItsBody Callback("id", false);
expectRewritten(Code, Expected,
id("id", ifStmt(hasCondition(boolLiteral(equals(false))))),
Callback);
}
} // end namespace ast_matchers
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/ToolingTest.cpp
|
//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Config/llvm-config.h"
#include "gtest/gtest.h"
#include <algorithm>
#include <string>
namespace clang {
namespace tooling {
namespace {
/// Takes an ast consumer and returns it from CreateASTConsumer. This only
/// works with single translation unit compilations.
class TestAction : public clang::ASTFrontendAction {
public:
/// Takes ownership of TestConsumer.
explicit TestAction(std::unique_ptr<clang::ASTConsumer> TestConsumer)
: TestConsumer(std::move(TestConsumer)) {}
protected:
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &compiler,
StringRef dummy) override {
/// TestConsumer will be deleted by the framework calling us.
return std::move(TestConsumer);
}
private:
std::unique_ptr<clang::ASTConsumer> TestConsumer;
};
class FindTopLevelDeclConsumer : public clang::ASTConsumer {
public:
explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
: FoundTopLevelDecl(FoundTopLevelDecl) {}
bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) override {
*FoundTopLevelDecl = true;
return true;
}
private:
bool * const FoundTopLevelDecl;
};
} // end namespace
TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
bool FoundTopLevelDecl = false;
EXPECT_TRUE(
runToolOnCode(new TestAction(llvm::make_unique<FindTopLevelDeclConsumer>(
&FoundTopLevelDecl)),
""));
EXPECT_FALSE(FoundTopLevelDecl);
}
namespace {
class FindClassDeclXConsumer : public clang::ASTConsumer {
public:
FindClassDeclXConsumer(bool *FoundClassDeclX)
: FoundClassDeclX(FoundClassDeclX) {}
bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) override {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
*GroupRef.begin())) {
if (Record->getName() == "X") {
*FoundClassDeclX = true;
}
}
return true;
}
private:
bool *FoundClassDeclX;
};
bool FindClassDeclX(ASTUnit *AST) {
for (std::vector<Decl *>::iterator i = AST->top_level_begin(),
e = AST->top_level_end();
i != e; ++i) {
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) {
if (Record->getName() == "X") {
return true;
}
}
}
return false;
}
} // end namespace
TEST(runToolOnCode, FindsClassDecl) {
bool FoundClassDeclX = false;
EXPECT_TRUE(
runToolOnCode(new TestAction(llvm::make_unique<FindClassDeclXConsumer>(
&FoundClassDeclX)),
"class X;"));
EXPECT_TRUE(FoundClassDeclX);
FoundClassDeclX = false;
EXPECT_TRUE(
runToolOnCode(new TestAction(llvm::make_unique<FindClassDeclXConsumer>(
&FoundClassDeclX)),
"class Y;"));
EXPECT_FALSE(FoundClassDeclX);
}
TEST(buildASTFromCode, FindsClassDecl) {
std::unique_ptr<ASTUnit> AST = buildASTFromCode("class X;");
ASSERT_TRUE(AST.get());
EXPECT_TRUE(FindClassDeclX(AST.get()));
AST = buildASTFromCode("class Y;");
ASSERT_TRUE(AST.get());
EXPECT_FALSE(FindClassDeclX(AST.get()));
}
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory<SyntaxOnlyAction>());
std::unique_ptr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != nullptr);
}
struct IndependentFrontendActionCreator {
std::unique_ptr<ASTConsumer> newASTConsumer() {
return llvm::make_unique<FindTopLevelDeclConsumer>(nullptr);
}
};
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
IndependentFrontendActionCreator Creator;
std::unique_ptr<FrontendActionFactory> Factory(
newFrontendActionFactory(&Creator));
std::unique_ptr<FrontendAction> Action(Factory->create());
EXPECT_TRUE(Action.get() != nullptr);
}
TEST(ToolInvocation, TestMapVirtualFile) {
IntrusiveRefCntPtr<clang::FileManager> Files(
new clang::FileManager(clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Files.get());
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
EXPECT_TRUE(Invocation.run());
}
TEST(ToolInvocation, TestVirtualModulesCompilation) {
// FIXME: Currently, this only tests that we don't exit with an error if a
// mapped module.map is found on the include path. In the future, expand this
// test to run a full modules enabled compilation, so we make sure we can
// rerun modules compilations with a virtual file system.
IntrusiveRefCntPtr<clang::FileManager> Files(
new clang::FileManager(clang::FileSystemOptions()));
std::vector<std::string> Args;
Args.push_back("tool-executable");
Args.push_back("-Idef");
Args.push_back("-fsyntax-only");
Args.push_back("test.cpp");
clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Files.get());
Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
Invocation.mapVirtualFile("def/abc", "\n");
// Add a module.map file in the include directory of our header, so we trigger
// the module.map header search logic.
Invocation.mapVirtualFile("def/module.map", "\n");
EXPECT_TRUE(Invocation.run());
}
struct VerifyEndCallback : public SourceFileCallbacks {
VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {}
bool handleBeginSource(CompilerInstance &CI, StringRef Filename) override {
++BeginCalled;
return true;
}
void handleEndSource() override { ++EndCalled; }
std::unique_ptr<ASTConsumer> newASTConsumer() {
return llvm::make_unique<FindTopLevelDeclConsumer>(&Matched);
}
unsigned BeginCalled;
unsigned EndCalled;
bool Matched;
};
#if !defined(LLVM_ON_WIN32)
TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
VerifyEndCallback EndCallback;
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
std::vector<std::string> Sources;
Sources.push_back("/a.cc");
Sources.push_back("/b.cc");
ClangTool Tool(Compilations, Sources);
Tool.mapVirtualFile("/a.cc", "void a() {}");
Tool.mapVirtualFile("/b.cc", "void b() {}");
std::unique_ptr<FrontendActionFactory> Action(
newFrontendActionFactory(&EndCallback, &EndCallback));
Tool.run(Action.get());
EXPECT_TRUE(EndCallback.Matched);
EXPECT_EQ(2u, EndCallback.BeginCalled);
EXPECT_EQ(2u, EndCallback.EndCalled);
}
#endif
struct SkipBodyConsumer : public clang::ASTConsumer {
/// Skip the 'skipMe' function.
bool shouldSkipFunctionBody(Decl *D) override {
FunctionDecl *F = dyn_cast<FunctionDecl>(D);
return F && F->getNameAsString() == "skipMe";
}
};
struct SkipBodyAction : public clang::ASTFrontendAction {
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
StringRef) override {
Compiler.getFrontendOpts().SkipFunctionBodies = true;
return llvm::make_unique<SkipBodyConsumer>();
}
};
TEST(runToolOnCode, TestSkipFunctionBody) {
EXPECT_TRUE(runToolOnCode(new SkipBodyAction,
"int skipMe() { an_error_here }"));
EXPECT_FALSE(runToolOnCode(new SkipBodyAction,
"int skipMeNot() { an_error_here }"));
}
TEST(runToolOnCodeWithArgs, TestNoDepFile) {
llvm::SmallString<32> DepFilePath;
ASSERT_FALSE(
llvm::sys::fs::createTemporaryFile("depfile", "d", DepFilePath));
std::vector<std::string> Args;
Args.push_back("-MMD");
Args.push_back("-MT");
Args.push_back(DepFilePath.str());
Args.push_back("-MF");
Args.push_back(DepFilePath.str());
EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args));
EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
}
TEST(ClangToolTest, ArgumentAdjusters) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "void a() {}");
std::unique_ptr<FrontendActionFactory> Action(
newFrontendActionFactory<SyntaxOnlyAction>());
bool Found = false;
bool Ran = false;
ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
[&Found, &Ran](const CommandLineArguments &Args) {
Ran = true;
if (std::find(Args.begin(), Args.end(), "-fsyntax-only") != Args.end())
Found = true;
return Args;
};
Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
Tool.run(Action.get());
EXPECT_TRUE(Ran);
EXPECT_TRUE(Found);
Ran = Found = false;
Tool.clearArgumentsAdjusters();
Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Tool.run(Action.get());
EXPECT_TRUE(Ran);
EXPECT_FALSE(Found);
}
#ifndef LLVM_ON_WIN32
TEST(ClangToolTest, BuildASTs) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
std::vector<std::string> Sources;
Sources.push_back("/a.cc");
Sources.push_back("/b.cc");
ClangTool Tool(Compilations, Sources);
Tool.mapVirtualFile("/a.cc", "void a() {}");
Tool.mapVirtualFile("/b.cc", "void b() {}");
std::vector<std::unique_ptr<ASTUnit>> ASTs;
EXPECT_EQ(0, Tool.buildASTs(ASTs));
EXPECT_EQ(2u, ASTs.size());
}
struct TestDiagnosticConsumer : public DiagnosticConsumer {
TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {}
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const Diagnostic &Info) override {
++NumDiagnosticsSeen;
}
unsigned NumDiagnosticsSeen;
};
TEST(ClangToolTest, InjectDiagnosticConsumer) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
TestDiagnosticConsumer Consumer;
Tool.setDiagnosticConsumer(&Consumer);
std::unique_ptr<FrontendActionFactory> Action(
newFrontendActionFactory<SyntaxOnlyAction>());
Tool.run(Action.get());
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}
TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) {
FixedCompilationDatabase Compilations("/", std::vector<std::string>());
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
TestDiagnosticConsumer Consumer;
Tool.setDiagnosticConsumer(&Consumer);
std::vector<std::unique_ptr<ASTUnit>> ASTs;
Tool.buildASTs(ASTs);
EXPECT_EQ(1u, ASTs.size());
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
}
#endif
} // end namespace tooling
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/CompilationDatabaseTest.cpp
|
//===- unittest/Tooling/CompilationDatabaseTest.cpp -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/FileMatchTrie.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/Path.h"
#include "gtest/gtest.h"
namespace clang {
namespace tooling {
static void expectFailure(StringRef JSONDatabase, StringRef Explanation) {
std::string ErrorMessage;
EXPECT_EQ(nullptr, JSONCompilationDatabase::loadFromBuffer(JSONDatabase,
ErrorMessage))
<< "Expected an error because of: " << Explanation.str();
}
TEST(JSONCompilationDatabase, ErrsOnInvalidFormat) {
expectFailure("", "Empty database");
expectFailure("{", "Invalid JSON");
expectFailure("[[]]", "Array instead of object");
expectFailure("[{\"a\":[]}]", "Array instead of value");
expectFailure("[{\"a\":\"b\"}]", "Unknown key");
expectFailure("[{[]:\"\"}]", "Incorrectly typed entry");
expectFailure("[{}]", "Empty entry");
expectFailure("[{\"directory\":\"\",\"command\":\"\"}]", "Missing file");
expectFailure("[{\"directory\":\"\",\"file\":\"\"}]", "Missing command");
expectFailure("[{\"command\":\"\",\"file\":\"\"}]", "Missing directory");
}
static std::vector<std::string> getAllFiles(StringRef JSONDatabase,
std::string &ErrorMessage) {
std::unique_ptr<CompilationDatabase> Database(
JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
if (!Database) {
ADD_FAILURE() << ErrorMessage;
return std::vector<std::string>();
}
return Database->getAllFiles();
}
static std::vector<CompileCommand> getAllCompileCommands(StringRef JSONDatabase,
std::string &ErrorMessage) {
std::unique_ptr<CompilationDatabase> Database(
JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
if (!Database) {
ADD_FAILURE() << ErrorMessage;
return std::vector<CompileCommand>();
}
return Database->getAllCompileCommands();
}
TEST(JSONCompilationDatabase, GetAllFiles) {
std::string ErrorMessage;
EXPECT_EQ(std::vector<std::string>(),
getAllFiles("[]", ErrorMessage)) << ErrorMessage;
std::vector<std::string> expected_files;
SmallString<16> PathStorage;
llvm::sys::path::native("//net/dir/file1", PathStorage);
expected_files.push_back(PathStorage.str());
llvm::sys::path::native("//net/dir/file2", PathStorage);
expected_files.push_back(PathStorage.str());
EXPECT_EQ(expected_files, getAllFiles(
"[{\"directory\":\"//net/dir\","
"\"command\":\"command\","
"\"file\":\"file1\"},"
" {\"directory\":\"//net/dir\","
"\"command\":\"command\","
"\"file\":\"file2\"}]",
ErrorMessage)) << ErrorMessage;
}
TEST(JSONCompilationDatabase, GetAllCompileCommands) {
std::string ErrorMessage;
EXPECT_EQ(0u,
getAllCompileCommands("[]", ErrorMessage).size()) << ErrorMessage;
StringRef Directory1("//net/dir1");
StringRef FileName1("file1");
StringRef Command1("command1");
StringRef Directory2("//net/dir2");
StringRef FileName2("file1");
StringRef Command2("command1");
std::vector<CompileCommand> Commands = getAllCompileCommands(
("[{\"directory\":\"" + Directory1 + "\"," +
"\"command\":\"" + Command1 + "\","
"\"file\":\"" + FileName1 + "\"},"
" {\"directory\":\"" + Directory2 + "\"," +
"\"command\":\"" + Command2 + "\","
"\"file\":\"" + FileName2 + "\"}]").str(),
ErrorMessage);
EXPECT_EQ(2U, Commands.size()) << ErrorMessage;
EXPECT_EQ(Directory1, Commands[0].Directory) << ErrorMessage;
ASSERT_EQ(1u, Commands[0].CommandLine.size());
EXPECT_EQ(Command1, Commands[0].CommandLine[0]) << ErrorMessage;
EXPECT_EQ(Directory2, Commands[1].Directory) << ErrorMessage;
ASSERT_EQ(1u, Commands[1].CommandLine.size());
EXPECT_EQ(Command2, Commands[1].CommandLine[0]) << ErrorMessage;
}
static CompileCommand findCompileArgsInJsonDatabase(StringRef FileName,
StringRef JSONDatabase,
std::string &ErrorMessage) {
std::unique_ptr<CompilationDatabase> Database(
JSONCompilationDatabase::loadFromBuffer(JSONDatabase, ErrorMessage));
if (!Database)
return CompileCommand();
std::vector<CompileCommand> Commands = Database->getCompileCommands(FileName);
EXPECT_LE(Commands.size(), 1u);
if (Commands.empty())
return CompileCommand();
return Commands[0];
}
struct FakeComparator : public PathComparator {
~FakeComparator() override {}
bool equivalent(StringRef FileA, StringRef FileB) const override {
return FileA.equals_lower(FileB);
}
};
class FileMatchTrieTest : public ::testing::Test {
protected:
FileMatchTrieTest() : Trie(new FakeComparator()) {}
StringRef find(StringRef Path) {
llvm::raw_string_ostream ES(Error);
return Trie.findEquivalent(Path, ES);
}
FileMatchTrie Trie;
std::string Error;
};
TEST_F(FileMatchTrieTest, InsertingRelativePath) {
Trie.insert("//net/path/file.cc");
Trie.insert("file.cc");
EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}
TEST_F(FileMatchTrieTest, MatchingRelativePath) {
EXPECT_EQ("", find("file.cc"));
}
TEST_F(FileMatchTrieTest, ReturnsBestResults) {
Trie.insert("//net/d/c/b.cc");
Trie.insert("//net/d/b/b.cc");
EXPECT_EQ("//net/d/b/b.cc", find("//net/d/b/b.cc"));
}
TEST_F(FileMatchTrieTest, HandlesSymlinks) {
Trie.insert("//net/AA/file.cc");
EXPECT_EQ("//net/AA/file.cc", find("//net/aa/file.cc"));
}
TEST_F(FileMatchTrieTest, ReportsSymlinkAmbiguity) {
Trie.insert("//net/Aa/file.cc");
Trie.insert("//net/aA/file.cc");
EXPECT_TRUE(find("//net/aa/file.cc").empty());
EXPECT_EQ("Path is ambiguous", Error);
}
TEST_F(FileMatchTrieTest, LongerMatchingSuffixPreferred) {
Trie.insert("//net/src/Aa/file.cc");
Trie.insert("//net/src/aA/file.cc");
Trie.insert("//net/SRC/aa/file.cc");
EXPECT_EQ("//net/SRC/aa/file.cc", find("//net/src/aa/file.cc"));
}
TEST_F(FileMatchTrieTest, EmptyTrie) {
EXPECT_TRUE(find("//net/some/path").empty());
}
TEST_F(FileMatchTrieTest, NoResult) {
Trie.insert("//net/somepath/otherfile.cc");
Trie.insert("//net/otherpath/somefile.cc");
EXPECT_EQ("", find("//net/somepath/somefile.cc"));
}
TEST_F(FileMatchTrieTest, RootElementDifferent) {
Trie.insert("//net/path/file.cc");
Trie.insert("//net/otherpath/file.cc");
EXPECT_EQ("//net/path/file.cc", find("//net/path/file.cc"));
}
TEST_F(FileMatchTrieTest, CannotResolveRelativePath) {
EXPECT_EQ("", find("relative-path.cc"));
EXPECT_EQ("Cannot resolve relative paths", Error);
}
TEST(findCompileArgsInJsonDatabase, FindsNothingIfEmpty) {
std::string ErrorMessage;
CompileCommand NotFound = findCompileArgsInJsonDatabase(
"a-file.cpp", "", ErrorMessage);
EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
}
TEST(findCompileArgsInJsonDatabase, ReadsSingleEntry) {
StringRef Directory("//net/some/directory");
StringRef FileName("//net/path/to/a-file.cpp");
StringRef Command("//net/path/to/compiler and some arguments");
std::string ErrorMessage;
CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
FileName,
("[{\"directory\":\"" + Directory + "\"," +
"\"command\":\"" + Command + "\","
"\"file\":\"" + FileName + "\"}]").str(),
ErrorMessage);
EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
ASSERT_EQ(4u, FoundCommand.CommandLine.size()) << ErrorMessage;
EXPECT_EQ("//net/path/to/compiler",
FoundCommand.CommandLine[0]) << ErrorMessage;
EXPECT_EQ("and", FoundCommand.CommandLine[1]) << ErrorMessage;
EXPECT_EQ("some", FoundCommand.CommandLine[2]) << ErrorMessage;
EXPECT_EQ("arguments", FoundCommand.CommandLine[3]) << ErrorMessage;
CompileCommand NotFound = findCompileArgsInJsonDatabase(
"a-file.cpp",
("[{\"directory\":\"" + Directory + "\"," +
"\"command\":\"" + Command + "\","
"\"file\":\"" + FileName + "\"}]").str(),
ErrorMessage);
EXPECT_TRUE(NotFound.Directory.empty()) << ErrorMessage;
EXPECT_TRUE(NotFound.CommandLine.empty()) << ErrorMessage;
}
TEST(findCompileArgsInJsonDatabase, ReadsCompileCommandLinesWithSpaces) {
StringRef Directory("//net/some/directory");
StringRef FileName("//net/path/to/a-file.cpp");
StringRef Command("\\\"//net/path to compiler\\\" \\\"and an argument\\\"");
std::string ErrorMessage;
CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
FileName,
("[{\"directory\":\"" + Directory + "\"," +
"\"command\":\"" + Command + "\","
"\"file\":\"" + FileName + "\"}]").str(),
ErrorMessage);
ASSERT_EQ(2u, FoundCommand.CommandLine.size());
EXPECT_EQ("//net/path to compiler",
FoundCommand.CommandLine[0]) << ErrorMessage;
EXPECT_EQ("and an argument", FoundCommand.CommandLine[1]) << ErrorMessage;
}
TEST(findCompileArgsInJsonDatabase, ReadsDirectoryWithSpaces) {
StringRef Directory("//net/some directory / with spaces");
StringRef FileName("//net/path/to/a-file.cpp");
StringRef Command("a command");
std::string ErrorMessage;
CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
FileName,
("[{\"directory\":\"" + Directory + "\"," +
"\"command\":\"" + Command + "\","
"\"file\":\"" + FileName + "\"}]").str(),
ErrorMessage);
EXPECT_EQ(Directory, FoundCommand.Directory) << ErrorMessage;
}
TEST(findCompileArgsInJsonDatabase, FindsEntry) {
StringRef Directory("//net/directory");
StringRef FileName("file");
StringRef Command("command");
std::string JsonDatabase = "[";
for (int I = 0; I < 10; ++I) {
if (I > 0) JsonDatabase += ",";
JsonDatabase +=
("{\"directory\":\"" + Directory + Twine(I) + "\"," +
"\"command\":\"" + Command + Twine(I) + "\","
"\"file\":\"" + FileName + Twine(I) + "\"}").str();
}
JsonDatabase += "]";
std::string ErrorMessage;
CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
"//net/directory4/file4", JsonDatabase, ErrorMessage);
EXPECT_EQ("//net/directory4", FoundCommand.Directory) << ErrorMessage;
ASSERT_EQ(1u, FoundCommand.CommandLine.size()) << ErrorMessage;
EXPECT_EQ("command4", FoundCommand.CommandLine[0]) << ErrorMessage;
}
static std::vector<std::string> unescapeJsonCommandLine(StringRef Command) {
std::string JsonDatabase =
("[{\"directory\":\"//net/root\", \"file\":\"test\", \"command\": \"" +
Command + "\"}]").str();
std::string ErrorMessage;
CompileCommand FoundCommand = findCompileArgsInJsonDatabase(
"//net/root/test", JsonDatabase, ErrorMessage);
EXPECT_TRUE(ErrorMessage.empty()) << ErrorMessage;
return FoundCommand.CommandLine;
}
TEST(unescapeJsonCommandLine, ReturnsEmptyArrayOnEmptyString) {
std::vector<std::string> Result = unescapeJsonCommandLine("");
EXPECT_TRUE(Result.empty());
}
TEST(unescapeJsonCommandLine, SplitsOnSpaces) {
std::vector<std::string> Result = unescapeJsonCommandLine("a b c");
ASSERT_EQ(3ul, Result.size());
EXPECT_EQ("a", Result[0]);
EXPECT_EQ("b", Result[1]);
EXPECT_EQ("c", Result[2]);
}
TEST(unescapeJsonCommandLine, MungesMultipleSpaces) {
std::vector<std::string> Result = unescapeJsonCommandLine(" a b ");
ASSERT_EQ(2ul, Result.size());
EXPECT_EQ("a", Result[0]);
EXPECT_EQ("b", Result[1]);
}
TEST(unescapeJsonCommandLine, UnescapesBackslashCharacters) {
std::vector<std::string> Backslash = unescapeJsonCommandLine("a\\\\\\\\");
ASSERT_EQ(1ul, Backslash.size());
EXPECT_EQ("a\\", Backslash[0]);
std::vector<std::string> Quote = unescapeJsonCommandLine("a\\\\\\\"");
ASSERT_EQ(1ul, Quote.size());
EXPECT_EQ("a\"", Quote[0]);
}
TEST(unescapeJsonCommandLine, DoesNotMungeSpacesBetweenQuotes) {
std::vector<std::string> Result = unescapeJsonCommandLine("\\\" a b \\\"");
ASSERT_EQ(1ul, Result.size());
EXPECT_EQ(" a b ", Result[0]);
}
TEST(unescapeJsonCommandLine, AllowsMultipleQuotedArguments) {
std::vector<std::string> Result = unescapeJsonCommandLine(
" \\\" a \\\" \\\" b \\\" ");
ASSERT_EQ(2ul, Result.size());
EXPECT_EQ(" a ", Result[0]);
EXPECT_EQ(" b ", Result[1]);
}
TEST(unescapeJsonCommandLine, AllowsEmptyArgumentsInQuotes) {
std::vector<std::string> Result = unescapeJsonCommandLine(
"\\\"\\\"\\\"\\\"");
ASSERT_EQ(1ul, Result.size());
EXPECT_TRUE(Result[0].empty()) << Result[0];
}
TEST(unescapeJsonCommandLine, ParsesEscapedQuotesInQuotedStrings) {
std::vector<std::string> Result = unescapeJsonCommandLine(
"\\\"\\\\\\\"\\\"");
ASSERT_EQ(1ul, Result.size());
EXPECT_EQ("\"", Result[0]);
}
TEST(unescapeJsonCommandLine, ParsesMultipleArgumentsWithEscapedCharacters) {
std::vector<std::string> Result = unescapeJsonCommandLine(
" \\\\\\\" \\\"a \\\\\\\" b \\\" \\\"and\\\\\\\\c\\\" \\\\\\\"");
ASSERT_EQ(4ul, Result.size());
EXPECT_EQ("\"", Result[0]);
EXPECT_EQ("a \" b ", Result[1]);
EXPECT_EQ("and\\c", Result[2]);
EXPECT_EQ("\"", Result[3]);
}
TEST(unescapeJsonCommandLine, ParsesStringsWithoutSpacesIntoSingleArgument) {
std::vector<std::string> QuotedNoSpaces = unescapeJsonCommandLine(
"\\\"a\\\"\\\"b\\\"");
ASSERT_EQ(1ul, QuotedNoSpaces.size());
EXPECT_EQ("ab", QuotedNoSpaces[0]);
std::vector<std::string> MixedNoSpaces = unescapeJsonCommandLine(
"\\\"a\\\"bcd\\\"ef\\\"\\\"\\\"\\\"g\\\"");
ASSERT_EQ(1ul, MixedNoSpaces.size());
EXPECT_EQ("abcdefg", MixedNoSpaces[0]);
}
TEST(unescapeJsonCommandLine, ParsesQuotedStringWithoutClosingQuote) {
std::vector<std::string> Unclosed = unescapeJsonCommandLine("\\\"abc");
ASSERT_EQ(1ul, Unclosed.size());
EXPECT_EQ("abc", Unclosed[0]);
std::vector<std::string> Empty = unescapeJsonCommandLine("\\\"");
ASSERT_EQ(1ul, Empty.size());
EXPECT_EQ("", Empty[0]);
}
TEST(unescapeJsonCommandLine, ParsesSingleQuotedString) {
std::vector<std::string> Args = unescapeJsonCommandLine("a'\\\\b \\\"c\\\"'");
ASSERT_EQ(1ul, Args.size());
EXPECT_EQ("a\\b \"c\"", Args[0]);
}
TEST(FixedCompilationDatabase, ReturnsFixedCommandLine) {
std::vector<std::string> CommandLine;
CommandLine.push_back("one");
CommandLine.push_back("two");
FixedCompilationDatabase Database(".", CommandLine);
std::vector<CompileCommand> Result =
Database.getCompileCommands("source");
ASSERT_EQ(1ul, Result.size());
std::vector<std::string> ExpectedCommandLine(1, "clang-tool");
ExpectedCommandLine.insert(ExpectedCommandLine.end(),
CommandLine.begin(), CommandLine.end());
ExpectedCommandLine.push_back("source");
EXPECT_EQ(".", Result[0].Directory);
EXPECT_EQ(ExpectedCommandLine, Result[0].CommandLine);
}
TEST(FixedCompilationDatabase, GetAllFiles) {
std::vector<std::string> CommandLine;
CommandLine.push_back("one");
CommandLine.push_back("two");
FixedCompilationDatabase Database(".", CommandLine);
EXPECT_EQ(0ul, Database.getAllFiles().size());
}
TEST(FixedCompilationDatabase, GetAllCompileCommands) {
std::vector<std::string> CommandLine;
CommandLine.push_back("one");
CommandLine.push_back("two");
FixedCompilationDatabase Database(".", CommandLine);
EXPECT_EQ(0ul, Database.getAllCompileCommands().size());
}
TEST(ParseFixedCompilationDatabase, ReturnsNullOnEmptyArgumentList) {
int Argc = 0;
std::unique_ptr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, nullptr));
EXPECT_FALSE(Database);
EXPECT_EQ(0, Argc);
}
TEST(ParseFixedCompilationDatabase, ReturnsNullWithoutDoubleDash) {
int Argc = 2;
const char *Argv[] = { "1", "2" };
std::unique_ptr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
EXPECT_FALSE(Database);
EXPECT_EQ(2, Argc);
}
TEST(ParseFixedCompilationDatabase, ReturnsArgumentsAfterDoubleDash) {
int Argc = 5;
const char *Argv[] = {
"1", "2", "--\0no-constant-folding", "-DDEF3", "-DDEF4"
};
std::unique_ptr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
ASSERT_TRUE((bool)Database);
std::vector<CompileCommand> Result =
Database->getCompileCommands("source");
ASSERT_EQ(1ul, Result.size());
ASSERT_EQ(".", Result[0].Directory);
std::vector<std::string> CommandLine;
CommandLine.push_back("clang-tool");
CommandLine.push_back("-DDEF3");
CommandLine.push_back("-DDEF4");
CommandLine.push_back("source");
ASSERT_EQ(CommandLine, Result[0].CommandLine);
EXPECT_EQ(2, Argc);
}
TEST(ParseFixedCompilationDatabase, ReturnsEmptyCommandLine) {
int Argc = 3;
const char *Argv[] = { "1", "2", "--\0no-constant-folding" };
std::unique_ptr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
ASSERT_TRUE((bool)Database);
std::vector<CompileCommand> Result =
Database->getCompileCommands("source");
ASSERT_EQ(1ul, Result.size());
ASSERT_EQ(".", Result[0].Directory);
std::vector<std::string> CommandLine;
CommandLine.push_back("clang-tool");
CommandLine.push_back("source");
ASSERT_EQ(CommandLine, Result[0].CommandLine);
EXPECT_EQ(2, Argc);
}
TEST(ParseFixedCompilationDatabase, HandlesPositionalArgs) {
const char *Argv[] = {"1", "2", "--", "-c", "somefile.cpp", "-DDEF3"};
int Argc = sizeof(Argv) / sizeof(char*);
std::unique_ptr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
ASSERT_TRUE((bool)Database);
std::vector<CompileCommand> Result =
Database->getCompileCommands("source");
ASSERT_EQ(1ul, Result.size());
ASSERT_EQ(".", Result[0].Directory);
std::vector<std::string> Expected;
Expected.push_back("clang-tool");
Expected.push_back("-c");
Expected.push_back("-DDEF3");
Expected.push_back("source");
ASSERT_EQ(Expected, Result[0].CommandLine);
EXPECT_EQ(2, Argc);
}
TEST(ParseFixedCompilationDatabase, HandlesArgv0) {
const char *Argv[] = {"1", "2", "--", "mytool", "somefile.cpp"};
int Argc = sizeof(Argv) / sizeof(char*);
std::unique_ptr<FixedCompilationDatabase> Database(
FixedCompilationDatabase::loadFromCommandLine(Argc, Argv));
ASSERT_TRUE((bool)Database);
std::vector<CompileCommand> Result =
Database->getCompileCommands("source");
ASSERT_EQ(1ul, Result.size());
ASSERT_EQ(".", Result[0].Directory);
std::vector<std::string> Expected;
Expected.push_back("clang-tool");
Expected.push_back("source");
ASSERT_EQ(Expected, Result[0].CommandLine);
EXPECT_EQ(2, Argc);
}
} // end namespace tooling
} // end namespace clang
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RecursiveASTVisitorTestDeclVisitor.cpp
|
//===- unittest/Tooling/RecursiveASTVisitorTestDeclVisitor.cpp ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "TestVisitor.h"
#include <stack>
using namespace clang;
namespace {
class VarDeclVisitor : public ExpectedLocationVisitor<VarDeclVisitor> {
public:
bool VisitVarDecl(VarDecl *Variable) {
Match(Variable->getNameAsString(), Variable->getLocStart());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsCXXForRangeStmtLoopVariable) {
VarDeclVisitor Visitor;
Visitor.ExpectMatch("i", 2, 17);
EXPECT_TRUE(Visitor.runOver(
"int x[5];\n"
"void f() { for (int i : x) {} }",
VarDeclVisitor::Lang_CXX11));
}
class ParmVarDeclVisitorForImplicitCode :
public ExpectedLocationVisitor<ParmVarDeclVisitorForImplicitCode> {
public:
bool shouldVisitImplicitCode() const { return true; }
bool VisitParmVarDecl(ParmVarDecl *ParamVar) {
Match(ParamVar->getNameAsString(), ParamVar->getLocStart());
return true;
}
};
// Test RAV visits parameter variable declaration of the implicit
// copy assignment operator and implicit copy constructor.
TEST(RecursiveASTVisitor, VisitsParmVarDeclForImplicitCode) {
ParmVarDeclVisitorForImplicitCode Visitor;
// Match parameter variable name of implicit copy assignment operator and
// implicit copy constructor.
// This parameter name does not have a valid IdentifierInfo, and shares
// same SourceLocation with its class declaration, so we match an empty name
// with the class' source location.
Visitor.ExpectMatch("", 1, 7);
Visitor.ExpectMatch("", 3, 7);
EXPECT_TRUE(Visitor.runOver(
"class X {};\n"
"void foo(X a, X b) {a = b;}\n"
"class Y {};\n"
"void bar(Y a) {Y b = a;}"));
}
class NamedDeclVisitor
: public ExpectedLocationVisitor<NamedDeclVisitor> {
public:
bool VisitNamedDecl(NamedDecl *Decl) {
std::string NameWithTemplateArgs;
llvm::raw_string_ostream OS(NameWithTemplateArgs);
Decl->getNameForDiagnostic(OS,
Decl->getASTContext().getPrintingPolicy(),
true);
Match(OS.str(), Decl->getLocation());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsPartialTemplateSpecialization) {
// From cfe-commits/Week-of-Mon-20100830/033998.html
// Contrary to the approach suggested in that email, we visit all
// specializations when we visit the primary template. Visiting them when we
// visit the associated specialization is problematic for specializations of
// template members of class templates.
NamedDeclVisitor Visitor;
Visitor.ExpectMatch("A<bool>", 1, 26);
Visitor.ExpectMatch("A<char *>", 2, 26);
EXPECT_TRUE(Visitor.runOver(
"template <class T> class A {};\n"
"template <class T> class A<T*> {};\n"
"A<bool> ab;\n"
"A<char*> acp;\n"));
}
TEST(RecursiveASTVisitor, VisitsUndefinedClassTemplateSpecialization) {
NamedDeclVisitor Visitor;
Visitor.ExpectMatch("A<int>", 1, 29);
EXPECT_TRUE(Visitor.runOver(
"template<typename T> struct A;\n"
"A<int> *p;\n"));
}
TEST(RecursiveASTVisitor, VisitsNestedUndefinedClassTemplateSpecialization) {
NamedDeclVisitor Visitor;
Visitor.ExpectMatch("A<int>::B<char>", 2, 31);
EXPECT_TRUE(Visitor.runOver(
"template<typename T> struct A {\n"
" template<typename U> struct B;\n"
"};\n"
"A<int>::B<char> *p;\n"));
}
TEST(RecursiveASTVisitor, VisitsUndefinedFunctionTemplateSpecialization) {
NamedDeclVisitor Visitor;
Visitor.ExpectMatch("A<int>", 1, 26);
EXPECT_TRUE(Visitor.runOver(
"template<typename T> int A();\n"
"int k = A<int>();\n"));
}
TEST(RecursiveASTVisitor, VisitsNestedUndefinedFunctionTemplateSpecialization) {
NamedDeclVisitor Visitor;
Visitor.ExpectMatch("A<int>::B<char>", 2, 35);
EXPECT_TRUE(Visitor.runOver(
"template<typename T> struct A {\n"
" template<typename U> static int B();\n"
"};\n"
"int k = A<int>::B<char>();\n"));
}
TEST(RecursiveASTVisitor, NoRecursionInSelfFriend) {
// From cfe-commits/Week-of-Mon-20100830/033977.html
NamedDeclVisitor Visitor;
Visitor.ExpectMatch("vector_iterator<int>", 2, 7);
EXPECT_TRUE(Visitor.runOver(
"template<typename Container>\n"
"class vector_iterator {\n"
" template <typename C> friend class vector_iterator;\n"
"};\n"
"vector_iterator<int> it_int;\n"));
}
} // end anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RewriterTestContext.h
|
//===--- RewriterTestContext.h ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a utility class for Rewriter related tests.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_UNITTESTS_TOOLING_REWRITERTESTCONTEXT_H
#define LLVM_CLANG_UNITTESTS_TOOLING_REWRITERTESTCONTEXT_H
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
/// \brief A class that sets up a ready to use Rewriter.
///
/// Useful in unit tests that need a Rewriter. Creates all dependencies
/// of a Rewriter with default values for testing and provides convenience
/// methods, which help with writing tests that change files.
class RewriterTestContext {
public:
RewriterTestContext()
: DiagOpts(new DiagnosticOptions()),
Diagnostics(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
&*DiagOpts),
DiagnosticPrinter(llvm::outs(), &*DiagOpts),
Files((FileSystemOptions())),
Sources(Diagnostics, Files),
Rewrite(Sources, Options) {
Diagnostics.setClient(&DiagnosticPrinter, false);
}
~RewriterTestContext() {}
FileID createInMemoryFile(StringRef Name, StringRef Content) {
std::unique_ptr<llvm::MemoryBuffer> Source =
llvm::MemoryBuffer::getMemBuffer(Content);
const FileEntry *Entry =
Files.getVirtualFile(Name, Source->getBufferSize(), 0);
Sources.overrideFileContents(Entry, std::move(Source));
assert(Entry != nullptr);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}
// FIXME: this code is mostly a duplicate of
// unittests/Tooling/RefactoringTest.cpp. Figure out a way to share it.
FileID createOnDiskFile(StringRef Name, StringRef Content) {
SmallString<1024> Path;
int FD;
std::error_code EC = llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
assert(!EC);
(void)EC;
llvm::raw_fd_ostream OutStream(FD, true);
OutStream << Content;
OutStream.close();
const FileEntry *File = Files.getFile(Path);
assert(File != nullptr);
StringRef Found =
TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
assert(Found == Path);
(void)Found;
return Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
}
SourceLocation getLocation(FileID ID, unsigned Line, unsigned Column) {
SourceLocation Result = Sources.translateFileLineCol(
Sources.getFileEntryForID(ID), Line, Column);
assert(Result.isValid());
return Result;
}
std::string getRewrittenText(FileID ID) {
std::string Result;
llvm::raw_string_ostream OS(Result);
Rewrite.getEditBuffer(ID).write(OS);
OS.flush();
return Result;
}
std::string getFileContentFromDisk(StringRef Name) {
std::string Path = TemporaryFiles.lookup(Name);
assert(!Path.empty());
// We need to read directly from the FileManager without relaying through
// a FileEntry, as otherwise we'd read through an already opened file
// descriptor, which might not see the changes made.
// FIXME: Figure out whether there is a way to get the SourceManger to
// reopen the file.
auto FileBuffer = Files.getBufferForFile(Path);
return (*FileBuffer)->getBuffer();
}
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
DiagnosticsEngine Diagnostics;
TextDiagnosticPrinter DiagnosticPrinter;
FileManager Files;
SourceManager Sources;
LangOptions Options;
Rewriter Rewrite;
// Will be set once on disk files are generated.
llvm::StringMap<std::string> TemporaryFiles;
};
} // end namespace clang
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RecursiveASTVisitorTestTypeLocVisitor.cpp
|
//===- unittest/Tooling/RecursiveASTVisitorTestTypeLocVisitor.cpp ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "TestVisitor.h"
#include <stack>
using namespace clang;
namespace {
class TypeLocVisitor : public ExpectedLocationVisitor<TypeLocVisitor> {
public:
bool VisitTypeLoc(TypeLoc TypeLocation) {
Match(TypeLocation.getType().getAsString(), TypeLocation.getBeginLoc());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsBaseClassDeclarations) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("class X", 1, 30);
EXPECT_TRUE(Visitor.runOver("class X {}; class Y : public X {};"));
}
TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersOfForwardDeclaredClass) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("class X", 3, 18);
EXPECT_TRUE(Visitor.runOver(
"class Y;\n"
"class X {};\n"
"class Y : public X {};"));
}
TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersWithIncompleteInnerClass) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("class X", 2, 18);
EXPECT_TRUE(Visitor.runOver(
"class X {};\n"
"class Y : public X { class Z; };"));
}
TEST(RecursiveASTVisitor, VisitsCXXBaseSpecifiersOfSelfReferentialType) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("X<class Y>", 2, 18);
EXPECT_TRUE(Visitor.runOver(
"template<typename T> class X {};\n"
"class Y : public X<Y> {};"));
}
TEST(RecursiveASTVisitor, VisitsClassTemplateTypeParmDefaultArgument) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("class X", 2, 23);
EXPECT_TRUE(Visitor.runOver(
"class X;\n"
"template<typename T = X> class Y;\n"
"template<typename T> class Y {};\n"));
}
TEST(RecursiveASTVisitor, VisitsCompoundLiteralType) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("struct S", 1, 26);
EXPECT_TRUE(Visitor.runOver(
"int f() { return (struct S { int a; }){.a = 0}.a; }",
TypeLocVisitor::Lang_C));
}
TEST(RecursiveASTVisitor, VisitsObjCPropertyType) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("NSNumber", 2, 33);
EXPECT_TRUE(Visitor.runOver(
"@class NSNumber; \n"
"@interface A @property (retain) NSNumber *x; @end\n",
TypeLocVisitor::Lang_OBJC));
}
TEST(RecursiveASTVisitor, VisitInvalidType) {
TypeLocVisitor Visitor;
// FIXME: It would be nice to have information about subtypes of invalid type
//Visitor.ExpectMatch("typeof(struct F *) []", 1, 1);
// Even if the full type is invalid, it should still find sub types
//Visitor.ExpectMatch("struct F", 1, 19);
EXPECT_FALSE(Visitor.runOver(
"__typeof__(struct F*) var[invalid];\n",
TypeLocVisitor::Lang_C));
}
} // end anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/RecursiveASTVisitorTestExprVisitor.cpp
|
//===- unittest/Tooling/RecursiveASTVisitorTestExprVisitor.cpp ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "TestVisitor.h"
#include <stack>
using namespace clang;
namespace {
class ParenExprVisitor : public ExpectedLocationVisitor<ParenExprVisitor> {
public:
bool VisitParenExpr(ParenExpr *Parens) {
Match("", Parens->getExprLoc());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsParensDuringDataRecursion) {
ParenExprVisitor Visitor;
Visitor.ExpectMatch("", 1, 9);
EXPECT_TRUE(Visitor.runOver("int k = (4) + 9;\n"));
}
class TemplateArgumentLocTraverser
: public ExpectedLocationVisitor<TemplateArgumentLocTraverser> {
public:
bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
std::string ArgStr;
llvm::raw_string_ostream Stream(ArgStr);
const TemplateArgument &Arg = ArgLoc.getArgument();
Arg.print(Context->getPrintingPolicy(), Stream);
Match(Stream.str(), ArgLoc.getLocation());
return ExpectedLocationVisitor<TemplateArgumentLocTraverser>::
TraverseTemplateArgumentLoc(ArgLoc);
}
};
TEST(RecursiveASTVisitor, VisitsClassTemplateTemplateParmDefaultArgument) {
TemplateArgumentLocTraverser Visitor;
Visitor.ExpectMatch("X", 2, 40);
EXPECT_TRUE(Visitor.runOver(
"template<typename T> class X;\n"
"template<template <typename> class T = X> class Y;\n"
"template<template <typename> class T> class Y {};\n"));
}
class CXXBoolLiteralExprVisitor
: public ExpectedLocationVisitor<CXXBoolLiteralExprVisitor> {
public:
bool VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *BE) {
if (BE->getValue())
Match("true", BE->getLocation());
else
Match("false", BE->getLocation());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsClassTemplateNonTypeParmDefaultArgument) {
CXXBoolLiteralExprVisitor Visitor;
Visitor.ExpectMatch("true", 2, 19);
EXPECT_TRUE(Visitor.runOver(
"template<bool B> class X;\n"
"template<bool B = true> class Y;\n"
"template<bool B> class Y {};\n"));
}
// A visitor that visits implicit declarations and matches constructors.
class ImplicitCtorVisitor
: public ExpectedLocationVisitor<ImplicitCtorVisitor> {
public:
bool shouldVisitImplicitCode() const { return true; }
bool VisitCXXConstructorDecl(CXXConstructorDecl* Ctor) {
if (Ctor->isImplicit()) { // Was not written in source code
if (const CXXRecordDecl* Class = Ctor->getParent()) {
Match(Class->getName(), Ctor->getLocation());
}
}
return true;
}
};
TEST(RecursiveASTVisitor, VisitsImplicitCopyConstructors) {
ImplicitCtorVisitor Visitor;
Visitor.ExpectMatch("Simple", 2, 8);
// Note: Clang lazily instantiates implicit declarations, so we need
// to use them in order to force them to appear in the AST.
EXPECT_TRUE(Visitor.runOver(
"struct WithCtor { WithCtor(); }; \n"
"struct Simple { Simple(); WithCtor w; }; \n"
"int main() { Simple s; Simple t(s); }\n"));
}
/// \brief A visitor that optionally includes implicit code and matches
/// CXXConstructExpr.
///
/// The name recorded for the match is the name of the class whose constructor
/// is invoked by the CXXConstructExpr, not the name of the class whose
/// constructor the CXXConstructExpr is contained in.
class ConstructExprVisitor
: public ExpectedLocationVisitor<ConstructExprVisitor> {
public:
ConstructExprVisitor() : ShouldVisitImplicitCode(false) {}
bool shouldVisitImplicitCode() const { return ShouldVisitImplicitCode; }
void setShouldVisitImplicitCode(bool NewValue) {
ShouldVisitImplicitCode = NewValue;
}
bool VisitCXXConstructExpr(CXXConstructExpr* Expr) {
if (const CXXConstructorDecl* Ctor = Expr->getConstructor()) {
if (const CXXRecordDecl* Class = Ctor->getParent()) {
Match(Class->getName(), Expr->getLocation());
}
}
return true;
}
private:
bool ShouldVisitImplicitCode;
};
TEST(RecursiveASTVisitor, CanVisitImplicitMemberInitializations) {
ConstructExprVisitor Visitor;
Visitor.setShouldVisitImplicitCode(true);
Visitor.ExpectMatch("WithCtor", 2, 8);
// Simple has a constructor that implicitly initializes 'w'. Test
// that a visitor that visits implicit code visits that initialization.
// Note: Clang lazily instantiates implicit declarations, so we need
// to use them in order to force them to appear in the AST.
EXPECT_TRUE(Visitor.runOver(
"struct WithCtor { WithCtor(); }; \n"
"struct Simple { WithCtor w; }; \n"
"int main() { Simple s; }\n"));
}
// The same as CanVisitImplicitMemberInitializations, but checking that the
// visits are omitted when the visitor does not include implicit code.
TEST(RecursiveASTVisitor, CanSkipImplicitMemberInitializations) {
ConstructExprVisitor Visitor;
Visitor.setShouldVisitImplicitCode(false);
Visitor.DisallowMatch("WithCtor", 2, 8);
// Simple has a constructor that implicitly initializes 'w'. Test
// that a visitor that skips implicit code skips that initialization.
// Note: Clang lazily instantiates implicit declarations, so we need
// to use them in order to force them to appear in the AST.
EXPECT_TRUE(Visitor.runOver(
"struct WithCtor { WithCtor(); }; \n"
"struct Simple { WithCtor w; }; \n"
"int main() { Simple s; }\n"));
}
class DeclRefExprVisitor : public ExpectedLocationVisitor<DeclRefExprVisitor> {
public:
bool VisitDeclRefExpr(DeclRefExpr *Reference) {
Match(Reference->getNameInfo().getAsString(), Reference->getLocation());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArguments) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 2, 3);
EXPECT_TRUE(Visitor.runOver(
"void x(); template <void (*T)()> class X {};\nX<x> y;"));
}
TEST(RecursiveASTVisitor, VisitsCXXForRangeStmtRange) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 2, 25);
Visitor.ExpectMatch("x", 2, 30);
EXPECT_TRUE(Visitor.runOver(
"int x[5];\n"
"void f() { for (int i : x) { x[0] = 1; } }",
DeclRefExprVisitor::Lang_CXX11));
}
TEST(RecursiveASTVisitor, VisitsCallExpr) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 1, 22);
EXPECT_TRUE(Visitor.runOver(
"void x(); void y() { x(); }"));
}
/* FIXME: According to Richard Smith this is a bug in the AST.
TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArgumentsInInstantiation) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 3, 43);
EXPECT_TRUE(Visitor.runOver(
"template <typename T> void x();\n"
"template <void (*T)()> class X {};\n"
"template <typename T> class Y : public X< x<T> > {};\n"
"Y<int> y;"));
}
*/
TEST(RecursiveASTVisitor, VisitsExtension) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("s", 1, 24);
EXPECT_TRUE(Visitor.runOver(
"int s = __extension__ (s);\n"));
}
TEST(RecursiveASTVisitor, VisitsCopyExprOfBlockDeclCapture) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 3, 24);
EXPECT_TRUE(Visitor.runOver("void f(int(^)(int)); \n"
"void g() { \n"
" f([&](int x){ return x; }); \n"
"}",
DeclRefExprVisitor::Lang_OBJCXX11));
}
} // end anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Tooling/ReplacementsYamlTest.cpp
|
//===- unittests/Tooling/ReplacementsYamlTest.cpp - Serialization tests ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Tests for serialization of Replacements.
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/ReplacementsYaml.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang::tooling;
TEST(ReplacementsYamlTest, serializesReplacements) {
TranslationUnitReplacements Doc;
Doc.MainSourceFile = "/path/to/source.cpp";
Doc.Context = "some context";
Doc.Replacements
.push_back(Replacement("/path/to/file1.h", 232, 56, "replacement #1"));
Doc.Replacements
.push_back(Replacement("/path/to/file2.h", 301, 2, "replacement #2"));
std::string YamlContent;
llvm::raw_string_ostream YamlContentStream(YamlContent);
yaml::Output YAML(YamlContentStream);
YAML << Doc;
// NOTE: If this test starts to fail for no obvious reason, check whitespace.
ASSERT_STREQ("---\n"
"MainSourceFile: /path/to/source.cpp\n"
"Context: some context\n"
"Replacements: \n" // Extra whitespace here!
" - FilePath: /path/to/file1.h\n"
" Offset: 232\n"
" Length: 56\n"
" ReplacementText: 'replacement #1'\n"
" - FilePath: /path/to/file2.h\n"
" Offset: 301\n"
" Length: 2\n"
" ReplacementText: 'replacement #2'\n"
"...\n",
YamlContentStream.str().c_str());
}
TEST(ReplacementsYamlTest, deserializesReplacements) {
std::string YamlContent = "---\n"
"MainSourceFile: /path/to/source.cpp\n"
"Context: some context\n"
"Replacements:\n"
" - FilePath: /path/to/file1.h\n"
" Offset: 232\n"
" Length: 56\n"
" ReplacementText: 'replacement #1'\n"
" - FilePath: /path/to/file2.h\n"
" Offset: 301\n"
" Length: 2\n"
" ReplacementText: 'replacement #2'\n"
"...\n";
TranslationUnitReplacements DocActual;
yaml::Input YAML(YamlContent);
YAML >> DocActual;
ASSERT_FALSE(YAML.error());
ASSERT_EQ(2u, DocActual.Replacements.size());
ASSERT_EQ("/path/to/source.cpp", DocActual.MainSourceFile);
ASSERT_EQ("some context", DocActual.Context);
ASSERT_EQ("/path/to/file1.h", DocActual.Replacements[0].getFilePath());
ASSERT_EQ(232u, DocActual.Replacements[0].getOffset());
ASSERT_EQ(56u, DocActual.Replacements[0].getLength());
ASSERT_EQ("replacement #1", DocActual.Replacements[0].getReplacementText());
ASSERT_EQ("/path/to/file2.h", DocActual.Replacements[1].getFilePath());
ASSERT_EQ(301u, DocActual.Replacements[1].getOffset());
ASSERT_EQ(2u, DocActual.Replacements[1].getLength());
ASSERT_EQ("replacement #2", DocActual.Replacements[1].getReplacementText());
}
TEST(ReplacementsYamlTest, deserializesWithoutContext) {
// Make sure a doc can be read without the context field.
std::string YamlContent = "---\n"
"MainSourceFile: /path/to/source.cpp\n"
"Replacements:\n"
" - FilePath: target_file.h\n"
" Offset: 1\n"
" Length: 10\n"
" ReplacementText: replacement\n"
"...\n";
TranslationUnitReplacements DocActual;
yaml::Input YAML(YamlContent);
YAML >> DocActual;
ASSERT_FALSE(YAML.error());
ASSERT_EQ("/path/to/source.cpp", DocActual.MainSourceFile);
ASSERT_EQ(1u, DocActual.Replacements.size());
ASSERT_EQ(std::string(), DocActual.Context);
ASSERT_EQ("target_file.h", DocActual.Replacements[0].getFilePath());
ASSERT_EQ(1u, DocActual.Replacements[0].getOffset());
ASSERT_EQ(10u, DocActual.Replacements[0].getLength());
ASSERT_EQ("replacement", DocActual.Replacements[0].getReplacementText());
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Lex/LexerTest.cpp
|
//===- unittests/Lex/LexerTest.cpp ------ Lexer tests ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/Lexer.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
class VoidModuleLoader : public ModuleLoader {
ModuleLoadResult loadModule(SourceLocation ImportLoc,
ModuleIdPath Path,
Module::NameVisibilityKind Visibility,
bool IsInclusionDirective) override {
return ModuleLoadResult();
}
void makeModuleVisible(Module *Mod,
Module::NameVisibilityKind Visibility,
SourceLocation ImportLoc) override { }
GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
{ return nullptr; }
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
{ return 0; };
};
// The test fixture.
class LexerTest : public ::testing::Test {
protected:
LexerTest()
: FileMgr(FileMgrOpts),
DiagID(new DiagnosticIDs()),
Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
SourceMgr(Diags, FileMgr),
TargetOpts(new TargetOptions)
{
TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
}
std::vector<Token> CheckLex(StringRef Source,
ArrayRef<tok::TokenKind> ExpectedTokens) {
std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Source);
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
VoidModuleLoader ModLoader;
HeaderSearch HeaderInfo(new HeaderSearchOptions, SourceMgr, Diags, LangOpts,
Target.get());
Preprocessor PP(new PreprocessorOptions(), Diags, LangOpts, SourceMgr,
HeaderInfo, ModLoader, /*IILookup =*/nullptr,
/*OwnsHeaderSearch =*/false);
PP.Initialize(*Target);
PP.EnterMainSourceFile();
std::vector<Token> toks;
while (1) {
Token tok;
PP.Lex(tok);
if (tok.is(tok::eof))
break;
toks.push_back(tok);
}
EXPECT_EQ(ExpectedTokens.size(), toks.size());
for (unsigned i = 0, e = ExpectedTokens.size(); i != e; ++i) {
EXPECT_EQ(ExpectedTokens[i], toks[i].getKind());
}
return toks;
}
std::string getSourceText(Token Begin, Token End) {
bool Invalid;
StringRef Str =
Lexer::getSourceText(CharSourceRange::getTokenRange(SourceRange(
Begin.getLocation(), End.getLocation())),
SourceMgr, LangOpts, &Invalid);
if (Invalid)
return "<INVALID>";
return Str;
}
FileSystemOptions FileMgrOpts;
FileManager FileMgr;
IntrusiveRefCntPtr<DiagnosticIDs> DiagID;
DiagnosticsEngine Diags;
SourceManager SourceMgr;
LangOptions LangOpts;
std::shared_ptr<TargetOptions> TargetOpts;
IntrusiveRefCntPtr<TargetInfo> Target;
};
TEST_F(LexerTest, GetSourceTextExpandsToMaximumInMacroArgument) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::l_paren);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_paren);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"M(f(M(i)))",
ExpectedTokens);
EXPECT_EQ("M(i)", getSourceText(toks[2], toks[2]));
}
TEST_F(LexerTest, GetSourceTextExpandsToMaximumInMacroArgumentForEndOfMacro) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"M(M(i) c)",
ExpectedTokens);
EXPECT_EQ("M(i)", getSourceText(toks[0], toks[0]));
}
TEST_F(LexerTest, GetSourceTextExpandsInMacroArgumentForBeginOfMacro) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"M(c c M(i))",
ExpectedTokens);
EXPECT_EQ("c M(i)", getSourceText(toks[1], toks[2]));
}
TEST_F(LexerTest, GetSourceTextExpandsInMacroArgumentForEndOfMacro) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"M(M(i) c c)",
ExpectedTokens);
EXPECT_EQ("M(i) c", getSourceText(toks[0], toks[1]));
}
TEST_F(LexerTest, GetSourceTextInSeparateFnMacros) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"M(c M(i)) M(M(i) c)",
ExpectedTokens);
EXPECT_EQ("<INVALID>", getSourceText(toks[1], toks[2]));
}
TEST_F(LexerTest, GetSourceTextWorksAcrossTokenPastes) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::l_paren);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_paren);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"#define C(x) M(x##c)\n"
"M(f(C(i)))",
ExpectedTokens);
EXPECT_EQ("C(i)", getSourceText(toks[2], toks[2]));
}
TEST_F(LexerTest, GetSourceTextExpandsAcrossMultipleMacroCalls) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::l_paren);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_paren);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"f(M(M(i)))",
ExpectedTokens);
EXPECT_EQ("M(M(i))", getSourceText(toks[2], toks[2]));
}
TEST_F(LexerTest, GetSourceTextInMiddleOfMacroArgument) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::l_paren);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_paren);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"M(f(i))",
ExpectedTokens);
EXPECT_EQ("i", getSourceText(toks[2], toks[2]));
}
TEST_F(LexerTest, GetSourceTextExpandsAroundDifferentMacroCalls) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::l_paren);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_paren);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"#define C(x) x\n"
"f(C(M(i)))",
ExpectedTokens);
EXPECT_EQ("C(M(i))", getSourceText(toks[2], toks[2]));
}
TEST_F(LexerTest, GetSourceTextOnlyExpandsIfFirstTokenInMacro) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::l_paren);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_paren);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"#define C(x) c x\n"
"f(C(M(i)))",
ExpectedTokens);
EXPECT_EQ("M(i)", getSourceText(toks[3], toks[3]));
}
TEST_F(LexerTest, GetSourceTextExpandsRecursively) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::l_paren);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_paren);
std::vector<Token> toks = CheckLex("#define M(x) x\n"
"#define C(x) c M(x)\n"
"C(f(M(i)))",
ExpectedTokens);
EXPECT_EQ("M(i)", getSourceText(toks[3], toks[3]));
}
TEST_F(LexerTest, LexAPI) {
std::vector<tok::TokenKind> ExpectedTokens;
ExpectedTokens.push_back(tok::l_square);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_square);
ExpectedTokens.push_back(tok::l_square);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::r_square);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
ExpectedTokens.push_back(tok::identifier);
std::vector<Token> toks = CheckLex("#define M(x) [x]\n"
"#define N(x) x\n"
"#define INN(x) x\n"
"#define NOF1 INN(val)\n"
"#define NOF2 val\n"
"M(foo) N([bar])\n"
"N(INN(val)) N(NOF1) N(NOF2) N(val)",
ExpectedTokens);
SourceLocation lsqrLoc = toks[0].getLocation();
SourceLocation idLoc = toks[1].getLocation();
SourceLocation rsqrLoc = toks[2].getLocation();
std::pair<SourceLocation,SourceLocation>
macroPair = SourceMgr.getExpansionRange(lsqrLoc);
SourceRange macroRange = SourceRange(macroPair.first, macroPair.second);
SourceLocation Loc;
EXPECT_TRUE(Lexer::isAtStartOfMacroExpansion(lsqrLoc, SourceMgr, LangOpts, &Loc));
EXPECT_EQ(Loc, macroRange.getBegin());
EXPECT_FALSE(Lexer::isAtStartOfMacroExpansion(idLoc, SourceMgr, LangOpts));
EXPECT_FALSE(Lexer::isAtEndOfMacroExpansion(idLoc, SourceMgr, LangOpts));
EXPECT_TRUE(Lexer::isAtEndOfMacroExpansion(rsqrLoc, SourceMgr, LangOpts, &Loc));
EXPECT_EQ(Loc, macroRange.getEnd());
CharSourceRange range = Lexer::makeFileCharRange(
CharSourceRange::getTokenRange(lsqrLoc, idLoc), SourceMgr, LangOpts);
EXPECT_TRUE(range.isInvalid());
range = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(idLoc, rsqrLoc),
SourceMgr, LangOpts);
EXPECT_TRUE(range.isInvalid());
range = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(lsqrLoc, rsqrLoc),
SourceMgr, LangOpts);
EXPECT_TRUE(!range.isTokenRange());
EXPECT_EQ(range.getAsRange(),
SourceRange(macroRange.getBegin(),
macroRange.getEnd().getLocWithOffset(1)));
StringRef text = Lexer::getSourceText(
CharSourceRange::getTokenRange(lsqrLoc, rsqrLoc),
SourceMgr, LangOpts);
EXPECT_EQ(text, "M(foo)");
SourceLocation macroLsqrLoc = toks[3].getLocation();
SourceLocation macroIdLoc = toks[4].getLocation();
SourceLocation macroRsqrLoc = toks[5].getLocation();
SourceLocation fileLsqrLoc = SourceMgr.getSpellingLoc(macroLsqrLoc);
SourceLocation fileIdLoc = SourceMgr.getSpellingLoc(macroIdLoc);
SourceLocation fileRsqrLoc = SourceMgr.getSpellingLoc(macroRsqrLoc);
range = Lexer::makeFileCharRange(
CharSourceRange::getTokenRange(macroLsqrLoc, macroIdLoc),
SourceMgr, LangOpts);
EXPECT_EQ(SourceRange(fileLsqrLoc, fileIdLoc.getLocWithOffset(3)),
range.getAsRange());
range = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(macroIdLoc, macroRsqrLoc),
SourceMgr, LangOpts);
EXPECT_EQ(SourceRange(fileIdLoc, fileRsqrLoc.getLocWithOffset(1)),
range.getAsRange());
macroPair = SourceMgr.getExpansionRange(macroLsqrLoc);
range = Lexer::makeFileCharRange(
CharSourceRange::getTokenRange(macroLsqrLoc, macroRsqrLoc),
SourceMgr, LangOpts);
EXPECT_EQ(SourceRange(macroPair.first, macroPair.second.getLocWithOffset(1)),
range.getAsRange());
text = Lexer::getSourceText(
CharSourceRange::getTokenRange(SourceRange(macroLsqrLoc, macroIdLoc)),
SourceMgr, LangOpts);
EXPECT_EQ(text, "[bar");
SourceLocation idLoc1 = toks[6].getLocation();
SourceLocation idLoc2 = toks[7].getLocation();
SourceLocation idLoc3 = toks[8].getLocation();
SourceLocation idLoc4 = toks[9].getLocation();
EXPECT_EQ("INN", Lexer::getImmediateMacroName(idLoc1, SourceMgr, LangOpts));
EXPECT_EQ("INN", Lexer::getImmediateMacroName(idLoc2, SourceMgr, LangOpts));
EXPECT_EQ("NOF2", Lexer::getImmediateMacroName(idLoc3, SourceMgr, LangOpts));
EXPECT_EQ("N", Lexer::getImmediateMacroName(idLoc4, SourceMgr, LangOpts));
}
} // anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Lex/PPCallbacksTest.cpp
|
//===- unittests/Lex/PPCallbacksTest.cpp - PPCallbacks tests ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===--------------------------------------------------------------===//
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Parse/Parser.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Path.h"
#include "gtest/gtest.h"
using namespace clang;
namespace {
// Stub out module loading.
class VoidModuleLoader : public ModuleLoader {
ModuleLoadResult loadModule(SourceLocation ImportLoc,
ModuleIdPath Path,
Module::NameVisibilityKind Visibility,
bool IsInclusionDirective) override {
return ModuleLoadResult();
}
void makeModuleVisible(Module *Mod,
Module::NameVisibilityKind Visibility,
SourceLocation ImportLoc) override { }
GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
{ return nullptr; }
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
{ return 0; };
};
// Stub to collect data from InclusionDirective callbacks.
class InclusionDirectiveCallbacks : public PPCallbacks {
public:
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange, const FileEntry *File,
StringRef SearchPath, StringRef RelativePath,
const Module *Imported) override {
this->HashLoc = HashLoc;
this->IncludeTok = IncludeTok;
this->FileName = FileName.str();
this->IsAngled = IsAngled;
this->FilenameRange = FilenameRange;
this->File = File;
this->SearchPath = SearchPath.str();
this->RelativePath = RelativePath.str();
this->Imported = Imported;
}
SourceLocation HashLoc;
Token IncludeTok;
SmallString<16> FileName;
bool IsAngled;
CharSourceRange FilenameRange;
const FileEntry* File;
SmallString<16> SearchPath;
SmallString<16> RelativePath;
const Module* Imported;
};
// Stub to collect data from PragmaOpenCLExtension callbacks.
class PragmaOpenCLExtensionCallbacks : public PPCallbacks {
public:
typedef struct {
SmallString<16> Name;
unsigned State;
} CallbackParameters;
PragmaOpenCLExtensionCallbacks() : Name("Not called."), State(99) {};
void PragmaOpenCLExtension(clang::SourceLocation NameLoc,
const clang::IdentifierInfo *Name,
clang::SourceLocation StateLoc,
unsigned State) override {
this->NameLoc = NameLoc;
this->Name = Name->getName();
this->StateLoc = StateLoc;
this->State = State;
};
SourceLocation NameLoc;
SmallString<16> Name;
SourceLocation StateLoc;
unsigned State;
};
// PPCallbacks test fixture.
class PPCallbacksTest : public ::testing::Test {
protected:
PPCallbacksTest()
: FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()),
DiagOpts(new DiagnosticOptions()),
Diags(DiagID, DiagOpts.get(), new IgnoringDiagConsumer()),
SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions()) {
TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
}
FileSystemOptions FileMgrOpts;
FileManager FileMgr;
IntrusiveRefCntPtr<DiagnosticIDs> DiagID;
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
DiagnosticsEngine Diags;
SourceManager SourceMgr;
LangOptions LangOpts;
std::shared_ptr<TargetOptions> TargetOpts;
IntrusiveRefCntPtr<TargetInfo> Target;
// Register a header path as a known file and add its location
// to search path.
void AddFakeHeader(HeaderSearch& HeaderInfo, const char* HeaderPath,
bool IsSystemHeader) {
// Tell FileMgr about header.
FileMgr.getVirtualFile(HeaderPath, 0, 0);
// Add header's parent path to search path.
StringRef SearchPath = llvm::sys::path::parent_path(HeaderPath);
const DirectoryEntry *DE = FileMgr.getDirectory(SearchPath);
DirectoryLookup DL(DE, SrcMgr::C_User, false);
HeaderInfo.AddSearchPath(DL, IsSystemHeader);
}
// Get the raw source string of the range.
StringRef GetSourceString(CharSourceRange Range) {
const char* B = SourceMgr.getCharacterData(Range.getBegin());
const char* E = SourceMgr.getCharacterData(Range.getEnd());
return StringRef(B, E - B);
}
// Run lexer over SourceText and collect FilenameRange from
// the InclusionDirective callback.
CharSourceRange InclusionDirectiveFilenameRange(const char* SourceText,
const char* HeaderPath, bool SystemHeader) {
std::unique_ptr<llvm::MemoryBuffer> Buf =
llvm::MemoryBuffer::getMemBuffer(SourceText);
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
VoidModuleLoader ModLoader;
IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts = new HeaderSearchOptions();
HeaderSearch HeaderInfo(HSOpts, SourceMgr, Diags, LangOpts,
Target.get());
AddFakeHeader(HeaderInfo, HeaderPath, SystemHeader);
IntrusiveRefCntPtr<PreprocessorOptions> PPOpts = new PreprocessorOptions();
Preprocessor PP(PPOpts, Diags, LangOpts, SourceMgr, HeaderInfo, ModLoader,
/*IILookup =*/nullptr,
/*OwnsHeaderSearch =*/false);
PP.Initialize(*Target);
InclusionDirectiveCallbacks* Callbacks = new InclusionDirectiveCallbacks;
PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
// Lex source text.
PP.EnterMainSourceFile();
while (true) {
Token Tok;
PP.Lex(Tok);
if (Tok.is(tok::eof))
break;
}
// Callbacks have been executed at this point -- return filename range.
return Callbacks->FilenameRange;
}
PragmaOpenCLExtensionCallbacks::CallbackParameters
PragmaOpenCLExtensionCall(const char* SourceText) {
LangOptions OpenCLLangOpts;
// OpenCLLangOpts.OpenCL = 1; HLSL Change - This is hard set
std::unique_ptr<llvm::MemoryBuffer> SourceBuf =
llvm::MemoryBuffer::getMemBuffer(SourceText, "test.cl");
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(SourceBuf)));
VoidModuleLoader ModLoader;
HeaderSearch HeaderInfo(new HeaderSearchOptions, SourceMgr, Diags,
OpenCLLangOpts, Target.get());
Preprocessor PP(new PreprocessorOptions(), Diags, OpenCLLangOpts, SourceMgr,
HeaderInfo, ModLoader, /*IILookup =*/nullptr,
/*OwnsHeaderSearch =*/false);
PP.Initialize(*Target);
// parser actually sets correct pragma handlers for preprocessor
// according to LangOptions, so we init Parser to register opencl
// pragma handlers
ASTContext Context(OpenCLLangOpts, SourceMgr,
PP.getIdentifierTable(), PP.getSelectorTable(),
PP.getBuiltinInfo());
Context.InitBuiltinTypes(*Target);
ASTConsumer Consumer;
Sema S(PP, Context, Consumer);
Parser P(PP, S, false);
PragmaOpenCLExtensionCallbacks* Callbacks = new PragmaOpenCLExtensionCallbacks;
PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
// Lex source text.
PP.EnterMainSourceFile();
while (true) {
Token Tok;
PP.Lex(Tok);
if (Tok.is(tok::eof))
break;
}
PragmaOpenCLExtensionCallbacks::CallbackParameters RetVal = {
Callbacks->Name,
Callbacks->State
};
return RetVal;
}
};
TEST_F(PPCallbacksTest, QuotedFilename) {
const char* Source =
"#include \"quoted.h\"\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/quoted.h", false);
ASSERT_EQ("\"quoted.h\"", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, AngledFilename) {
const char* Source =
"#include <angled.h>\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/angled.h", true);
ASSERT_EQ("<angled.h>", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, QuotedInMacro) {
const char* Source =
"#define MACRO_QUOTED \"quoted.h\"\n"
"#include MACRO_QUOTED\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/quoted.h", false);
ASSERT_EQ("\"quoted.h\"", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, AngledInMacro) {
const char* Source =
"#define MACRO_ANGLED <angled.h>\n"
"#include MACRO_ANGLED\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/angled.h", true);
ASSERT_EQ("<angled.h>", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, StringizedMacroArgument) {
const char* Source =
"#define MACRO_STRINGIZED(x) #x\n"
"#include MACRO_STRINGIZED(quoted.h)\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/quoted.h", false);
ASSERT_EQ("\"quoted.h\"", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, ConcatenatedMacroArgument) {
const char* Source =
"#define MACRO_ANGLED <angled.h>\n"
"#define MACRO_CONCAT(x, y) x ## _ ## y\n"
"#include MACRO_CONCAT(MACRO, ANGLED)\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/angled.h", false);
ASSERT_EQ("<angled.h>", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, TrigraphFilename) {
const char* Source =
"#include \"tri\?\?-graph.h\"\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/tri~graph.h", false);
ASSERT_EQ("\"tri\?\?-graph.h\"", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, TrigraphInMacro) {
const char* Source =
"#define MACRO_TRIGRAPH \"tri\?\?-graph.h\"\n"
"#include MACRO_TRIGRAPH\n";
CharSourceRange Range =
InclusionDirectiveFilenameRange(Source, "/tri~graph.h", false);
ASSERT_EQ("\"tri\?\?-graph.h\"", GetSourceString(Range));
}
TEST_F(PPCallbacksTest, DISABLED_OpenCLExtensionPragmaEnabled) { // HLSL Change
const char* Source =
"#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n";
PragmaOpenCLExtensionCallbacks::CallbackParameters Parameters =
PragmaOpenCLExtensionCall(Source);
ASSERT_EQ("cl_khr_fp64", Parameters.Name);
unsigned ExpectedState = 1;
ASSERT_EQ(ExpectedState, Parameters.State);
}
TEST_F(PPCallbacksTest, DISABLED_OpenCLExtensionPragmaDisabled) { // HLSL Change
const char* Source =
"#pragma OPENCL EXTENSION cl_khr_fp16 : disable\n";
PragmaOpenCLExtensionCallbacks::CallbackParameters Parameters =
PragmaOpenCLExtensionCall(Source);
ASSERT_EQ("cl_khr_fp16", Parameters.Name);
unsigned ExpectedState = 0;
ASSERT_EQ(ExpectedState, Parameters.State);
}
} // anonoymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Lex/CMakeLists.txt
|
set(LLVM_LINK_COMPONENTS
Support
)
add_clang_unittest(LexTests
LexerTest.cpp
PPCallbacksTest.cpp
PPConditionalDirectiveRecordTest.cpp
)
target_link_libraries(LexTests
clangAST
clangBasic
clangLex
clangParse
clangSema
)
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp
|
//===- unittests/Lex/PPConditionalDirectiveRecordTest.cpp-PP directive tests =//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/PPConditionalDirectiveRecord.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
// The test fixture.
class PPConditionalDirectiveRecordTest : public ::testing::Test {
protected:
PPConditionalDirectiveRecordTest()
: FileMgr(FileMgrOpts),
DiagID(new DiagnosticIDs()),
Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
SourceMgr(Diags, FileMgr),
TargetOpts(new TargetOptions)
{
TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
}
FileSystemOptions FileMgrOpts;
FileManager FileMgr;
IntrusiveRefCntPtr<DiagnosticIDs> DiagID;
DiagnosticsEngine Diags;
SourceManager SourceMgr;
LangOptions LangOpts;
std::shared_ptr<TargetOptions> TargetOpts;
IntrusiveRefCntPtr<TargetInfo> Target;
};
class VoidModuleLoader : public ModuleLoader {
ModuleLoadResult loadModule(SourceLocation ImportLoc,
ModuleIdPath Path,
Module::NameVisibilityKind Visibility,
bool IsInclusionDirective) override {
return ModuleLoadResult();
}
void makeModuleVisible(Module *Mod,
Module::NameVisibilityKind Visibility,
SourceLocation ImportLoc) override { }
GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
{ return nullptr; }
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
{ return 0; };
};
TEST_F(PPConditionalDirectiveRecordTest, PPRecAPI) {
const char *source =
"0 1\n"
"#if 1\n"
"2\n"
"#ifndef BB\n"
"3 4\n"
"#else\n"
"#endif\n"
"5\n"
"#endif\n"
"6\n"
"#if 1\n"
"7\n"
"#if 1\n"
"#endif\n"
"8\n"
"#endif\n"
"9\n";
std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(source);
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
VoidModuleLoader ModLoader;
HeaderSearch HeaderInfo(new HeaderSearchOptions, SourceMgr, Diags, LangOpts,
Target.get());
Preprocessor PP(new PreprocessorOptions(), Diags, LangOpts, SourceMgr,
HeaderInfo, ModLoader,
/*IILookup =*/nullptr,
/*OwnsHeaderSearch =*/false);
PP.Initialize(*Target);
PPConditionalDirectiveRecord *
PPRec = new PPConditionalDirectiveRecord(SourceMgr);
PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
PP.EnterMainSourceFile();
std::vector<Token> toks;
while (1) {
Token tok;
PP.Lex(tok);
if (tok.is(tok::eof))
break;
toks.push_back(tok);
}
// Make sure we got the tokens that we expected.
ASSERT_EQ(10U, toks.size());
EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[0].getLocation(), toks[1].getLocation())));
EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[0].getLocation(), toks[2].getLocation())));
EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[3].getLocation(), toks[4].getLocation())));
EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[1].getLocation(), toks[5].getLocation())));
EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[2].getLocation(), toks[6].getLocation())));
EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[2].getLocation(), toks[5].getLocation())));
EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[0].getLocation(), toks[6].getLocation())));
EXPECT_TRUE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[2].getLocation(), toks[8].getLocation())));
EXPECT_FALSE(PPRec->rangeIntersectsConditionalDirective(
SourceRange(toks[0].getLocation(), toks[9].getLocation())));
EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion(
toks[0].getLocation(), toks[2].getLocation()));
EXPECT_FALSE(PPRec->areInDifferentConditionalDirectiveRegion(
toks[3].getLocation(), toks[4].getLocation()));
EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion(
toks[1].getLocation(), toks[5].getLocation()));
EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion(
toks[2].getLocation(), toks[0].getLocation()));
EXPECT_FALSE(PPRec->areInDifferentConditionalDirectiveRegion(
toks[4].getLocation(), toks[3].getLocation()));
EXPECT_TRUE(PPRec->areInDifferentConditionalDirectiveRegion(
toks[5].getLocation(), toks[1].getLocation()));
}
} // anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Basic/SourceManagerTest.cpp
|
//===- unittests/Basic/SourceManagerTest.cpp ------ SourceManager tests ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/llvm-config.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
// The test fixture.
class SourceManagerTest : public ::testing::Test {
protected:
SourceManagerTest()
: FileMgr(FileMgrOpts),
DiagID(new DiagnosticIDs()),
Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
SourceMgr(Diags, FileMgr),
TargetOpts(new TargetOptions) {
TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
}
FileSystemOptions FileMgrOpts;
FileManager FileMgr;
IntrusiveRefCntPtr<DiagnosticIDs> DiagID;
DiagnosticsEngine Diags;
SourceManager SourceMgr;
LangOptions LangOpts;
std::shared_ptr<TargetOptions> TargetOpts;
IntrusiveRefCntPtr<TargetInfo> Target;
};
class VoidModuleLoader : public ModuleLoader {
ModuleLoadResult loadModule(SourceLocation ImportLoc,
ModuleIdPath Path,
Module::NameVisibilityKind Visibility,
bool IsInclusionDirective) override {
return ModuleLoadResult();
}
void makeModuleVisible(Module *Mod,
Module::NameVisibilityKind Visibility,
SourceLocation ImportLoc) override { }
GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
{ return nullptr; }
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
{ return 0; };
};
TEST_F(SourceManagerTest, isBeforeInTranslationUnit) {
const char *source =
"#define M(x) [x]\n"
"M(foo)";
std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(source);
FileID mainFileID = SourceMgr.createFileID(std::move(Buf));
SourceMgr.setMainFileID(mainFileID);
VoidModuleLoader ModLoader;
HeaderSearch HeaderInfo(new HeaderSearchOptions, SourceMgr, Diags, LangOpts,
&*Target);
Preprocessor PP(new PreprocessorOptions(), Diags, LangOpts, SourceMgr,
HeaderInfo, ModLoader,
/*IILookup =*/nullptr,
/*OwnsHeaderSearch =*/false);
PP.Initialize(*Target);
PP.EnterMainSourceFile();
std::vector<Token> toks;
while (1) {
Token tok;
PP.Lex(tok);
if (tok.is(tok::eof))
break;
toks.push_back(tok);
}
// Make sure we got the tokens that we expected.
ASSERT_EQ(3U, toks.size());
ASSERT_EQ(tok::l_square, toks[0].getKind());
ASSERT_EQ(tok::identifier, toks[1].getKind());
ASSERT_EQ(tok::r_square, toks[2].getKind());
SourceLocation lsqrLoc = toks[0].getLocation();
SourceLocation idLoc = toks[1].getLocation();
SourceLocation rsqrLoc = toks[2].getLocation();
SourceLocation macroExpStartLoc = SourceMgr.translateLineCol(mainFileID, 2, 1);
SourceLocation macroExpEndLoc = SourceMgr.translateLineCol(mainFileID, 2, 6);
ASSERT_TRUE(macroExpStartLoc.isFileID());
ASSERT_TRUE(macroExpEndLoc.isFileID());
SmallString<32> str;
ASSERT_EQ("M", PP.getSpelling(macroExpStartLoc, str));
ASSERT_EQ(")", PP.getSpelling(macroExpEndLoc, str));
EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(lsqrLoc, idLoc));
EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(idLoc, rsqrLoc));
EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(macroExpStartLoc, idLoc));
EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(idLoc, macroExpEndLoc));
}
TEST_F(SourceManagerTest, getColumnNumber) {
const char *Source =
"int x;\n"
"int y;";
std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Source);
FileID MainFileID = SourceMgr.createFileID(std::move(Buf));
SourceMgr.setMainFileID(MainFileID);
bool Invalid;
Invalid = false;
EXPECT_EQ(1U, SourceMgr.getColumnNumber(MainFileID, 0, &Invalid));
EXPECT_TRUE(!Invalid);
Invalid = false;
EXPECT_EQ(5U, SourceMgr.getColumnNumber(MainFileID, 4, &Invalid));
EXPECT_TRUE(!Invalid);
Invalid = false;
EXPECT_EQ(1U, SourceMgr.getColumnNumber(MainFileID, 7, &Invalid));
EXPECT_TRUE(!Invalid);
Invalid = false;
EXPECT_EQ(5U, SourceMgr.getColumnNumber(MainFileID, 11, &Invalid));
EXPECT_TRUE(!Invalid);
Invalid = false;
EXPECT_EQ(7U, SourceMgr.getColumnNumber(MainFileID, strlen(Source),
&Invalid));
EXPECT_TRUE(!Invalid);
Invalid = false;
SourceMgr.getColumnNumber(MainFileID, strlen(Source)+1, &Invalid);
EXPECT_TRUE(Invalid);
// Test invalid files
Invalid = false;
SourceMgr.getColumnNumber(FileID(), 0, &Invalid);
EXPECT_TRUE(Invalid);
Invalid = false;
SourceMgr.getColumnNumber(FileID(), 1, &Invalid);
EXPECT_TRUE(Invalid);
// Test with no invalid flag.
EXPECT_EQ(1U, SourceMgr.getColumnNumber(MainFileID, 0, nullptr));
}
#if defined(LLVM_ON_UNIX)
TEST_F(SourceManagerTest, getMacroArgExpandedLocation) {
const char *header =
"#define FM(x,y) x\n";
const char *main =
"#include \"/test-header.h\"\n"
"#define VAL 0\n"
"FM(VAL,0)\n"
"FM(0,VAL)\n"
"FM(FM(0,VAL),0)\n"
"#define CONCAT(X, Y) X##Y\n"
"CONCAT(1,1)\n";
std::unique_ptr<MemoryBuffer> HeaderBuf = MemoryBuffer::getMemBuffer(header);
std::unique_ptr<MemoryBuffer> MainBuf = MemoryBuffer::getMemBuffer(main);
FileID mainFileID = SourceMgr.createFileID(std::move(MainBuf));
SourceMgr.setMainFileID(mainFileID);
const FileEntry *headerFile = FileMgr.getVirtualFile("/test-header.h",
HeaderBuf->getBufferSize(), 0);
SourceMgr.overrideFileContents(headerFile, std::move(HeaderBuf));
VoidModuleLoader ModLoader;
HeaderSearch HeaderInfo(new HeaderSearchOptions, SourceMgr, Diags, LangOpts,
&*Target);
Preprocessor PP(new PreprocessorOptions(), Diags, LangOpts, SourceMgr,
HeaderInfo, ModLoader,
/*IILookup =*/nullptr,
/*OwnsHeaderSearch =*/false);
PP.Initialize(*Target);
PP.EnterMainSourceFile();
std::vector<Token> toks;
while (1) {
Token tok;
PP.Lex(tok);
if (tok.is(tok::eof))
break;
toks.push_back(tok);
}
// Make sure we got the tokens that we expected.
ASSERT_EQ(4U, toks.size());
ASSERT_EQ(tok::numeric_constant, toks[0].getKind());
ASSERT_EQ(tok::numeric_constant, toks[1].getKind());
ASSERT_EQ(tok::numeric_constant, toks[2].getKind());
ASSERT_EQ(tok::numeric_constant, toks[3].getKind());
SourceLocation defLoc = SourceMgr.translateLineCol(mainFileID, 2, 13);
SourceLocation loc1 = SourceMgr.translateLineCol(mainFileID, 3, 8);
SourceLocation loc2 = SourceMgr.translateLineCol(mainFileID, 4, 4);
SourceLocation loc3 = SourceMgr.translateLineCol(mainFileID, 5, 7);
SourceLocation defLoc2 = SourceMgr.translateLineCol(mainFileID, 6, 22);
defLoc = SourceMgr.getMacroArgExpandedLocation(defLoc);
loc1 = SourceMgr.getMacroArgExpandedLocation(loc1);
loc2 = SourceMgr.getMacroArgExpandedLocation(loc2);
loc3 = SourceMgr.getMacroArgExpandedLocation(loc3);
defLoc2 = SourceMgr.getMacroArgExpandedLocation(defLoc2);
EXPECT_TRUE(defLoc.isFileID());
EXPECT_TRUE(loc1.isFileID());
EXPECT_TRUE(SourceMgr.isMacroArgExpansion(loc2));
EXPECT_TRUE(SourceMgr.isMacroArgExpansion(loc3));
EXPECT_EQ(loc2, toks[1].getLocation());
EXPECT_EQ(loc3, toks[2].getLocation());
EXPECT_TRUE(defLoc2.isFileID());
}
namespace {
struct MacroAction {
SourceLocation Loc;
std::string Name;
bool isDefinition; // if false, it is expansion.
MacroAction(SourceLocation Loc, StringRef Name, bool isDefinition)
: Loc(Loc), Name(Name), isDefinition(isDefinition) { }
};
class MacroTracker : public PPCallbacks {
std::vector<MacroAction> &Macros;
public:
explicit MacroTracker(std::vector<MacroAction> &Macros) : Macros(Macros) { }
void MacroDefined(const Token &MacroNameTok,
const MacroDirective *MD) override {
Macros.push_back(MacroAction(MD->getLocation(),
MacroNameTok.getIdentifierInfo()->getName(),
true));
}
void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
SourceRange Range, const MacroArgs *Args) override {
Macros.push_back(MacroAction(MacroNameTok.getLocation(),
MacroNameTok.getIdentifierInfo()->getName(),
false));
}
};
}
TEST_F(SourceManagerTest, isBeforeInTranslationUnitWithMacroInInclude) {
const char *header =
"#define MACRO_IN_INCLUDE 0\n";
const char *main =
"#define M(x) x\n"
"#define INC \"/test-header.h\"\n"
"#include M(INC)\n"
"#define INC2 </test-header.h>\n"
"#include M(INC2)\n";
std::unique_ptr<MemoryBuffer> HeaderBuf = MemoryBuffer::getMemBuffer(header);
std::unique_ptr<MemoryBuffer> MainBuf = MemoryBuffer::getMemBuffer(main);
SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(MainBuf)));
const FileEntry *headerFile = FileMgr.getVirtualFile("/test-header.h",
HeaderBuf->getBufferSize(), 0);
SourceMgr.overrideFileContents(headerFile, std::move(HeaderBuf));
VoidModuleLoader ModLoader;
HeaderSearch HeaderInfo(new HeaderSearchOptions, SourceMgr, Diags, LangOpts,
&*Target);
Preprocessor PP(new PreprocessorOptions(), Diags, LangOpts, SourceMgr,
HeaderInfo, ModLoader,
/*IILookup =*/nullptr,
/*OwnsHeaderSearch =*/false);
PP.Initialize(*Target);
std::vector<MacroAction> Macros;
PP.addPPCallbacks(llvm::make_unique<MacroTracker>(Macros));
PP.EnterMainSourceFile();
std::vector<Token> toks;
while (1) {
Token tok;
PP.Lex(tok);
if (tok.is(tok::eof))
break;
toks.push_back(tok);
}
// Make sure we got the tokens that we expected.
ASSERT_EQ(0U, toks.size());
ASSERT_EQ(9U, Macros.size());
// #define M(x) x
ASSERT_TRUE(Macros[0].isDefinition);
ASSERT_EQ("M", Macros[0].Name);
// #define INC "/test-header.h"
ASSERT_TRUE(Macros[1].isDefinition);
ASSERT_EQ("INC", Macros[1].Name);
// M expansion in #include M(INC)
ASSERT_FALSE(Macros[2].isDefinition);
ASSERT_EQ("M", Macros[2].Name);
// INC expansion in #include M(INC)
ASSERT_FALSE(Macros[3].isDefinition);
ASSERT_EQ("INC", Macros[3].Name);
// #define MACRO_IN_INCLUDE 0
ASSERT_TRUE(Macros[4].isDefinition);
ASSERT_EQ("MACRO_IN_INCLUDE", Macros[4].Name);
// #define INC2 </test-header.h>
ASSERT_TRUE(Macros[5].isDefinition);
ASSERT_EQ("INC2", Macros[5].Name);
// M expansion in #include M(INC2)
ASSERT_FALSE(Macros[6].isDefinition);
ASSERT_EQ("M", Macros[6].Name);
// INC2 expansion in #include M(INC2)
ASSERT_FALSE(Macros[7].isDefinition);
ASSERT_EQ("INC2", Macros[7].Name);
// #define MACRO_IN_INCLUDE 0
ASSERT_TRUE(Macros[8].isDefinition);
ASSERT_EQ("MACRO_IN_INCLUDE", Macros[8].Name);
// The INC expansion in #include M(INC) comes before the first
// MACRO_IN_INCLUDE definition of the included file.
EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(Macros[3].Loc, Macros[4].Loc));
// The INC2 expansion in #include M(INC2) comes before the second
// MACRO_IN_INCLUDE definition of the included file.
EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(Macros[7].Loc, Macros[8].Loc));
}
#endif
} // anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Basic/VirtualFileSystemTest.cpp
|
//===- unittests/Basic/VirtualFileSystem.cpp ---------------- VFS tests ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/VirtualFileSystem.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "gtest/gtest.h"
#include <map>
using namespace clang;
using namespace llvm;
using llvm::sys::fs::UniqueID;
namespace {
class DummyFileSystem : public vfs::FileSystem {
int FSID; // used to produce UniqueIDs
int FileID; // used to produce UniqueIDs
std::map<std::string, vfs::Status> FilesAndDirs;
static int getNextFSID() {
static int Count = 0;
return Count++;
}
public:
DummyFileSystem() : FSID(getNextFSID()), FileID(0) {}
ErrorOr<vfs::Status> status(const Twine &Path) override {
std::map<std::string, vfs::Status>::iterator I =
FilesAndDirs.find(Path.str());
if (I == FilesAndDirs.end())
return make_error_code(llvm::errc::no_such_file_or_directory);
return I->second;
}
ErrorOr<std::unique_ptr<vfs::File>>
openFileForRead(const Twine &Path) override {
llvm_unreachable("unimplemented");
}
struct DirIterImpl : public clang::vfs::detail::DirIterImpl {
std::map<std::string, vfs::Status> &FilesAndDirs;
std::map<std::string, vfs::Status>::iterator I;
std::string Path;
bool isInPath(StringRef S) {
if (Path.size() < S.size() && S.find(Path) == 0) {
auto LastSep = S.find_last_of('/');
if (LastSep == Path.size() || LastSep == Path.size()-1)
return true;
}
return false;
}
DirIterImpl(std::map<std::string, vfs::Status> &FilesAndDirs,
const Twine &_Path)
: FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()),
Path(_Path.str()) {
for ( ; I != FilesAndDirs.end(); ++I) {
if (isInPath(I->first)) {
CurrentEntry = I->second;
break;
}
}
}
std::error_code increment() override {
++I;
for ( ; I != FilesAndDirs.end(); ++I) {
if (isInPath(I->first)) {
CurrentEntry = I->second;
break;
}
}
if (I == FilesAndDirs.end())
CurrentEntry = vfs::Status();
return std::error_code();
}
};
vfs::directory_iterator dir_begin(const Twine &Dir,
std::error_code &EC) override {
return vfs::directory_iterator(
std::make_shared<DirIterImpl>(FilesAndDirs, Dir));
}
void addEntry(StringRef Path, const vfs::Status &Status) {
FilesAndDirs[Path] = Status;
}
void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
0, 0, 1024, sys::fs::file_type::regular_file, Perms);
addEntry(Path, S);
}
void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) {
vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
0, 0, 0, sys::fs::file_type::directory_file, Perms);
addEntry(Path, S);
}
void addSymlink(StringRef Path) {
vfs::Status S(Path, Path, UniqueID(FSID, FileID++), sys::TimeValue::now(),
0, 0, 0, sys::fs::file_type::symlink_file, sys::fs::all_all);
addEntry(Path, S);
}
};
} // end anonymous namespace
TEST(VirtualFileSystemTest, StatusQueries) {
IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
ErrorOr<vfs::Status> Status((std::error_code()));
D->addRegularFile("/foo");
Status = D->status("/foo");
ASSERT_FALSE(Status.getError());
EXPECT_TRUE(Status->isStatusKnown());
EXPECT_FALSE(Status->isDirectory());
EXPECT_TRUE(Status->isRegularFile());
EXPECT_FALSE(Status->isSymlink());
EXPECT_FALSE(Status->isOther());
EXPECT_TRUE(Status->exists());
D->addDirectory("/bar");
Status = D->status("/bar");
ASSERT_FALSE(Status.getError());
EXPECT_TRUE(Status->isStatusKnown());
EXPECT_TRUE(Status->isDirectory());
EXPECT_FALSE(Status->isRegularFile());
EXPECT_FALSE(Status->isSymlink());
EXPECT_FALSE(Status->isOther());
EXPECT_TRUE(Status->exists());
D->addSymlink("/baz");
Status = D->status("/baz");
ASSERT_FALSE(Status.getError());
EXPECT_TRUE(Status->isStatusKnown());
EXPECT_FALSE(Status->isDirectory());
EXPECT_FALSE(Status->isRegularFile());
EXPECT_TRUE(Status->isSymlink());
EXPECT_FALSE(Status->isOther());
EXPECT_TRUE(Status->exists());
EXPECT_TRUE(Status->equivalent(*Status));
ErrorOr<vfs::Status> Status2 = D->status("/foo");
ASSERT_FALSE(Status2.getError());
EXPECT_FALSE(Status->equivalent(*Status2));
}
TEST(VirtualFileSystemTest, BaseOnlyOverlay) {
IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem());
ErrorOr<vfs::Status> Status((std::error_code()));
EXPECT_FALSE(Status = D->status("/foo"));
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(new vfs::OverlayFileSystem(D));
EXPECT_FALSE(Status = O->status("/foo"));
D->addRegularFile("/foo");
Status = D->status("/foo");
EXPECT_FALSE(Status.getError());
ErrorOr<vfs::Status> Status2((std::error_code()));
Status2 = O->status("/foo");
EXPECT_FALSE(Status2.getError());
EXPECT_TRUE(Status->equivalent(*Status2));
}
TEST(VirtualFileSystemTest, OverlayFiles) {
IntrusiveRefCntPtr<DummyFileSystem> Base(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Top(new DummyFileSystem());
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Base));
O->pushOverlay(Middle);
O->pushOverlay(Top);
ErrorOr<vfs::Status> Status1((std::error_code())),
Status2((std::error_code())), Status3((std::error_code())),
StatusB((std::error_code())), StatusM((std::error_code())),
StatusT((std::error_code()));
Base->addRegularFile("/foo");
StatusB = Base->status("/foo");
ASSERT_FALSE(StatusB.getError());
Status1 = O->status("/foo");
ASSERT_FALSE(Status1.getError());
Middle->addRegularFile("/foo");
StatusM = Middle->status("/foo");
ASSERT_FALSE(StatusM.getError());
Status2 = O->status("/foo");
ASSERT_FALSE(Status2.getError());
Top->addRegularFile("/foo");
StatusT = Top->status("/foo");
ASSERT_FALSE(StatusT.getError());
Status3 = O->status("/foo");
ASSERT_FALSE(Status3.getError());
EXPECT_TRUE(Status1->equivalent(*StatusB));
EXPECT_TRUE(Status2->equivalent(*StatusM));
EXPECT_TRUE(Status3->equivalent(*StatusT));
EXPECT_FALSE(Status1->equivalent(*Status2));
EXPECT_FALSE(Status2->equivalent(*Status3));
EXPECT_FALSE(Status1->equivalent(*Status3));
}
TEST(VirtualFileSystemTest, OverlayDirsNonMerged) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(Upper);
Lower->addDirectory("/lower-only");
Upper->addDirectory("/upper-only");
// non-merged paths should be the same
ErrorOr<vfs::Status> Status1 = Lower->status("/lower-only");
ASSERT_FALSE(Status1.getError());
ErrorOr<vfs::Status> Status2 = O->status("/lower-only");
ASSERT_FALSE(Status2.getError());
EXPECT_TRUE(Status1->equivalent(*Status2));
Status1 = Upper->status("/upper-only");
ASSERT_FALSE(Status1.getError());
Status2 = O->status("/upper-only");
ASSERT_FALSE(Status2.getError());
EXPECT_TRUE(Status1->equivalent(*Status2));
}
TEST(VirtualFileSystemTest, MergedDirPermissions) {
// merged directories get the permissions of the upper dir
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(Upper);
ErrorOr<vfs::Status> Status((std::error_code()));
Lower->addDirectory("/both", sys::fs::owner_read);
Upper->addDirectory("/both", sys::fs::owner_all | sys::fs::group_read);
Status = O->status("/both");
ASSERT_FALSE(Status.getError());
EXPECT_EQ(0740, Status->getPermissions());
// permissions (as usual) are not recursively applied
Lower->addRegularFile("/both/foo", sys::fs::owner_read);
Upper->addRegularFile("/both/bar", sys::fs::owner_write);
Status = O->status("/both/foo");
ASSERT_FALSE( Status.getError());
EXPECT_EQ(0400, Status->getPermissions());
Status = O->status("/both/bar");
ASSERT_FALSE(Status.getError());
EXPECT_EQ(0200, Status->getPermissions());
}
namespace {
struct ScopedDir {
SmallString<128> Path;
ScopedDir(const Twine &Name, bool Unique=false) {
std::error_code EC;
if (Unique) {
EC = llvm::sys::fs::createUniqueDirectory(Name, Path);
} else {
Path = Name.str();
EC = llvm::sys::fs::create_directory(Twine(Path));
}
if (EC)
Path = "";
EXPECT_FALSE(EC);
}
~ScopedDir() {
if (Path != "")
EXPECT_FALSE(llvm::sys::fs::remove(Path.str()));
}
operator StringRef() { return Path.str(); }
};
}
TEST(VirtualFileSystemTest, BasicRealFSIteration) {
ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true);
IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();
std::error_code EC;
vfs::directory_iterator I = FS->dir_begin(Twine(TestDirectory), EC);
ASSERT_FALSE(EC);
EXPECT_EQ(vfs::directory_iterator(), I); // empty directory is empty
ScopedDir _a(TestDirectory+"/a");
ScopedDir _ab(TestDirectory+"/a/b");
ScopedDir _c(TestDirectory+"/c");
ScopedDir _cd(TestDirectory+"/c/d");
I = FS->dir_begin(Twine(TestDirectory), EC);
ASSERT_FALSE(EC);
ASSERT_NE(vfs::directory_iterator(), I);
// Check either a or c, since we can't rely on the iteration order.
EXPECT_TRUE(I->getName().endswith("a") || I->getName().endswith("c"));
I.increment(EC);
ASSERT_FALSE(EC);
ASSERT_NE(vfs::directory_iterator(), I);
EXPECT_TRUE(I->getName().endswith("a") || I->getName().endswith("c"));
I.increment(EC);
EXPECT_EQ(vfs::directory_iterator(), I);
}
TEST(VirtualFileSystemTest, BasicRealFSRecursiveIteration) {
ScopedDir TestDirectory("virtual-file-system-test", /*Unique*/true);
IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getRealFileSystem();
std::error_code EC;
auto I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
ASSERT_FALSE(EC);
EXPECT_EQ(vfs::recursive_directory_iterator(), I); // empty directory is empty
ScopedDir _a(TestDirectory+"/a");
ScopedDir _ab(TestDirectory+"/a/b");
ScopedDir _c(TestDirectory+"/c");
ScopedDir _cd(TestDirectory+"/c/d");
I = vfs::recursive_directory_iterator(*FS, Twine(TestDirectory), EC);
ASSERT_FALSE(EC);
ASSERT_NE(vfs::recursive_directory_iterator(), I);
std::vector<std::string> Contents;
for (auto E = vfs::recursive_directory_iterator(); !EC && I != E;
I.increment(EC)) {
Contents.push_back(I->getName());
}
// Check contents, which may be in any order
EXPECT_EQ(4U, Contents.size());
int Counts[4] = { 0, 0, 0, 0 };
for (const std::string &Name : Contents) {
ASSERT_FALSE(Name.empty());
int Index = Name[Name.size()-1] - 'a';
ASSERT_TRUE(Index >= 0 && Index < 4);
Counts[Index]++;
}
EXPECT_EQ(1, Counts[0]); // a
EXPECT_EQ(1, Counts[1]); // b
EXPECT_EQ(1, Counts[2]); // c
EXPECT_EQ(1, Counts[3]); // d
}
template <typename T, size_t N>
std::vector<StringRef> makeStringRefVector(const T (&Arr)[N]) {
std::vector<StringRef> Vec;
for (size_t i = 0; i != N; ++i)
Vec.push_back(Arr[i]);
return Vec;
}
template <typename DirIter>
static void checkContents(DirIter I, ArrayRef<StringRef> Expected) {
std::error_code EC;
auto ExpectedIter = Expected.begin(), ExpectedEnd = Expected.end();
for (DirIter E;
!EC && I != E && ExpectedIter != ExpectedEnd;
I.increment(EC), ++ExpectedIter)
EXPECT_EQ(*ExpectedIter, I->getName());
EXPECT_EQ(ExpectedEnd, ExpectedIter);
EXPECT_EQ(DirIter(), I);
}
TEST(VirtualFileSystemTest, OverlayIteration) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(Upper);
std::error_code EC;
checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());
Lower->addRegularFile("/file1");
checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file1"));
Upper->addRegularFile("/file2");
{
const char *Contents[] = {"/file2", "/file1"};
checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
}
Lower->addDirectory("/dir1");
Lower->addRegularFile("/dir1/foo");
Upper->addDirectory("/dir2");
Upper->addRegularFile("/dir2/foo");
checkContents(O->dir_begin("/dir2", EC), ArrayRef<StringRef>("/dir2/foo"));
{
const char *Contents[] = {"/dir2", "/file2", "/dir1", "/file1"};
checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
}
}
TEST(VirtualFileSystemTest, OverlayRecursiveIteration) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(Middle);
O->pushOverlay(Upper);
std::error_code EC;
checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
ArrayRef<StringRef>());
Lower->addRegularFile("/file1");
checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
ArrayRef<StringRef>("/file1"));
Upper->addDirectory("/dir");
Upper->addRegularFile("/dir/file2");
{
const char *Contents[] = {"/dir", "/dir/file2", "/file1"};
checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
makeStringRefVector(Contents));
}
Lower->addDirectory("/dir1");
Lower->addRegularFile("/dir1/foo");
Lower->addDirectory("/dir1/a");
Lower->addRegularFile("/dir1/a/b");
Middle->addDirectory("/a");
Middle->addDirectory("/a/b");
Middle->addDirectory("/a/b/c");
Middle->addRegularFile("/a/b/c/d");
Middle->addRegularFile("/hiddenByUp");
Upper->addDirectory("/dir2");
Upper->addRegularFile("/dir2/foo");
Upper->addRegularFile("/hiddenByUp");
checkContents(vfs::recursive_directory_iterator(*O, "/dir2", EC),
ArrayRef<StringRef>("/dir2/foo"));
{
const char *Contents[] = { "/dir", "/dir/file2", "/dir2", "/dir2/foo",
"/hiddenByUp", "/a", "/a/b", "/a/b/c", "/a/b/c/d", "/dir1", "/dir1/a",
"/dir1/a/b", "/dir1/foo", "/file1" };
checkContents(vfs::recursive_directory_iterator(*O, "/", EC),
makeStringRefVector(Contents));
}
}
TEST(VirtualFileSystemTest, ThreeLevelIteration) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(Middle);
O->pushOverlay(Upper);
std::error_code EC;
checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>());
Middle->addRegularFile("/file2");
checkContents(O->dir_begin("/", EC), ArrayRef<StringRef>("/file2"));
Lower->addRegularFile("/file1");
Upper->addRegularFile("/file3");
{
const char *Contents[] = {"/file3", "/file2", "/file1"};
checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
}
}
TEST(VirtualFileSystemTest, HiddenInIteration) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Middle(new DummyFileSystem());
IntrusiveRefCntPtr<DummyFileSystem> Upper(new DummyFileSystem());
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(Middle);
O->pushOverlay(Upper);
std::error_code EC;
Lower->addRegularFile("/onlyInLow", sys::fs::owner_read);
Lower->addRegularFile("/hiddenByMid", sys::fs::owner_read);
Lower->addRegularFile("/hiddenByUp", sys::fs::owner_read);
Middle->addRegularFile("/onlyInMid", sys::fs::owner_write);
Middle->addRegularFile("/hiddenByMid", sys::fs::owner_write);
Middle->addRegularFile("/hiddenByUp", sys::fs::owner_write);
Upper->addRegularFile("/onlyInUp", sys::fs::owner_all);
Upper->addRegularFile("/hiddenByUp", sys::fs::owner_all);
{
const char *Contents[] = {"/hiddenByUp", "/onlyInUp", "/hiddenByMid",
"/onlyInMid", "/onlyInLow"};
checkContents(O->dir_begin("/", EC), makeStringRefVector(Contents));
}
// Make sure we get the top-most entry
{
std::error_code EC;
vfs::directory_iterator I = O->dir_begin("/", EC), E;
for ( ; !EC && I != E; I.increment(EC))
if (I->getName() == "/hiddenByUp")
break;
ASSERT_NE(E, I);
EXPECT_EQ(sys::fs::owner_all, I->getPermissions());
}
{
std::error_code EC;
vfs::directory_iterator I = O->dir_begin("/", EC), E;
for ( ; !EC && I != E; I.increment(EC))
if (I->getName() == "/hiddenByMid")
break;
ASSERT_NE(E, I);
EXPECT_EQ(sys::fs::owner_write, I->getPermissions());
}
}
// NOTE: in the tests below, we use '//root/' as our root directory, since it is
// a legal *absolute* path on Windows as well as *nix.
class VFSFromYAMLTest : public ::testing::Test {
public:
int NumDiagnostics;
void SetUp() override { NumDiagnostics = 0; }
static void CountingDiagHandler(const SMDiagnostic &, void *Context) {
VFSFromYAMLTest *Test = static_cast<VFSFromYAMLTest *>(Context);
++Test->NumDiagnostics;
}
IntrusiveRefCntPtr<vfs::FileSystem>
getFromYAMLRawString(StringRef Content,
IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS) {
std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBuffer(Content);
return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, this,
ExternalFS);
}
IntrusiveRefCntPtr<vfs::FileSystem> getFromYAMLString(
StringRef Content,
IntrusiveRefCntPtr<vfs::FileSystem> ExternalFS = new DummyFileSystem()) {
std::string VersionPlusContent("{\n 'version':0,\n");
VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
return getFromYAMLRawString(VersionPlusContent, ExternalFS);
}
};
TEST_F(VFSFromYAMLTest, BasicVFSFromYAML) {
IntrusiveRefCntPtr<vfs::FileSystem> FS;
FS = getFromYAMLString("");
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString("[]");
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString("'string'");
EXPECT_EQ(nullptr, FS.get());
EXPECT_EQ(3, NumDiagnostics);
}
TEST_F(VFSFromYAMLTest, MappedFiles) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
Lower->addRegularFile("//root/foo/bar/a");
IntrusiveRefCntPtr<vfs::FileSystem> FS =
getFromYAMLString("{ 'roots': [\n"
"{\n"
" 'type': 'directory',\n"
" 'name': '//root/',\n"
" 'contents': [ {\n"
" 'type': 'file',\n"
" 'name': 'file1',\n"
" 'external-contents': '//root/foo/bar/a'\n"
" },\n"
" {\n"
" 'type': 'file',\n"
" 'name': 'file2',\n"
" 'external-contents': '//root/foo/b'\n"
" }\n"
" ]\n"
"}\n"
"]\n"
"}",
Lower);
ASSERT_TRUE(FS.get() != nullptr);
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(FS);
// file
ErrorOr<vfs::Status> S = O->status("//root/file1");
ASSERT_FALSE(S.getError());
EXPECT_EQ("//root/foo/bar/a", S->getName());
ErrorOr<vfs::Status> SLower = O->status("//root/foo/bar/a");
EXPECT_EQ("//root/foo/bar/a", SLower->getName());
EXPECT_TRUE(S->equivalent(*SLower));
// directory
S = O->status("//root/");
ASSERT_FALSE(S.getError());
EXPECT_TRUE(S->isDirectory());
EXPECT_TRUE(S->equivalent(*O->status("//root/"))); // non-volatile UniqueID
// broken mapping
EXPECT_EQ(O->status("//root/file2").getError(),
llvm::errc::no_such_file_or_directory);
EXPECT_EQ(0, NumDiagnostics);
}
TEST_F(VFSFromYAMLTest, CaseInsensitive) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
Lower->addRegularFile("//root/foo/bar/a");
IntrusiveRefCntPtr<vfs::FileSystem> FS =
getFromYAMLString("{ 'case-sensitive': 'false',\n"
" 'roots': [\n"
"{\n"
" 'type': 'directory',\n"
" 'name': '//root/',\n"
" 'contents': [ {\n"
" 'type': 'file',\n"
" 'name': 'XX',\n"
" 'external-contents': '//root/foo/bar/a'\n"
" }\n"
" ]\n"
"}]}",
Lower);
ASSERT_TRUE(FS.get() != nullptr);
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(FS);
ErrorOr<vfs::Status> S = O->status("//root/XX");
ASSERT_FALSE(S.getError());
ErrorOr<vfs::Status> SS = O->status("//root/xx");
ASSERT_FALSE(SS.getError());
EXPECT_TRUE(S->equivalent(*SS));
SS = O->status("//root/xX");
EXPECT_TRUE(S->equivalent(*SS));
SS = O->status("//root/Xx");
EXPECT_TRUE(S->equivalent(*SS));
EXPECT_EQ(0, NumDiagnostics);
}
TEST_F(VFSFromYAMLTest, CaseSensitive) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
Lower->addRegularFile("//root/foo/bar/a");
IntrusiveRefCntPtr<vfs::FileSystem> FS =
getFromYAMLString("{ 'case-sensitive': 'true',\n"
" 'roots': [\n"
"{\n"
" 'type': 'directory',\n"
" 'name': '//root/',\n"
" 'contents': [ {\n"
" 'type': 'file',\n"
" 'name': 'XX',\n"
" 'external-contents': '//root/foo/bar/a'\n"
" }\n"
" ]\n"
"}]}",
Lower);
ASSERT_TRUE(FS.get() != nullptr);
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(FS);
ErrorOr<vfs::Status> SS = O->status("//root/xx");
EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
SS = O->status("//root/xX");
EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
SS = O->status("//root/Xx");
EXPECT_EQ(SS.getError(), llvm::errc::no_such_file_or_directory);
EXPECT_EQ(0, NumDiagnostics);
}
TEST_F(VFSFromYAMLTest, IllegalVFSFile) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
// invalid YAML at top-level
IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString("{]", Lower);
EXPECT_EQ(nullptr, FS.get());
// invalid YAML in roots
FS = getFromYAMLString("{ 'roots':[}", Lower);
// invalid YAML in directory
FS = getFromYAMLString(
"{ 'roots':[ { 'name': 'foo', 'type': 'directory', 'contents': [}",
Lower);
EXPECT_EQ(nullptr, FS.get());
// invalid configuration
FS = getFromYAMLString("{ 'knobular': 'true', 'roots':[] }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString("{ 'case-sensitive': 'maybe', 'roots':[] }", Lower);
EXPECT_EQ(nullptr, FS.get());
// invalid roots
FS = getFromYAMLString("{ 'roots':'' }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString("{ 'roots':{} }", Lower);
EXPECT_EQ(nullptr, FS.get());
// invalid entries
FS = getFromYAMLString(
"{ 'roots':[ { 'type': 'other', 'name': 'me', 'contents': '' }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': [], "
"'external-contents': 'other' }",
Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString(
"{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': [] }",
Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString(
"{ 'roots':[ { 'type': 'file', 'name': 'me', 'external-contents': {} }",
Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString(
"{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': {} }",
Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString(
"{ 'roots':[ { 'type': 'directory', 'name': 'me', 'contents': '' }",
Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString(
"{ 'roots':[ { 'thingy': 'directory', 'name': 'me', 'contents': [] }",
Lower);
EXPECT_EQ(nullptr, FS.get());
// missing mandatory fields
FS = getFromYAMLString("{ 'roots':[ { 'type': 'file', 'name': 'me' }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString(
"{ 'roots':[ { 'type': 'file', 'external-contents': 'other' }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString("{ 'roots':[ { 'name': 'me', 'contents': [] }", Lower);
EXPECT_EQ(nullptr, FS.get());
// duplicate keys
FS = getFromYAMLString("{ 'roots':[], 'roots':[] }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLString(
"{ 'case-sensitive':'true', 'case-sensitive':'true', 'roots':[] }",
Lower);
EXPECT_EQ(nullptr, FS.get());
FS =
getFromYAMLString("{ 'roots':[{'name':'me', 'name':'you', 'type':'file', "
"'external-contents':'blah' } ] }",
Lower);
EXPECT_EQ(nullptr, FS.get());
// missing version
FS = getFromYAMLRawString("{ 'roots':[] }", Lower);
EXPECT_EQ(nullptr, FS.get());
// bad version number
FS = getFromYAMLRawString("{ 'version':'foo', 'roots':[] }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLRawString("{ 'version':-1, 'roots':[] }", Lower);
EXPECT_EQ(nullptr, FS.get());
FS = getFromYAMLRawString("{ 'version':100000, 'roots':[] }", Lower);
EXPECT_EQ(nullptr, FS.get());
EXPECT_EQ(24, NumDiagnostics);
}
TEST_F(VFSFromYAMLTest, UseExternalName) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
Lower->addRegularFile("//root/external/file");
IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
"{ 'roots': [\n"
" { 'type': 'file', 'name': '//root/A',\n"
" 'external-contents': '//root/external/file'\n"
" },\n"
" { 'type': 'file', 'name': '//root/B',\n"
" 'use-external-name': true,\n"
" 'external-contents': '//root/external/file'\n"
" },\n"
" { 'type': 'file', 'name': '//root/C',\n"
" 'use-external-name': false,\n"
" 'external-contents': '//root/external/file'\n"
" }\n"
"] }", Lower);
ASSERT_TRUE(nullptr != FS.get());
// default true
EXPECT_EQ("//root/external/file", FS->status("//root/A")->getName());
// explicit
EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
// global configuration
FS = getFromYAMLString(
"{ 'use-external-names': false,\n"
" 'roots': [\n"
" { 'type': 'file', 'name': '//root/A',\n"
" 'external-contents': '//root/external/file'\n"
" },\n"
" { 'type': 'file', 'name': '//root/B',\n"
" 'use-external-name': true,\n"
" 'external-contents': '//root/external/file'\n"
" },\n"
" { 'type': 'file', 'name': '//root/C',\n"
" 'use-external-name': false,\n"
" 'external-contents': '//root/external/file'\n"
" }\n"
"] }", Lower);
ASSERT_TRUE(nullptr != FS.get());
// default
EXPECT_EQ("//root/A", FS->status("//root/A")->getName());
// explicit
EXPECT_EQ("//root/external/file", FS->status("//root/B")->getName());
EXPECT_EQ("//root/C", FS->status("//root/C")->getName());
}
TEST_F(VFSFromYAMLTest, MultiComponentPath) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
Lower->addRegularFile("//root/other");
// file in roots
IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
"{ 'roots': [\n"
" { 'type': 'file', 'name': '//root/path/to/file',\n"
" 'external-contents': '//root/other' }]\n"
"}", Lower);
ASSERT_TRUE(nullptr != FS.get());
EXPECT_FALSE(FS->status("//root/path/to/file").getError());
EXPECT_FALSE(FS->status("//root/path/to").getError());
EXPECT_FALSE(FS->status("//root/path").getError());
EXPECT_FALSE(FS->status("//root/").getError());
// at the start
FS = getFromYAMLString(
"{ 'roots': [\n"
" { 'type': 'directory', 'name': '//root/path/to',\n"
" 'contents': [ { 'type': 'file', 'name': 'file',\n"
" 'external-contents': '//root/other' }]}]\n"
"}", Lower);
ASSERT_TRUE(nullptr != FS.get());
EXPECT_FALSE(FS->status("//root/path/to/file").getError());
EXPECT_FALSE(FS->status("//root/path/to").getError());
EXPECT_FALSE(FS->status("//root/path").getError());
EXPECT_FALSE(FS->status("//root/").getError());
// at the end
FS = getFromYAMLString(
"{ 'roots': [\n"
" { 'type': 'directory', 'name': '//root/',\n"
" 'contents': [ { 'type': 'file', 'name': 'path/to/file',\n"
" 'external-contents': '//root/other' }]}]\n"
"}", Lower);
ASSERT_TRUE(nullptr != FS.get());
EXPECT_FALSE(FS->status("//root/path/to/file").getError());
EXPECT_FALSE(FS->status("//root/path/to").getError());
EXPECT_FALSE(FS->status("//root/path").getError());
EXPECT_FALSE(FS->status("//root/").getError());
}
TEST_F(VFSFromYAMLTest, TrailingSlashes) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
Lower->addRegularFile("//root/other");
// file in roots
IntrusiveRefCntPtr<vfs::FileSystem> FS = getFromYAMLString(
"{ 'roots': [\n"
" { 'type': 'directory', 'name': '//root/path/to////',\n"
" 'contents': [ { 'type': 'file', 'name': 'file',\n"
" 'external-contents': '//root/other' }]}]\n"
"}", Lower);
ASSERT_TRUE(nullptr != FS.get());
EXPECT_FALSE(FS->status("//root/path/to/file").getError());
EXPECT_FALSE(FS->status("//root/path/to").getError());
EXPECT_FALSE(FS->status("//root/path").getError());
EXPECT_FALSE(FS->status("//root/").getError());
}
TEST_F(VFSFromYAMLTest, DirectoryIteration) {
IntrusiveRefCntPtr<DummyFileSystem> Lower(new DummyFileSystem());
Lower->addDirectory("//root/");
Lower->addDirectory("//root/foo");
Lower->addDirectory("//root/foo/bar");
Lower->addRegularFile("//root/foo/bar/a");
Lower->addRegularFile("//root/foo/bar/b");
Lower->addRegularFile("//root/file3");
IntrusiveRefCntPtr<vfs::FileSystem> FS =
getFromYAMLString("{ 'use-external-names': false,\n"
" 'roots': [\n"
"{\n"
" 'type': 'directory',\n"
" 'name': '//root/',\n"
" 'contents': [ {\n"
" 'type': 'file',\n"
" 'name': 'file1',\n"
" 'external-contents': '//root/foo/bar/a'\n"
" },\n"
" {\n"
" 'type': 'file',\n"
" 'name': 'file2',\n"
" 'external-contents': '//root/foo/bar/b'\n"
" }\n"
" ]\n"
"}\n"
"]\n"
"}",
Lower);
ASSERT_TRUE(FS.get() != NULL);
IntrusiveRefCntPtr<vfs::OverlayFileSystem> O(
new vfs::OverlayFileSystem(Lower));
O->pushOverlay(FS);
std::error_code EC;
{
const char *Contents[] = {"//root/file1", "//root/file2", "//root/file3",
"//root/foo"};
checkContents(O->dir_begin("//root/", EC), makeStringRefVector(Contents));
}
{
const char *Contents[] = {"//root/foo/bar/a", "//root/foo/bar/b"};
checkContents(O->dir_begin("//root/foo/bar", EC),
makeStringRefVector(Contents));
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Basic/DiagnosticTest.cpp
|
//===- unittests/Basic/DiagnosticTest.cpp -- Diagnostic engine tests ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticIDs.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
// Check that DiagnosticErrorTrap works with SuppressAllDiagnostics.
TEST(DiagnosticTest, suppressAndTrap) {
DiagnosticsEngine Diags(new DiagnosticIDs(),
new DiagnosticOptions,
new IgnoringDiagConsumer());
Diags.setSuppressAllDiagnostics(true);
{
DiagnosticErrorTrap trap(Diags);
// Diag that would set UncompilableErrorOccurred and ErrorOccurred.
Diags.Report(diag::err_target_unknown_triple) << "unknown";
// Diag that would set UnrecoverableErrorOccurred and ErrorOccurred.
Diags.Report(diag::err_cannot_open_file) << "file" << "error";
// Diag that would set FatalErrorOccurred
// (via non-note following a fatal error).
Diags.Report(diag::warn_mt_message) << "warning";
EXPECT_TRUE(trap.hasErrorOccurred());
EXPECT_TRUE(trap.hasUnrecoverableErrorOccurred());
}
EXPECT_FALSE(Diags.hasErrorOccurred());
EXPECT_FALSE(Diags.hasFatalErrorOccurred());
EXPECT_FALSE(Diags.hasUncompilableErrorOccurred());
EXPECT_FALSE(Diags.hasUnrecoverableErrorOccurred());
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Basic/CharInfoTest.cpp
|
//===- unittests/Basic/CharInfoTest.cpp -- ASCII classification tests -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/CharInfo.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
// Check that the CharInfo table has been constructed reasonably.
TEST(CharInfoTest, validateInfoTable) {
using namespace charinfo;
EXPECT_EQ((unsigned)CHAR_SPACE, InfoTable[(unsigned)' ']);
EXPECT_EQ((unsigned)CHAR_HORZ_WS, InfoTable[(unsigned)'\t']);
EXPECT_EQ((unsigned)CHAR_HORZ_WS, InfoTable[(unsigned)'\f']); // ??
EXPECT_EQ((unsigned)CHAR_HORZ_WS, InfoTable[(unsigned)'\v']); // ??
EXPECT_EQ((unsigned)CHAR_VERT_WS, InfoTable[(unsigned)'\n']);
EXPECT_EQ((unsigned)CHAR_VERT_WS, InfoTable[(unsigned)'\r']);
EXPECT_EQ((unsigned)CHAR_UNDER, InfoTable[(unsigned)'_']);
EXPECT_EQ((unsigned)CHAR_PERIOD, InfoTable[(unsigned)'.']);
for (unsigned i = 'a'; i <= 'f'; ++i) {
EXPECT_EQ((unsigned)CHAR_XLOWER, InfoTable[i]);
EXPECT_EQ((unsigned)CHAR_XUPPER, InfoTable[i+'A'-'a']);
}
for (unsigned i = 'g'; i <= 'z'; ++i) {
EXPECT_EQ((unsigned)CHAR_LOWER, InfoTable[i]);
EXPECT_EQ((unsigned)CHAR_UPPER, InfoTable[i+'A'-'a']);
}
for (unsigned i = '0'; i <= '9'; ++i)
EXPECT_EQ((unsigned)CHAR_DIGIT, InfoTable[i]);
}
// Check various predicates.
TEST(CharInfoTest, isASCII) {
EXPECT_TRUE(isASCII('\0'));
EXPECT_TRUE(isASCII('\n'));
EXPECT_TRUE(isASCII(' '));
EXPECT_TRUE(isASCII('a'));
EXPECT_TRUE(isASCII('\x7f'));
EXPECT_FALSE(isASCII('\x80'));
EXPECT_FALSE(isASCII('\xc2'));
EXPECT_FALSE(isASCII('\xff'));
}
TEST(CharInfoTest, isIdentifierHead) {
EXPECT_TRUE(isIdentifierHead('a'));
EXPECT_TRUE(isIdentifierHead('A'));
EXPECT_TRUE(isIdentifierHead('z'));
EXPECT_TRUE(isIdentifierHead('Z'));
EXPECT_TRUE(isIdentifierHead('_'));
EXPECT_FALSE(isIdentifierHead('0'));
EXPECT_FALSE(isIdentifierHead('.'));
EXPECT_FALSE(isIdentifierHead('`'));
EXPECT_FALSE(isIdentifierHead('\0'));
EXPECT_FALSE(isIdentifierHead('$'));
EXPECT_TRUE(isIdentifierHead('$', /*AllowDollar=*/true));
EXPECT_FALSE(isIdentifierHead('\x80'));
EXPECT_FALSE(isIdentifierHead('\xc2'));
EXPECT_FALSE(isIdentifierHead('\xff'));
}
TEST(CharInfoTest, isIdentifierBody) {
EXPECT_TRUE(isIdentifierBody('a'));
EXPECT_TRUE(isIdentifierBody('A'));
EXPECT_TRUE(isIdentifierBody('z'));
EXPECT_TRUE(isIdentifierBody('Z'));
EXPECT_TRUE(isIdentifierBody('_'));
EXPECT_TRUE(isIdentifierBody('0'));
EXPECT_FALSE(isIdentifierBody('.'));
EXPECT_FALSE(isIdentifierBody('`'));
EXPECT_FALSE(isIdentifierBody('\0'));
EXPECT_FALSE(isIdentifierBody('$'));
EXPECT_TRUE(isIdentifierBody('$', /*AllowDollar=*/true));
EXPECT_FALSE(isIdentifierBody('\x80'));
EXPECT_FALSE(isIdentifierBody('\xc2'));
EXPECT_FALSE(isIdentifierBody('\xff'));
}
TEST(CharInfoTest, isHorizontalWhitespace) {
EXPECT_FALSE(isHorizontalWhitespace('a'));
EXPECT_FALSE(isHorizontalWhitespace('_'));
EXPECT_FALSE(isHorizontalWhitespace('0'));
EXPECT_FALSE(isHorizontalWhitespace('.'));
EXPECT_FALSE(isHorizontalWhitespace('`'));
EXPECT_FALSE(isHorizontalWhitespace('\0'));
EXPECT_FALSE(isHorizontalWhitespace('\x7f'));
EXPECT_TRUE(isHorizontalWhitespace(' '));
EXPECT_TRUE(isHorizontalWhitespace('\t'));
EXPECT_TRUE(isHorizontalWhitespace('\f')); // ??
EXPECT_TRUE(isHorizontalWhitespace('\v')); // ??
EXPECT_FALSE(isHorizontalWhitespace('\n'));
EXPECT_FALSE(isHorizontalWhitespace('\r'));
EXPECT_FALSE(isHorizontalWhitespace('\x80'));
EXPECT_FALSE(isHorizontalWhitespace('\xc2'));
EXPECT_FALSE(isHorizontalWhitespace('\xff'));
}
TEST(CharInfoTest, isVerticalWhitespace) {
EXPECT_FALSE(isVerticalWhitespace('a'));
EXPECT_FALSE(isVerticalWhitespace('_'));
EXPECT_FALSE(isVerticalWhitespace('0'));
EXPECT_FALSE(isVerticalWhitespace('.'));
EXPECT_FALSE(isVerticalWhitespace('`'));
EXPECT_FALSE(isVerticalWhitespace('\0'));
EXPECT_FALSE(isVerticalWhitespace('\x7f'));
EXPECT_FALSE(isVerticalWhitespace(' '));
EXPECT_FALSE(isVerticalWhitespace('\t'));
EXPECT_FALSE(isVerticalWhitespace('\f')); // ??
EXPECT_FALSE(isVerticalWhitespace('\v')); // ??
EXPECT_TRUE(isVerticalWhitespace('\n'));
EXPECT_TRUE(isVerticalWhitespace('\r'));
EXPECT_FALSE(isVerticalWhitespace('\x80'));
EXPECT_FALSE(isVerticalWhitespace('\xc2'));
EXPECT_FALSE(isVerticalWhitespace('\xff'));
}
TEST(CharInfoTest, isWhitespace) {
EXPECT_FALSE(isWhitespace('a'));
EXPECT_FALSE(isWhitespace('_'));
EXPECT_FALSE(isWhitespace('0'));
EXPECT_FALSE(isWhitespace('.'));
EXPECT_FALSE(isWhitespace('`'));
EXPECT_FALSE(isWhitespace('\0'));
EXPECT_FALSE(isWhitespace('\x7f'));
EXPECT_TRUE(isWhitespace(' '));
EXPECT_TRUE(isWhitespace('\t'));
EXPECT_TRUE(isWhitespace('\f'));
EXPECT_TRUE(isWhitespace('\v'));
EXPECT_TRUE(isWhitespace('\n'));
EXPECT_TRUE(isWhitespace('\r'));
EXPECT_FALSE(isWhitespace('\x80'));
EXPECT_FALSE(isWhitespace('\xc2'));
EXPECT_FALSE(isWhitespace('\xff'));
}
TEST(CharInfoTest, isDigit) {
EXPECT_TRUE(isDigit('0'));
EXPECT_TRUE(isDigit('9'));
EXPECT_FALSE(isDigit('a'));
EXPECT_FALSE(isDigit('A'));
EXPECT_FALSE(isDigit('z'));
EXPECT_FALSE(isDigit('Z'));
EXPECT_FALSE(isDigit('.'));
EXPECT_FALSE(isDigit('_'));
EXPECT_FALSE(isDigit('/'));
EXPECT_FALSE(isDigit('\0'));
EXPECT_FALSE(isDigit('\x80'));
EXPECT_FALSE(isDigit('\xc2'));
EXPECT_FALSE(isDigit('\xff'));
}
TEST(CharInfoTest, isHexDigit) {
EXPECT_TRUE(isHexDigit('0'));
EXPECT_TRUE(isHexDigit('9'));
EXPECT_TRUE(isHexDigit('a'));
EXPECT_TRUE(isHexDigit('A'));
EXPECT_FALSE(isHexDigit('z'));
EXPECT_FALSE(isHexDigit('Z'));
EXPECT_FALSE(isHexDigit('.'));
EXPECT_FALSE(isHexDigit('_'));
EXPECT_FALSE(isHexDigit('/'));
EXPECT_FALSE(isHexDigit('\0'));
EXPECT_FALSE(isHexDigit('\x80'));
EXPECT_FALSE(isHexDigit('\xc2'));
EXPECT_FALSE(isHexDigit('\xff'));
}
TEST(CharInfoTest, isLetter) {
EXPECT_FALSE(isLetter('0'));
EXPECT_FALSE(isLetter('9'));
EXPECT_TRUE(isLetter('a'));
EXPECT_TRUE(isLetter('A'));
EXPECT_TRUE(isLetter('z'));
EXPECT_TRUE(isLetter('Z'));
EXPECT_FALSE(isLetter('.'));
EXPECT_FALSE(isLetter('_'));
EXPECT_FALSE(isLetter('/'));
EXPECT_FALSE(isLetter('('));
EXPECT_FALSE(isLetter('\0'));
EXPECT_FALSE(isLetter('\x80'));
EXPECT_FALSE(isLetter('\xc2'));
EXPECT_FALSE(isLetter('\xff'));
}
TEST(CharInfoTest, isLowercase) {
EXPECT_FALSE(isLowercase('0'));
EXPECT_FALSE(isLowercase('9'));
EXPECT_TRUE(isLowercase('a'));
EXPECT_FALSE(isLowercase('A'));
EXPECT_TRUE(isLowercase('z'));
EXPECT_FALSE(isLowercase('Z'));
EXPECT_FALSE(isLowercase('.'));
EXPECT_FALSE(isLowercase('_'));
EXPECT_FALSE(isLowercase('/'));
EXPECT_FALSE(isLowercase('('));
EXPECT_FALSE(isLowercase('\0'));
EXPECT_FALSE(isLowercase('\x80'));
EXPECT_FALSE(isLowercase('\xc2'));
EXPECT_FALSE(isLowercase('\xff'));
}
TEST(CharInfoTest, isUppercase) {
EXPECT_FALSE(isUppercase('0'));
EXPECT_FALSE(isUppercase('9'));
EXPECT_FALSE(isUppercase('a'));
EXPECT_TRUE(isUppercase('A'));
EXPECT_FALSE(isUppercase('z'));
EXPECT_TRUE(isUppercase('Z'));
EXPECT_FALSE(isUppercase('.'));
EXPECT_FALSE(isUppercase('_'));
EXPECT_FALSE(isUppercase('/'));
EXPECT_FALSE(isUppercase('('));
EXPECT_FALSE(isUppercase('\0'));
EXPECT_FALSE(isUppercase('\x80'));
EXPECT_FALSE(isUppercase('\xc2'));
EXPECT_FALSE(isUppercase('\xff'));
}
TEST(CharInfoTest, isAlphanumeric) {
EXPECT_TRUE(isAlphanumeric('0'));
EXPECT_TRUE(isAlphanumeric('9'));
EXPECT_TRUE(isAlphanumeric('a'));
EXPECT_TRUE(isAlphanumeric('A'));
EXPECT_TRUE(isAlphanumeric('z'));
EXPECT_TRUE(isAlphanumeric('Z'));
EXPECT_FALSE(isAlphanumeric('.'));
EXPECT_FALSE(isAlphanumeric('_'));
EXPECT_FALSE(isAlphanumeric('/'));
EXPECT_FALSE(isAlphanumeric('('));
EXPECT_FALSE(isAlphanumeric('\0'));
EXPECT_FALSE(isAlphanumeric('\x80'));
EXPECT_FALSE(isAlphanumeric('\xc2'));
EXPECT_FALSE(isAlphanumeric('\xff'));
}
TEST(CharInfoTest, isPunctuation) {
EXPECT_FALSE(isPunctuation('0'));
EXPECT_FALSE(isPunctuation('9'));
EXPECT_FALSE(isPunctuation('a'));
EXPECT_FALSE(isPunctuation('A'));
EXPECT_FALSE(isPunctuation('z'));
EXPECT_FALSE(isPunctuation('Z'));
EXPECT_TRUE(isPunctuation('.'));
EXPECT_TRUE(isPunctuation('_'));
EXPECT_TRUE(isPunctuation('/'));
EXPECT_TRUE(isPunctuation('('));
EXPECT_FALSE(isPunctuation(' '));
EXPECT_FALSE(isPunctuation('\n'));
EXPECT_FALSE(isPunctuation('\0'));
EXPECT_FALSE(isPunctuation('\x80'));
EXPECT_FALSE(isPunctuation('\xc2'));
EXPECT_FALSE(isPunctuation('\xff'));
}
TEST(CharInfoTest, isPrintable) {
EXPECT_TRUE(isPrintable('0'));
EXPECT_TRUE(isPrintable('9'));
EXPECT_TRUE(isPrintable('a'));
EXPECT_TRUE(isPrintable('A'));
EXPECT_TRUE(isPrintable('z'));
EXPECT_TRUE(isPrintable('Z'));
EXPECT_TRUE(isPrintable('.'));
EXPECT_TRUE(isPrintable('_'));
EXPECT_TRUE(isPrintable('/'));
EXPECT_TRUE(isPrintable('('));
EXPECT_TRUE(isPrintable(' '));
EXPECT_FALSE(isPrintable('\t'));
EXPECT_FALSE(isPrintable('\n'));
EXPECT_FALSE(isPrintable('\0'));
EXPECT_FALSE(isPrintable('\x80'));
EXPECT_FALSE(isPrintable('\xc2'));
EXPECT_FALSE(isPrintable('\xff'));
}
TEST(CharInfoTest, isPreprocessingNumberBody) {
EXPECT_TRUE(isPreprocessingNumberBody('0'));
EXPECT_TRUE(isPreprocessingNumberBody('9'));
EXPECT_TRUE(isPreprocessingNumberBody('a'));
EXPECT_TRUE(isPreprocessingNumberBody('A'));
EXPECT_TRUE(isPreprocessingNumberBody('z'));
EXPECT_TRUE(isPreprocessingNumberBody('Z'));
EXPECT_TRUE(isPreprocessingNumberBody('.'));
EXPECT_TRUE(isPreprocessingNumberBody('_'));
EXPECT_FALSE(isPreprocessingNumberBody('/'));
EXPECT_FALSE(isPreprocessingNumberBody('('));
EXPECT_FALSE(isPreprocessingNumberBody('\0'));
EXPECT_FALSE(isPreprocessingNumberBody('\x80'));
EXPECT_FALSE(isPreprocessingNumberBody('\xc2'));
EXPECT_FALSE(isPreprocessingNumberBody('\xff'));
}
TEST(CharInfoTest, isRawStringDelimBody) {
EXPECT_TRUE(isRawStringDelimBody('0'));
EXPECT_TRUE(isRawStringDelimBody('9'));
EXPECT_TRUE(isRawStringDelimBody('a'));
EXPECT_TRUE(isRawStringDelimBody('A'));
EXPECT_TRUE(isRawStringDelimBody('z'));
EXPECT_TRUE(isRawStringDelimBody('Z'));
EXPECT_TRUE(isRawStringDelimBody('.'));
EXPECT_TRUE(isRawStringDelimBody('_'));
EXPECT_TRUE(isRawStringDelimBody('/'));
EXPECT_FALSE(isRawStringDelimBody('('));
EXPECT_FALSE(isRawStringDelimBody('\0'));
EXPECT_FALSE(isRawStringDelimBody('\x80'));
EXPECT_FALSE(isRawStringDelimBody('\xc2'));
EXPECT_FALSE(isRawStringDelimBody('\xff'));
}
TEST(CharInfoTest, toLowercase) {
EXPECT_EQ('0', toLowercase('0'));
EXPECT_EQ('9', toLowercase('9'));
EXPECT_EQ('a', toLowercase('a'));
EXPECT_EQ('a', toLowercase('A'));
EXPECT_EQ('z', toLowercase('z'));
EXPECT_EQ('z', toLowercase('Z'));
EXPECT_EQ('.', toLowercase('.'));
EXPECT_EQ('_', toLowercase('_'));
EXPECT_EQ('/', toLowercase('/'));
EXPECT_EQ('\0', toLowercase('\0'));
}
TEST(CharInfoTest, toUppercase) {
EXPECT_EQ('0', toUppercase('0'));
EXPECT_EQ('9', toUppercase('9'));
EXPECT_EQ('A', toUppercase('a'));
EXPECT_EQ('A', toUppercase('A'));
EXPECT_EQ('Z', toUppercase('z'));
EXPECT_EQ('Z', toUppercase('Z'));
EXPECT_EQ('.', toUppercase('.'));
EXPECT_EQ('_', toUppercase('_'));
EXPECT_EQ('/', toUppercase('/'));
EXPECT_EQ('\0', toUppercase('\0'));
}
TEST(CharInfoTest, isValidIdentifier) {
EXPECT_FALSE(isValidIdentifier(""));
// 1 character
EXPECT_FALSE(isValidIdentifier("."));
EXPECT_FALSE(isValidIdentifier("\n"));
EXPECT_FALSE(isValidIdentifier(" "));
EXPECT_FALSE(isValidIdentifier("\x80"));
EXPECT_FALSE(isValidIdentifier("\xc2"));
EXPECT_FALSE(isValidIdentifier("\xff"));
EXPECT_FALSE(isValidIdentifier("$"));
EXPECT_FALSE(isValidIdentifier("1"));
EXPECT_TRUE(isValidIdentifier("_"));
EXPECT_TRUE(isValidIdentifier("a"));
EXPECT_TRUE(isValidIdentifier("z"));
EXPECT_TRUE(isValidIdentifier("A"));
EXPECT_TRUE(isValidIdentifier("Z"));
// 2 characters, '_' suffix
EXPECT_FALSE(isValidIdentifier("._"));
EXPECT_FALSE(isValidIdentifier("\n_"));
EXPECT_FALSE(isValidIdentifier(" _"));
EXPECT_FALSE(isValidIdentifier("\x80_"));
EXPECT_FALSE(isValidIdentifier("\xc2_"));
EXPECT_FALSE(isValidIdentifier("\xff_"));
EXPECT_FALSE(isValidIdentifier("$_"));
EXPECT_FALSE(isValidIdentifier("1_"));
EXPECT_TRUE(isValidIdentifier("__"));
EXPECT_TRUE(isValidIdentifier("a_"));
EXPECT_TRUE(isValidIdentifier("z_"));
EXPECT_TRUE(isValidIdentifier("A_"));
EXPECT_TRUE(isValidIdentifier("Z_"));
// 2 characters, '_' prefix
EXPECT_FALSE(isValidIdentifier("_."));
EXPECT_FALSE(isValidIdentifier("_\n"));
EXPECT_FALSE(isValidIdentifier("_ "));
EXPECT_FALSE(isValidIdentifier("_\x80"));
EXPECT_FALSE(isValidIdentifier("_\xc2"));
EXPECT_FALSE(isValidIdentifier("_\xff"));
EXPECT_FALSE(isValidIdentifier("_$"));
EXPECT_TRUE(isValidIdentifier("_1"));
EXPECT_TRUE(isValidIdentifier("__"));
EXPECT_TRUE(isValidIdentifier("_a"));
EXPECT_TRUE(isValidIdentifier("_z"));
EXPECT_TRUE(isValidIdentifier("_A"));
EXPECT_TRUE(isValidIdentifier("_Z"));
// 3 characters, '__' prefix
EXPECT_FALSE(isValidIdentifier("__."));
EXPECT_FALSE(isValidIdentifier("__\n"));
EXPECT_FALSE(isValidIdentifier("__ "));
EXPECT_FALSE(isValidIdentifier("__\x80"));
EXPECT_FALSE(isValidIdentifier("__\xc2"));
EXPECT_FALSE(isValidIdentifier("__\xff"));
EXPECT_FALSE(isValidIdentifier("__$"));
EXPECT_TRUE(isValidIdentifier("__1"));
EXPECT_TRUE(isValidIdentifier("___"));
EXPECT_TRUE(isValidIdentifier("__a"));
EXPECT_TRUE(isValidIdentifier("__z"));
EXPECT_TRUE(isValidIdentifier("__A"));
EXPECT_TRUE(isValidIdentifier("__Z"));
// 3 characters, '_' prefix and suffix
EXPECT_FALSE(isValidIdentifier("_._"));
EXPECT_FALSE(isValidIdentifier("_\n_"));
EXPECT_FALSE(isValidIdentifier("_ _"));
EXPECT_FALSE(isValidIdentifier("_\x80_"));
EXPECT_FALSE(isValidIdentifier("_\xc2_"));
EXPECT_FALSE(isValidIdentifier("_\xff_"));
EXPECT_FALSE(isValidIdentifier("_$_"));
EXPECT_TRUE(isValidIdentifier("_1_"));
EXPECT_TRUE(isValidIdentifier("___"));
EXPECT_TRUE(isValidIdentifier("_a_"));
EXPECT_TRUE(isValidIdentifier("_z_"));
EXPECT_TRUE(isValidIdentifier("_A_"));
EXPECT_TRUE(isValidIdentifier("_Z_"));
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Basic/CMakeLists.txt
|
set(LLVM_LINK_COMPONENTS
Support
)
add_clang_unittest(BasicTests
CharInfoTest.cpp
DiagnosticTest.cpp
FileManagerTest.cpp
SourceManagerTest.cpp
VirtualFileSystemTest.cpp
)
target_link_libraries(BasicTests
clangBasic
clangLex
)
|
0 |
repos/DirectXShaderCompiler/tools/clang/unittests
|
repos/DirectXShaderCompiler/tools/clang/unittests/Basic/FileManagerTest.cpp
|
//===- unittests/Basic/FileMangerTest.cpp ------------ FileManger tests ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/FileSystemStatCache.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Config/llvm-config.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
// Used to create a fake file system for running the tests with such
// that the tests are not affected by the structure/contents of the
// file system on the machine running the tests.
class FakeStatCache : public FileSystemStatCache {
private:
// Maps a file/directory path to its desired stat result. Anything
// not in this map is considered to not exist in the file system.
llvm::StringMap<FileData, llvm::BumpPtrAllocator> StatCalls;
void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {
FileData Data;
Data.Name = Path;
Data.Size = 0;
Data.ModTime = 0;
Data.UniqueID = llvm::sys::fs::UniqueID(1, INode);
Data.IsDirectory = !IsFile;
Data.IsNamedPipe = false;
Data.InPCH = false;
StatCalls[Path] = Data;
}
public:
// Inject a file with the given inode value to the fake file system.
void InjectFile(const char *Path, ino_t INode) {
InjectFileOrDirectory(Path, INode, /*IsFile=*/true);
}
// Inject a directory with the given inode value to the fake file system.
void InjectDirectory(const char *Path, ino_t INode) {
InjectFileOrDirectory(Path, INode, /*IsFile=*/false);
}
// Implement FileSystemStatCache::getStat().
LookupResult getStat(const char *Path, FileData &Data, bool isFile,
std::unique_ptr<vfs::File> *F,
vfs::FileSystem &FS) override {
if (StatCalls.count(Path) != 0) {
Data = StatCalls[Path];
return CacheExists;
}
return CacheMissing; // This means the file/directory doesn't exist.
}
};
// The test fixture.
class FileManagerTest : public ::testing::Test {
protected:
FileManagerTest() : manager(options) {
}
FileSystemOptions options;
FileManager manager;
};
// When a virtual file is added, its getDir() field is set correctly
// (not NULL, correct name).
TEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {
const FileEntry *file = manager.getVirtualFile("foo.cpp", 42, 0);
ASSERT_TRUE(file != nullptr);
const DirectoryEntry *dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_STREQ(".", dir->getName());
file = manager.getVirtualFile("x/y/z.cpp", 42, 0);
ASSERT_TRUE(file != nullptr);
dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_STREQ("x/y", dir->getName());
}
// Before any virtual file is added, no virtual directory exists.
TEST_F(FileManagerTest, NoVirtualDirectoryExistsBeforeAVirtualFileIsAdded) {
// An empty FakeStatCache causes all stat calls made by the
// FileManager to report "file/directory doesn't exist". This
// avoids the possibility of the result of this test being affected
// by what's in the real file system.
manager.addStatCache(llvm::make_unique<FakeStatCache>());
EXPECT_EQ(nullptr, manager.getDirectory("virtual/dir/foo"));
EXPECT_EQ(nullptr, manager.getDirectory("virtual/dir"));
EXPECT_EQ(nullptr, manager.getDirectory("virtual"));
}
// When a virtual file is added, all of its ancestors should be created.
TEST_F(FileManagerTest, getVirtualFileCreatesDirectoryEntriesForAncestors) {
// Fake an empty real file system.
manager.addStatCache(llvm::make_unique<FakeStatCache>());
manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
EXPECT_EQ(nullptr, manager.getDirectory("virtual/dir/foo"));
const DirectoryEntry *dir = manager.getDirectory("virtual/dir");
ASSERT_TRUE(dir != nullptr);
EXPECT_STREQ("virtual/dir", dir->getName());
dir = manager.getDirectory("virtual");
ASSERT_TRUE(dir != nullptr);
EXPECT_STREQ("virtual", dir->getName());
}
// getFile() returns non-NULL if a real file exists at the given path.
TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("/tmp", 42);
statCache->InjectFile("/tmp/test", 43);
#ifdef LLVM_ON_WIN32
const char *DirName = "C:.";
const char *FileName = "C:test";
statCache->InjectDirectory(DirName, 44);
statCache->InjectFile(FileName, 45);
#endif
manager.addStatCache(std::move(statCache));
const FileEntry *file = manager.getFile("/tmp/test");
ASSERT_TRUE(file != nullptr);
EXPECT_STREQ("/tmp/test", file->getName());
const DirectoryEntry *dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_STREQ("/tmp", dir->getName());
#ifdef LLVM_ON_WIN32
file = manager.getFile(FileName);
ASSERT_TRUE(file != NULL);
dir = file->getDir();
ASSERT_TRUE(dir != NULL);
EXPECT_STREQ(DirName, dir->getName());
#endif
}
// getFile() returns non-NULL if a virtual file exists at the given path.
TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {
// Fake an empty real file system.
manager.addStatCache(llvm::make_unique<FakeStatCache>());
manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
const FileEntry *file = manager.getFile("virtual/dir/bar.h");
ASSERT_TRUE(file != nullptr);
EXPECT_STREQ("virtual/dir/bar.h", file->getName());
const DirectoryEntry *dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_STREQ("virtual/dir", dir->getName());
}
// getFile() returns different FileEntries for different paths when
// there's no aliasing.
TEST_F(FileManagerTest, getFileReturnsDifferentFileEntriesForDifferentFiles) {
// Inject two fake files into the file system. Different inodes
// mean the files are not symlinked together.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
statCache->InjectFile("foo.cpp", 42);
statCache->InjectFile("bar.cpp", 43);
manager.addStatCache(std::move(statCache));
const FileEntry *fileFoo = manager.getFile("foo.cpp");
const FileEntry *fileBar = manager.getFile("bar.cpp");
ASSERT_TRUE(fileFoo != nullptr);
ASSERT_TRUE(fileBar != nullptr);
EXPECT_NE(fileFoo, fileBar);
}
// getFile() returns NULL if neither a real file nor a virtual file
// exists at the given path.
TEST_F(FileManagerTest, getFileReturnsNULLForNonexistentFile) {
// Inject a fake foo.cpp into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
statCache->InjectFile("foo.cpp", 42);
manager.addStatCache(std::move(statCache));
// Create a virtual bar.cpp file.
manager.getVirtualFile("bar.cpp", 200, 0);
const FileEntry *file = manager.getFile("xyz.txt");
EXPECT_EQ(nullptr, file);
}
// The following tests apply to Unix-like system only.
#ifndef LLVM_ON_WIN32
// getFile() returns the same FileEntry for real files that are aliases.
TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedRealFiles) {
// Inject two real files with the same inode.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("abc", 41);
statCache->InjectFile("abc/foo.cpp", 42);
statCache->InjectFile("abc/bar.cpp", 42);
manager.addStatCache(std::move(statCache));
EXPECT_EQ(manager.getFile("abc/foo.cpp"), manager.getFile("abc/bar.cpp"));
}
// getFile() returns the same FileEntry for virtual files that have
// corresponding real files that are aliases.
TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedVirtualFiles) {
// Inject two real files with the same inode.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("abc", 41);
statCache->InjectFile("abc/foo.cpp", 42);
statCache->InjectFile("abc/bar.cpp", 42);
manager.addStatCache(std::move(statCache));
manager.getVirtualFile("abc/foo.cpp", 100, 0);
manager.getVirtualFile("abc/bar.cpp", 200, 0);
EXPECT_EQ(manager.getFile("abc/foo.cpp"), manager.getFile("abc/bar.cpp"));
}
TEST_F(FileManagerTest, addRemoveStatCache) {
manager.addStatCache(llvm::make_unique<FakeStatCache>());
auto statCacheOwner = llvm::make_unique<FakeStatCache>();
auto *statCache = statCacheOwner.get();
manager.addStatCache(std::move(statCacheOwner));
manager.addStatCache(llvm::make_unique<FakeStatCache>());
manager.removeStatCache(statCache);
}
#endif // !LLVM_ON_WIN32
} // anonymous namespace
|
0 |
repos/DirectXShaderCompiler/tools/clang
|
repos/DirectXShaderCompiler/tools/clang/test/lit.site.cfg.in
|
import sys
## Autogenerated by LLVM/Clang configuration.
# Do not edit!
config.llvm_src_root = "@LLVM_SOURCE_DIR@"
config.llvm_obj_root = "@LLVM_BINARY_DIR@"
config.llvm_tools_dir = "@LLVM_TOOLS_DIR@"
config.llvm_libs_dir = "@LLVM_LIBS_DIR@"
config.llvm_shlib_dir = "@SHLIBDIR@"
config.llvm_plugin_ext = "@LLVM_PLUGIN_EXT@"
config.lit_tools_dir = "@LLVM_LIT_TOOLS_DIR@"
config.clang_obj_root = "@CLANG_BINARY_DIR@"
config.clang_tools_dir = "@CLANG_TOOLS_DIR@"
config.host_triple = "@LLVM_HOST_TRIPLE@"
config.target_triple = "@TARGET_TRIPLE@"
config.llvm_use_sanitizer = "@LLVM_USE_SANITIZER@"
config.clang_arcmt = @ENABLE_CLANG_ARCMT@
config.clang_staticanalyzer = @ENABLE_CLANG_STATIC_ANALYZER@
config.clang_examples = @ENABLE_CLANG_EXAMPLES@
config.enable_shared = @ENABLE_SHARED@
config.enable_backtrace = "@ENABLE_BACKTRACES@"
config.host_arch = "@HOST_ARCH@"
config.spirv = "@ENABLE_SPIRV_CODEGEN@" =="ON"
# Support substitution of the tools and libs dirs with user parameters. This is
# used when we can't determine the tool dir at configuration time.
try:
config.clang_tools_dir = config.clang_tools_dir % lit_config.params
config.llvm_tools_dir = config.llvm_tools_dir % lit_config.params
config.llvm_shlib_dir = config.llvm_shlib_dir % lit_config.params
config.llvm_libs_dir = config.llvm_libs_dir % lit_config.params
except KeyError:
e = sys.exc_info()[1]
key, = e.args
lit_config.fatal("unable to find %r parameter, use '--param=%s=VALUE'" % (key,key))
# Let the main config do the real work.
lit_config.load_config(config, "@CLANG_SOURCE_DIR@/test/lit.cfg")
|
0 |
repos/DirectXShaderCompiler/tools/clang
|
repos/DirectXShaderCompiler/tools/clang/test/CMakeLists.txt
|
# Test runner infrastructure for Clang. This configures the Clang test trees
# for use by Lit, and delegates to LLVM's lit test handlers.
if (CMAKE_CFG_INTDIR STREQUAL ".")
set(LLVM_BUILD_MODE ".")
else ()
set(LLVM_BUILD_MODE "%(build_mode)s")
endif ()
string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} CLANG_TOOLS_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
configure_lit_site_cfg(
${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg
)
configure_lit_site_cfg(
${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.in
${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg
)
configure_lit_site_cfg(
${CMAKE_CURRENT_SOURCE_DIR}/taef/lit.site.cfg.in
${CMAKE_CURRENT_BINARY_DIR}/taef/lit.site.cfg
)
configure_lit_site_cfg(
${CMAKE_CURRENT_SOURCE_DIR}/taef_exec/lit.site.cfg.in
${CMAKE_CURRENT_BINARY_DIR}/taef_exec/lit.site.cfg
)
option(CLANG_TEST_USE_VG "Run Clang tests under Valgrind" OFF)
if(CLANG_TEST_USE_VG)
set(CLANG_TEST_EXTRA_ARGS ${CLANG_TEST_EXTRA_ARGS} "--vg")
endif ()
list(APPEND CLANG_TEST_DEPS
clang clang-headers
clang-check clang-format
c-index-test diagtool
clang-tblgen
)
if (CLANG_ENABLE_ARCMT)
list(APPEND CLANG_TEST_DEPS
arcmt-test
c-arcmt-test
)
endif ()
if (ENABLE_CLANG_EXAMPLES)
list(APPEND CLANG_TEST_DEPS
clang-interpreter
PrintFunctionNames
)
endif ()
if (ENABLE_CLANG_STATIC_ANALYZER AND ENABLE_CLANG_EXAMPLES)
list(APPEND CLANG_TEST_DEPS
SampleAnalyzerPlugin
)
endif ()
set(CLANG_TEST_PARAMS
clang_site_config=${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg
)
if( NOT CLANG_BUILT_STANDALONE )
list(APPEND CLANG_TEST_DEPS
llvm-config
llc opt FileCheck count not llvm-symbolizer llvm-profdata llvm-objdump
)
endif()
# HLSL Change Begin
# Explicitly overriding check-clang dependencies for HLSL
set(CLANG_TEST_DEPS dxc dxa dxopt dxl dxv dxr dxcompiler clang-tblgen llvm-config opt FileCheck count not ClangUnitTests)
if (WIN32)
list(APPEND CLANG_TEST_DEPS
dxc_batch ExecHLSLTests
)
endif()
add_custom_target(clang-test-depends DEPENDS ${CLANG_TEST_DEPS})
set_target_properties(clang-test-depends PROPERTIES FOLDER "Clang tests")
# HLSL Change End
add_lit_testsuite(check-clang "Running the Clang regression tests"
${CMAKE_CURRENT_BINARY_DIR}
#LIT ${LLVM_LIT}
PARAMS ${CLANG_TEST_PARAMS}
skip_taef_exec=False
DEPENDS ${CLANG_TEST_DEPS}
ARGS ${CLANG_TEST_EXTRA_ARGS}
)
set_target_properties(check-clang PROPERTIES FOLDER "Clang tests")
# Add a legacy target spelling: clang-test
add_custom_target(clang-test)
add_dependencies(clang-test check-clang)
set_target_properties(clang-test PROPERTIES FOLDER "Clang tests")
# HLSL Change Begin - Generate lit targets for test subdirectories.
set(CLANG_TEST_PARAMS
${CLANG_TEST_PARAMS}
clang_unit_site_config=${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg
clang_taef_site_config=${CMAKE_CURRENT_BINARY_DIR}/taef/lit.site.cfg
no_priority=True
clang_taef_exec_site_config=${CMAKE_CURRENT_BINARY_DIR}/taef_exec/lit.site.cfg
)
add_lit_testsuites(CLANG ${CMAKE_CURRENT_SOURCE_DIR}
PARAMS ${CLANG_TEST_PARAMS}
DEPENDS ${CLANG_TEST_DEPS}
FOLDER "Clang tests/Suites"
)
# Manually generate targets that we need to expose in visual studio builds.
# The code below here _ONLY_ executes when building with Visual Studio or Xcode.
if (NOT CMAKE_CONFIGURATION_TYPES)
return()
endif()
# Add the unit test suite
add_lit_target("check-clang-unit" "Running lit suite clang-unit"
${CMAKE_CURRENT_SOURCE_DIR}/Unit
PARAMS ${CLANG_TEST_PARAMS}
DEPENDS ClangUnitTests
ARGS ${CLANG_TEST_EXTRA_ARGS}
)
# Add TAEF targets
if (WIN32)
add_lit_target("check-clang-taef" "Running lit suite hlsl"
${CMAKE_CURRENT_SOURCE_DIR}/taef
PARAMS ${CLANG_TEST_PARAMS}
DEPENDS ClangHLSLTests
ARGS ${CLANG_TEST_EXTRA_ARGS}
)
set(TAEF_EXEC_ADAPTER "" CACHE STRING "adapter for taef exec test")
add_lit_target("check-clang-taef-exec" "Running lit suite hlsl execution test"
${CMAKE_CURRENT_SOURCE_DIR}/taef_exec
PARAMS ${CLANG_TEST_PARAMS}
adapter=${TAEF_EXEC_ADAPTER}
DEPENDS ExecHLSLTests dxexp
ARGS ${CLANG_TEST_EXTRA_ARGS}
)
endif()
# HLSL Change End
|
0 |
repos/DirectXShaderCompiler/tools/clang
|
repos/DirectXShaderCompiler/tools/clang/test/TestRunner.sh
|
#!/bin/sh
#
# TestRunner.sh - Backward compatible utility for testing an individual file.
# Find where this script is.
Dir=$(dirname $(which $0))
AbsDir=$(cd $Dir; pwd)
# Find 'lit', assuming standard layout.
lit=$AbsDir/../../../utils/lit/lit.py
# Dispatch to lit.
$lit "$@"
|
0 |
repos/DirectXShaderCompiler/tools/clang
|
repos/DirectXShaderCompiler/tools/clang/test/make_test_dirs.pl
|
#!/usr/bin/perl -w
#
# Simple little Perl script that takes the cxx-sections.data file as
# input and generates a directory structure that mimics the standard's
# structure.
use English;
$current_indent_level = -4;
while ($line = <STDIN>) {
$line =~ /^\s*/;
$next_indent_level = length($MATCH);
if ($line =~ /\[([^\]]*)\]/) {
my $section = $1;
while ($next_indent_level < $current_indent_level) {
chdir("..");
$current_indent_level -= 4;
}
if ($next_indent_level == $current_indent_level) {
chdir("..");
} else {
$current_indent_level = $next_indent_level;
}
mkdir($section);
chdir($section);
}
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/test/SemaCUDA
|
repos/DirectXShaderCompiler/tools/clang/test/SemaCUDA/Inputs/cuda.h
|
/* Minimal declarations for CUDA support. Testing purposes only. */
#include <stddef.h>
#define __constant__ __attribute__((constant))
#define __device__ __attribute__((device))
#define __global__ __attribute__((global))
#define __host__ __attribute__((host))
#define __shared__ __attribute__((shared))
#define __launch_bounds__(...) __attribute__((launch_bounds(__VA_ARGS__)))
struct dim3 {
unsigned x, y, z;
__host__ __device__ dim3(unsigned x, unsigned y = 1, unsigned z = 1) : x(x), y(y), z(z) {}
};
typedef struct cudaStream *cudaStream_t;
int cudaConfigureCall(dim3 gridSize, dim3 blockSize, size_t sharedSize = 0,
cudaStream_t stream = 0);
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/arm-neon-header.c
|
// RUN: %clang_cc1 -triple thumbv7-apple-darwin10 -target-cpu cortex-a8 -fsyntax-only -Wvector-conversions -ffreestanding %s
// RUN: %clang_cc1 -triple thumbv7-apple-darwin10 -target-cpu cortex-a8 -fsyntax-only -fno-lax-vector-conversions -ffreestanding %s
// RUN: %clang_cc1 -x c++ -triple thumbv7-apple-darwin10 -target-cpu cortex-a8 -fsyntax-only -Wvector-conversions -ffreestanding %s
#include <arm_neon.h>
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/stdbool.cpp
|
// RUN: %clang_cc1 -E -dM %s | FileCheck --check-prefix=CHECK-GNU-COMPAT %s
// RUN: %clang_cc1 -std=c++98 -E -dM %s | FileCheck --check-prefix=CHECK-CONFORMING %s
// RUN: %clang_cc1 -fsyntax-only -std=gnu++98 -verify -Weverything %s
#include <stdbool.h>
#define zzz
// CHECK-GNU-COMPAT: #define _Bool bool
// CHECK-GNU-COMPAT: #define bool bool
// CHECK-GNU-COMPAT: #define false false
// CHECK-GNU-COMPAT: #define true true
// CHECK-CONFORMING-NOT: #define _Bool
// CHECK-CONFORMING: #define __CHAR_BIT__
// CHECK-CONFORMING-NOT: #define false false
// CHECK-CONFORMING: #define zzz
zzz
// expected-no-diagnostics
extern bool x;
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/arm-acle-header.c
|
// RUN: %clang_cc1 -triple armv7-eabi -target-cpu cortex-a15 -fsyntax-only -ffreestanding %s
// RUN: %clang_cc1 -triple aarch64-eabi -target-cpu cortex-a53 -fsyntax-only -ffreestanding %s
// RUN: %clang_cc1 -triple thumbv7-windows -target-cpu cortex-a53 -fsyntax-only -ffreestanding %s
// RUN: %clang_cc1 -x c++ -triple armv7-eabi -target-cpu cortex-a15 -fsyntax-only -ffreestanding %s
// RUN: %clang_cc1 -x c++ -triple aarch64-eabi -target-cpu cortex-a57 -fsyntax-only -ffreestanding %s
// RUN: %clang_cc1 -x c++ -triple thumbv7-windows -target-cpu cortex-a15 -fsyntax-only -ffreestanding %s
// expected-no-diagnostics
#include <arm_acle.h>
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/unwind.c
|
// RUN: %clang_cc1 -triple arm-unknown-linux-gnueabi \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only %s
// RUN: %clang_cc1 -triple mips-unknown-linux \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only %s
// RUN: %clang_cc1 -triple i686-unknown-linux \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only %s
// RUN: %clang_cc1 -triple x86_64-unknown-linux \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only %s
// RUN: %clang_cc1 -triple arm-unknown-linux-gnueabi \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only -x c++ %s
// RUN: %clang_cc1 -triple mips-unknown-linux \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only -x c++ %s
// RUN: %clang_cc1 -triple i686-unknown-linux \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only -x c++ %s
// RUN: %clang_cc1 -triple x86_64-unknown-linux \
// RUN: -isystem %S/Inputs/include -ffreestanding -fsyntax-only -x c++ %s
#include "unwind.h"
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/ms-null-ms-header-vs-stddef.cpp
|
// RUN: %clang_cc1 -fsyntax-only -triple i686-pc-win32 -fms-compatibility -fms-compatibility-version=17.00 %s
// RUN: %clang_cc1 -fsyntax-only -triple i386-mingw32 %s
// Something in MSVC's headers (pulled in e.g. by <crtdefs.h>) defines __null
// to something, mimick that.
#define __null
#include <stddef.h>
// __null is used as a type annotation in MS headers, with __null defined to
// nothing in regular builds. This should continue to work even with stddef.h
// included.
void f(__null void* p) { }
// NULL should work fine even with __null defined to nothing.
void* p = NULL;
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/int64-type.c
|
// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -verify %s -ffreestanding
// expected-no-diagnostics
#include <stdint.h>
typedef unsigned long long uint64_t;
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/c89.c
|
// RUN: %clang_cc1 -triple i386-apple-darwin10 -target-cpu yonah -fsyntax-only -verify -std=c89 %s
// expected-no-diagnostics
// FIXME: Disable inclusion of mm_malloc.h, our current implementation is broken
// on win32 since we don't generally know how to find errno.h.
#define __MM_MALLOC_H
// PR6658
#include <xmmintrin.h>
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/typedef_guards.c
|
// RUN: %clang_cc1 -fsyntax-only -verify %s
// expected-no-diagnostics
// NULL is rdefined in stddef.h
#define NULL ((void*) 0)
// These are headers bundled with Clang.
#include <stdarg.h>
#include <stddef.h>
#ifndef _VA_LIST
typedef __builtin_va_list va_list;
#endif
#ifndef _SIZE_T
typedef __typeof__(sizeof(int)) size_t;
#endif
#ifndef _WCHAR_T
typedef __typeof__(*L"") wchar_t;
#endif
extern void foo(wchar_t x);
extern void bar(size_t x);
void *baz() { return NULL; }
void quz() {
va_list y;
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/c11.c
|
// RUN: rm -rf %t
// RUN: %clang_cc1 -fsyntax-only -verify -std=c11 %s
// RUN: %clang_cc1 -fsyntax-only -verify -std=c11 -fmodules -fmodules-cache-path=%t %s -D__STDC_WANT_LIB_EXT1__=1
// RUN: %clang_cc1 -fsyntax-only -verify -std=c11 -ffreestanding %s
// RUN: %clang_cc1 -fsyntax-only -verify -std=c11 -triple i686-pc-win32 -fms-compatibility-version=17.00 %s
noreturn int f(); // expected-error 1+{{}}
#include <stdnoreturn.h>
#include <stdnoreturn.h>
#include <stdnoreturn.h>
int g();
noreturn int g();
int noreturn g();
int g();
#include <stdalign.h>
_Static_assert(__alignas_is_defined, "");
_Static_assert(__alignof_is_defined, "");
alignas(alignof(int)) char c[4];
_Static_assert(__alignof(c) == 4, "");
#define __STDC_WANT_LIB_EXT1__ 1
#include <stddef.h>
rsize_t x = 0;
_Static_assert(sizeof(max_align_t) >= sizeof(long long), "");
_Static_assert(alignof(max_align_t) >= alignof(long long), "");
_Static_assert(sizeof(max_align_t) >= sizeof(long double), "");
_Static_assert(alignof(max_align_t) >= alignof(long double), "");
#ifdef _MSC_VER
_Static_assert(sizeof(max_align_t) == sizeof(double), "");
#endif
// If we are freestanding, then also check RSIZE_MAX (in a hosted implementation
// we will use the host stdint.h, which may not yet have C11 support).
#ifndef __STDC_HOSTED__
#include <stdint.h>
rsize_t x2 = RSIZE_MAX;
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/xmmintrin.c
|
// RUN: %clang_cc1 %s -ffreestanding -triple x86_64-apple-macosx10.9.0 -emit-llvm -o - | FileCheck %s
//
// RUN: rm -rf %t
// RUN: %clang_cc1 %s -ffreestanding -triple x86_64-apple-macosx10.9.0 -emit-llvm -o - \
// RUN: -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -isystem %S/Inputs/include \
// RUN: | FileCheck %s
// REQUIRES: x86-registered-target
#include <xmmintrin.h>
// Make sure the last step of _mm_cvtps_pi16 converts <4 x i32> to <4 x i16> by
// checking that clang emits PACKSSDW instead of PACKSSWB.
// CHECK: define i64 @test_mm_cvtps_pi16
// CHECK: call x86_mmx @llvm.x86.mmx.packssdw
__m64 test_mm_cvtps_pi16(__m128 a) {
return _mm_cvtps_pi16(a);
}
// Make sure that including <xmmintrin.h> also makes <emmintrin.h>'s content available.
// This is an ugly hack for GCC compatibility.
__m128 test_xmmintrin_provides_emmintrin(__m128d __a, __m128d __b) {
return _mm_add_sd(__a, __b);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/stddefneeds.cpp
|
// RUN: %clang_cc1 -fsyntax-only -triple x86_64-apple-macosx10.9.0 -verify -Wsentinel -std=c++11 %s
ptrdiff_t p0; // expected-error{{unknown}}
size_t s0; // expected-error{{unknown}}
void* v0 = NULL; // expected-error{{undeclared}}
wint_t w0; // expected-error{{unknown}}
max_align_t m0; // expected-error{{unknown}}
#define __need_ptrdiff_t
#include <stddef.h>
ptrdiff_t p1;
size_t s1; // expected-error{{unknown}}
void* v1 = NULL; // expected-error{{undeclared}}
wint_t w1; // expected-error{{unknown}}
max_align_t m1; // expected-error{{unknown}}
#define __need_size_t
#include <stddef.h>
ptrdiff_t p2;
size_t s2;
void* v2 = NULL; // expected-error{{undeclared}}
wint_t w2; // expected-error{{unknown}}
max_align_t m2; // expected-error{{unknown}}
#define __need_NULL
#include <stddef.h>
ptrdiff_t p3;
size_t s3;
void* v3 = NULL;
wint_t w3; // expected-error{{unknown}}
max_align_t m3; // expected-error{{unknown}}
// Shouldn't bring in wint_t by default:
#include <stddef.h>
ptrdiff_t p4;
size_t s4;
void* v4 = NULL;
wint_t w4; // expected-error{{unknown}}
max_align_t m4;
#define __need_wint_t
#include <stddef.h>
ptrdiff_t p5;
size_t s5;
void* v5 = NULL;
wint_t w5;
max_align_t m5;
// linux/stddef.h does something like this for cpp files:
#undef NULL
#define NULL 0
// glibc (and other) headers then define __need_NULL and rely on stddef.h
// to redefine NULL to the correct value again.
#define __need_NULL
#include <stddef.h>
// gtk headers then use __attribute__((sentinel)), which doesn't work if NULL
// is 0.
void f(const char* c, ...) __attribute__((sentinel));
void g() {
f("", NULL); // Shouldn't warn.
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/wmmintrin.c
|
// Check that wmmintrin.h is includable with just -maes.
// RUN: %clang_cc1 -triple x86_64-unknown-unknown \
// RUN: -verify %s -ffreestanding -target-feature +aes
// expected-no-diagnostics
#include <wmmintrin.h>
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/x86-intrinsics-headers.c
|
// RUN: %clang_cc1 -fsyntax-only -ffreestanding %s
// RUN: %clang_cc1 -fsyntax-only -ffreestanding -fno-lax-vector-conversions %s
// RUN: %clang_cc1 -fsyntax-only -ffreestanding -x c++ %s
#if defined(i386) || defined(__x86_64__)
#ifdef __SSE4_2__
// nmmintrin forwards to smmintrin.
#include <nmmintrin.h>
#endif
// immintrin includes all other intel intrinsic headers.
#include <immintrin.h>
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/x86_64-apple-macosx-types.cpp
|
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -std=c++11 -verify %s
// expected-no-diagnostics
struct true_type {
static constexpr const bool value = true;
};
struct false_type {
static constexpr const bool value = false;
};
template <class _Tp, class _Up> struct is_same : public false_type {};
template <class _Tp> struct is_same<_Tp, _Tp> : public true_type {};
// Check that our 'is_same' works.
static_assert(is_same<char, char>::value, "is_same is broken");
static_assert(!is_same<char, char *>::value, "is_same is broken");
template <class _Tp, unsigned _AlignOf, unsigned _SizeOf>
struct check_type {
static constexpr const bool value =
(alignof(_Tp) == _AlignOf) && (sizeof(_Tp) == _SizeOf);
};
//===----------------------------------------------------------------------===//
// Fundamental types
//===----------------------------------------------------------------------===//
static_assert(check_type<bool, 1, 1>::value, "bool is wrong");
static_assert(check_type<char, 1, 1>::value, "char is wrong");
static_assert(check_type<signed char, 1, 1>::value, "signed char is wrong");
static_assert(check_type<unsigned char, 1, 1>::value, "unsigned char is wrong");
static_assert(check_type<char16_t, 2, 2>::value, "char16_t is wrong");
static_assert(check_type<char32_t, 4, 4>::value, "char32_t is wrong");
static_assert(check_type<wchar_t, 4, 4>::value, "wchar_t is wrong");
static_assert(check_type<short, 2, 2>::value, "short is wrong");
static_assert(check_type<unsigned short, 2, 2>::value, "unsigned short is wrong");
static_assert(check_type<int, 4, 4>::value, "int is wrong");
static_assert(check_type<unsigned int, 4, 4>::value, "unsigned int is wrong");
static_assert(check_type<long, 8, 8>::value, "long is wrong");
static_assert(check_type<unsigned long, 8, 8>::value, "unsigned long is wrong");
static_assert(check_type<long long, 8, 8>::value, "long long is wrong");
static_assert(check_type<unsigned long long, 8, 8>::value, "unsigned long long is wrong");
static_assert(check_type<float, 4, 4>::value, "float is wrong");
static_assert(check_type<double, 8, 8>::value, "double is wrong");
static_assert(check_type<long double, 16, 16>::value, "long double is wrong");
static_assert(check_type<void *, 8, 8>::value, "'void *' is wrong");
static_assert(check_type<int (*)(int), 8, 8>::value, "function pointer is wrong");
//===----------------------------------------------------------------------===//
// stdarg.h
//===----------------------------------------------------------------------===//
#include <stdarg.h>
static_assert(check_type<va_list, 8, 24>::value, "va_list is wrong");
//===----------------------------------------------------------------------===//
// stddef.h
//===----------------------------------------------------------------------===//
#define __STDC_WANT_LIB_EXT1__ 1
#include <stddef.h>
static_assert(is_same<long int, ::ptrdiff_t>::value, "::ptrdiff_t is wrong");
static_assert(is_same<decltype(sizeof(char)), ::size_t>::value, "::size_t is wrong");
static_assert(is_same<long unsigned int, ::size_t>::value, "::size_t is wrong");
static_assert(is_same<long unsigned int, ::rsize_t>::value, "::rsize_t is wrong");
static_assert(is_same<long double, ::max_align_t>::value, "::max_align_t is wrong");
#define __need_wint_t
#include <stddef.h>
static_assert(is_same<int, ::wint_t>::value, "::wint_t is wrong");
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/thumbv7-apple-ios-types.cpp
|
// RUN: %clang_cc1 -triple thumbv7-apple-ios7.0 -target-abi apcs-gnu -std=c++11 -verify %s
// expected-no-diagnostics
struct true_type {
static constexpr const bool value = true;
};
struct false_type {
static constexpr const bool value = false;
};
template <class _Tp, class _Up> struct is_same : public false_type {};
template <class _Tp> struct is_same<_Tp, _Tp> : public true_type {};
// Check that our 'is_same' works.
static_assert(is_same<char, char>::value, "is_same is broken");
static_assert(!is_same<char, char *>::value, "is_same is broken");
template <class _Tp, unsigned _AlignOf, unsigned _SizeOf>
struct check_type {
static constexpr const bool value =
(alignof(_Tp) == _AlignOf) && (sizeof(_Tp) == _SizeOf);
};
//===----------------------------------------------------------------------===//
// Fundamental types
//===----------------------------------------------------------------------===//
static_assert(check_type<bool, 1, 1>::value, "bool is wrong");
static_assert(check_type<char, 1, 1>::value, "char is wrong");
static_assert(check_type<signed char, 1, 1>::value, "signed char is wrong");
static_assert(check_type<unsigned char, 1, 1>::value, "unsigned char is wrong");
static_assert(check_type<char16_t, 2, 2>::value, "char16_t is wrong");
static_assert(check_type<char32_t, 4, 4>::value, "char32_t is wrong");
static_assert(check_type<wchar_t, 4, 4>::value, "wchar_t is wrong");
static_assert(check_type<short, 2, 2>::value, "short is wrong");
static_assert(check_type<unsigned short, 2, 2>::value, "unsigned short is wrong");
static_assert(check_type<int, 4, 4>::value, "int is wrong");
static_assert(check_type<unsigned int, 4, 4>::value, "unsigned int is wrong");
static_assert(check_type<long, 4, 4>::value, "long is wrong");
static_assert(check_type<unsigned long, 4, 4>::value, "unsigned long is wrong");
static_assert(check_type<long long, 8, 8>::value, "long long is wrong");
static_assert(check_type<unsigned long long, 8, 8>::value, "unsigned long long is wrong");
static_assert(check_type<float, 4, 4>::value, "float is wrong");
static_assert(check_type<double, 8, 8>::value, "double is wrong");
static_assert(check_type<long double, 4, 8>::value, "long double is wrong");
static_assert(check_type<void *, 4, 4>::value, "'void *' is wrong");
static_assert(check_type<int (*)(int), 4, 4>::value, "function pointer is wrong");
//===----------------------------------------------------------------------===//
// stdarg.h
//===----------------------------------------------------------------------===//
#include <stdarg.h>
static_assert(check_type<va_list, 4, 4>::value, "va_list is wrong");
//===----------------------------------------------------------------------===//
// stddef.h
//===----------------------------------------------------------------------===//
#define __STDC_WANT_LIB_EXT1__ 1
#include <stddef.h>
static_assert(is_same<int, ::ptrdiff_t>::value, "::ptrdiff_t is wrong");
static_assert(is_same<decltype(sizeof(char)), ::size_t>::value, "::size_t is wrong");
static_assert(is_same<long unsigned int, ::size_t>::value, "::size_t is wrong");
static_assert(is_same<long unsigned int, ::rsize_t>::value, "::rsize_t is wrong");
static_assert(is_same<long double, ::max_align_t>::value, "::max_align_t is wrong");
#define __need_wint_t
#include <stddef.h>
static_assert(is_same<int, ::wint_t>::value, "::wint_t is wrong");
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/arm64-apple-ios-types.cpp
|
// RUN: %clang_cc1 -triple arm64-apple-ios7.0 -std=c++11 -verify %s
// expected-no-diagnostics
struct true_type {
static constexpr const bool value = true;
};
struct false_type {
static constexpr const bool value = false;
};
template <class _Tp, class _Up> struct is_same : public false_type {};
template <class _Tp> struct is_same<_Tp, _Tp> : public true_type {};
// Check that our 'is_same' works.
static_assert(is_same<char, char>::value, "is_same is broken");
static_assert(!is_same<char, char *>::value, "is_same is broken");
template <class _Tp, unsigned _AlignOf, unsigned _SizeOf>
struct check_type {
static constexpr const bool value =
(alignof(_Tp) == _AlignOf) && (sizeof(_Tp) == _SizeOf);
};
//===----------------------------------------------------------------------===//
// Fundamental types
//===----------------------------------------------------------------------===//
static_assert(check_type<bool, 1, 1>::value, "bool is wrong");
static_assert(check_type<char, 1, 1>::value, "char is wrong");
static_assert(check_type<signed char, 1, 1>::value, "signed char is wrong");
static_assert(check_type<unsigned char, 1, 1>::value, "unsigned char is wrong");
static_assert(check_type<char16_t, 2, 2>::value, "char16_t is wrong");
static_assert(check_type<char32_t, 4, 4>::value, "char32_t is wrong");
static_assert(check_type<wchar_t, 4, 4>::value, "wchar_t is wrong");
static_assert(check_type<short, 2, 2>::value, "short is wrong");
static_assert(check_type<unsigned short, 2, 2>::value, "unsigned short is wrong");
static_assert(check_type<int, 4, 4>::value, "int is wrong");
static_assert(check_type<unsigned int, 4, 4>::value, "unsigned int is wrong");
static_assert(check_type<long, 8, 8>::value, "long is wrong");
static_assert(check_type<unsigned long, 8, 8>::value, "unsigned long is wrong");
static_assert(check_type<long long, 8, 8>::value, "long long is wrong");
static_assert(check_type<unsigned long long, 8, 8>::value, "unsigned long long is wrong");
static_assert(check_type<float, 4, 4>::value, "float is wrong");
static_assert(check_type<double, 8, 8>::value, "double is wrong");
static_assert(check_type<long double, 8, 8>::value, "long double is wrong");
static_assert(check_type<void *, 8, 8>::value, "'void *' is wrong");
static_assert(check_type<int (*)(int), 8, 8>::value, "function pointer is wrong");
//===----------------------------------------------------------------------===//
// stdarg.h
//===----------------------------------------------------------------------===//
#include <stdarg.h>
static_assert(check_type<va_list, 8, 8>::value, "va_list is wrong");
//===----------------------------------------------------------------------===//
// stddef.h
//===----------------------------------------------------------------------===//
#define __STDC_WANT_LIB_EXT1__ 1
#include <stddef.h>
static_assert(is_same<long int, ::ptrdiff_t>::value, "::ptrdiff_t is wrong");
static_assert(is_same<decltype(sizeof(char)), ::size_t>::value, "::size_t is wrong");
static_assert(is_same<long unsigned int, ::size_t>::value, "::size_t is wrong");
static_assert(is_same<long unsigned int, ::rsize_t>::value, "::rsize_t is wrong");
static_assert(is_same<long double, ::max_align_t>::value, "::max_align_t is wrong");
#define __need_wint_t
#include <stddef.h>
static_assert(is_same<int, ::wint_t>::value, "::wint_t is wrong");
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/altivec-header.c
|
// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -faltivec -ffreestanding -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -faltivec -ffreestanding -emit-llvm -fno-lax-vector-conversions -o - %s | FileCheck %s
// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -faltivec -ffreestanding -emit-llvm -x c++ -o - %s | FileCheck %s
#include <altivec.h>
// Verify that simply including <altivec.h> does not generate any code
// (i.e. all inline routines in the header are marked "static")
// CHECK: target triple = "powerpc64-
// CHECK-NEXT: {{^$}}
// CHECK-NEXT: llvm.ident
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/x86intrin.c
|
// RUN: %clang_cc1 -fsyntax-only -ffreestanding %s -verify
// RUN: %clang_cc1 -fsyntax-only -ffreestanding -fno-lax-vector-conversions %s -verify
// RUN: %clang_cc1 -fsyntax-only -ffreestanding -x c++ %s -verify
// expected-no-diagnostics
#if defined(i386) || defined(__x86_64__)
// Pretend to enable all features.
#ifndef __3dNOW__
#define __3dNOW__
#endif
#ifndef __BMI__
#define __BMI__
#endif
#ifndef __BMI2__
#define __BMI2__
#endif
#ifndef __LZCNT__
#define __LZCNT__
#endif
#ifndef __POPCNT__
#define __POPCNT__
#endif
#ifndef __RDSEED__
#define __RDSEED__
#endif
#ifndef __PRFCHW__
#define __PRFCHW__
#endif
#ifndef __SSE4A__
#define __SSE4A__
#endif
#ifndef __FMA4__
#define __FMA4__
#endif
#ifndef __XOP__
#define __XOP__
#endif
#ifndef __F16C__
#define __F16C__
#endif
#ifndef __MMX__
#define __MMX__
#endif
#ifndef __SSE__
#define __SSE__
#endif
#ifndef __SSE2__
#define __SSE2__
#endif
#ifndef __SSE3__
#define __SSE3__
#endif
#ifndef __SSSE3__
#define __SSSE3__
#endif
#ifndef __SSE4_1__
#define __SSE4_1__
#endif
#ifndef __SSE4_2__
#define __SSE4_2__
#endif
#ifndef __AES__
#define __AES__
#endif
#ifndef __AVX__
#define __AVX__
#endif
#ifndef __AVX2__
#define __AVX2__
#endif
#ifndef __BMI__
#define __BMI__
#endif
#ifndef __BMI2__
#define __BMI2__
#endif
#ifndef __LZCNT__
#define __LZCNT__
#endif
#ifndef __FMA__
#define __FMA__
#endif
#ifndef __RDRND__
#define __RDRND__
#endif
#ifndef __SHA__
#define __SHA__
#endif
#ifndef __ADX__
#define __ADX__
#endif
#ifndef __TBM__
#define __TBM__
#endif
#ifndef __RTM__
#define __RTM__
#endif
#ifndef __PCLMUL__
#define __PCLMUL__
#endif
#ifndef __FSGSBASE__
#define __FSGSBASE__
#endif
#ifndef __AVX512F__
#define __AVX512F__
#endif
#ifndef __AVX512VL__
#define __AVX512VL__
#endif
#ifndef __AVX512BW__
#define __AVX512BW__
#endif
#ifndef __AVX512ER__
#define __AVX512ER__
#endif
#ifndef __AVX512PF__
#define __AVX512PF__
#endif
#ifndef __AVX512DQ__
#define __AVX512DQ__
#endif
#ifndef __AVX512CD__
#define __AVX512CD__
#endif
// Now include the metaheader that includes all x86 intrinsic headers.
#include <x86intrin.h>
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/tgmath.c
|
// RUN: %clang_cc1 -fsyntax-only -isystem %S/Inputs/include -verify %s
// expected-no-diagnostics
#include <tgmath.h>
float f;
double d;
long double l;
float complex fc;
double complex dc;
long double complex lc;
// creal
_Static_assert(sizeof(creal(f)) == sizeof(f), "");
_Static_assert(sizeof(creal(d)) == sizeof(d), "");
_Static_assert(sizeof(creal(l)) == sizeof(l), "");
_Static_assert(sizeof(creal(fc)) == sizeof(f), "");
_Static_assert(sizeof(creal(dc)) == sizeof(d), "");
_Static_assert(sizeof(creal(lc)) == sizeof(l), "");
// fabs
_Static_assert(sizeof(fabs(f)) == sizeof(f), "");
_Static_assert(sizeof(fabs(d)) == sizeof(d), "");
_Static_assert(sizeof(fabs(l)) == sizeof(l), "");
_Static_assert(sizeof(fabs(fc)) == sizeof(f), "");
_Static_assert(sizeof(fabs(dc)) == sizeof(d), "");
_Static_assert(sizeof(fabs(lc)) == sizeof(l), "");
// logb
_Static_assert(sizeof(logb(f)) == sizeof(f), "");
_Static_assert(sizeof(logb(d)) == sizeof(d), "");
_Static_assert(sizeof(logb(l)) == sizeof(l), "");
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/ms-intrin.cpp
|
// RUN: %clang_cc1 -triple i386-pc-win32 -target-cpu pentium4 \
// RUN: -fms-extensions -fms-compatibility -fms-compatibility-version=17.00 \
// RUN: -ffreestanding -fsyntax-only -Werror \
// RUN: -isystem %S/Inputs/include %s
// RUN: %clang_cc1 -triple i386-pc-win32 -target-cpu broadwell \
// RUN: -fms-extensions -fms-compatibility -fms-compatibility-version=17.00 \
// RUN: -ffreestanding -fsyntax-only -Werror \
// RUN: -isystem %S/Inputs/include %s
// RUN: %clang_cc1 -triple x86_64-pc-win32 \
// RUN: -fms-extensions -fms-compatibility -fms-compatibility-version=17.00 \
// RUN: -ffreestanding -fsyntax-only -Werror \
// RUN: -isystem %S/Inputs/include %s
// RUN: %clang_cc1 -triple thumbv7--windows \
// RUN: -fms-compatibility -fms-compatibility-version=17.00 \
// RUN: -ffreestanding -fsyntax-only -Werror \
// RUN: -isystem %S/Inputs/include %s
// Intrin.h needs size_t, but -ffreestanding prevents us from getting it from
// stddef.h. Work around it with this typedef.
typedef __SIZE_TYPE__ size_t;
#include <Intrin.h>
// Use some C++ to make sure we closed the extern "C" brackets.
template <typename T>
void foo(T V) {}
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/wchar_limits.cpp
|
// RUN: %clang_cc1 -ffreestanding -fsyntax-only -verify %s
// RUN: %clang_cc1 -ffreestanding -fsyntax-only -verify -fshort-wchar %s
// expected-no-diagnostics
#include <stdint.h>
const bool swchar = (wchar_t)-1 > (wchar_t)0;
int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/ms-wchar.c
|
// RUN: %clang_cc1 -fsyntax-only -triple i386-pc-win32 -fms-compatibility %s
#if defined(_WCHAR_T_DEFINED)
#error "_WCHAR_T_DEFINED should not be defined in C99"
#endif
#include <stddef.h>
#if !defined(_WCHAR_T_DEFINED)
#error "_WCHAR_T_DEFINED should have been set by stddef.h"
#endif
#if defined(_NATIVE_WCHAR_T_DEFINED)
#error "_NATIVE_WCHAR_T_DEFINED should not be defined"
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/cxx11.cpp
|
// RUN: rm -rf %t
// RUN: %clang_cc1 -ffreestanding -fsyntax-only -std=c++11 %s
// RUN: %clang_cc1 -ffreestanding -fsyntax-only -std=c++11 -fmodules -fmodules-cache-path=%t %s
// This test fails on systems with older OS X 10.9 SDK headers, see PR18322.
#include <stdalign.h>
#if defined alignas
#error alignas should not be defined in C++
#endif
#if defined alignof
#error alignof should not be defined in C++
#endif
static_assert(__alignas_is_defined, "");
static_assert(__alignof_is_defined, "");
#include <stdint.h>
#ifndef SIZE_MAX
#error SIZE_MAX should be defined in C++
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/limits.cpp
|
// RUN: %clang_cc1 -ffreestanding -fsyntax-only -verify %s
// RUN: %clang_cc1 -fno-signed-char -ffreestanding -fsyntax-only -verify %s
// RUN: %clang_cc1 -std=c++11 -ffreestanding -fsyntax-only -verify %s
// expected-no-diagnostics
#include <limits.h>
_Static_assert(SCHAR_MAX == -(SCHAR_MIN+1), "");
_Static_assert(SHRT_MAX == -(SHRT_MIN+1), "");
_Static_assert(INT_MAX == -(INT_MIN+1), "");
_Static_assert(LONG_MAX == -(LONG_MIN+1L), "");
_Static_assert(SCHAR_MAX == UCHAR_MAX/2, "");
_Static_assert(SHRT_MAX == USHRT_MAX/2, "");
_Static_assert(INT_MAX == UINT_MAX/2, "");
_Static_assert(LONG_MAX == ULONG_MAX/2, "");
_Static_assert(SCHAR_MIN == -SCHAR_MAX-1, "");
_Static_assert(SHRT_MIN == -SHRT_MAX-1, "");
_Static_assert(INT_MIN == -INT_MAX-1, "");
_Static_assert(LONG_MIN == -LONG_MAX-1L, "");
_Static_assert(UCHAR_MAX == (unsigned char)~0ULL, "");
_Static_assert(USHRT_MAX == (unsigned short)~0ULL, "");
_Static_assert(UINT_MAX == (unsigned int)~0ULL, "");
_Static_assert(ULONG_MAX == (unsigned long)~0ULL, "");
_Static_assert(MB_LEN_MAX >= 1, "");
_Static_assert(CHAR_BIT >= 8, "");
const bool char_is_signed = (char)-1 < (char)0;
_Static_assert(CHAR_MIN == (char_is_signed ? -CHAR_MAX-1 : 0), "");
_Static_assert(CHAR_MAX == (char_is_signed ? -(CHAR_MIN+1) : (char)~0ULL), "");
#if __STDC_VERSION__ >= 199901 || __cplusplus >= 201103L
_Static_assert(LLONG_MAX == -(LLONG_MIN+1LL), "");
_Static_assert(LLONG_MIN == -LLONG_MAX-1LL, "");
_Static_assert(ULLONG_MAX == (unsigned long long)~0ULL, "");
#else
int LLONG_MIN, LLONG_MAX, ULLONG_MAX; // Not defined.
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/altivec-intrin.c
|
// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -target-cpu power8 \
// RUN: -faltivec -verify %s
// Test special behavior of Altivec intrinsics in this file.
#include <altivec.h>
__attribute__((__aligned__(16))) float x[20];
int main()
{
vector unsigned char l = vec_lvsl (0, &x[1]); // expected-warning {{is deprecated: use assignment for unaligned little endian loads/stores}}
vector unsigned char r = vec_lvsr (0, &x[1]); // expected-warning {{is deprecated: use assignment for unaligned little endian loads/stores}}
}
// FIXME: As noted in ms-intrin.cpp, it would be nice if we didn't have to
// hard-code the line number from altivec.h here.
// [email protected]:* {{deprecated here}}
// [email protected]:* {{deprecated here}}
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/cpuid.c
|
// RUN: %clang_cc1 %s -ffreestanding -triple x86_64-apple-darwin -emit-llvm -o - | FileCheck %s --check-prefix=CHECK-64
// RUN: %clang_cc1 %s -ffreestanding -triple i386 -emit-llvm -o - | FileCheck %s --check-prefix=CHECK-32
#include <cpuid.h>
// CHECK-64: {{.*}} call { i32, i32, i32, i32 } asm " xchgq %rbx,${1:q}\0A cpuid\0A xchgq %rbx,${1:q}", "={ax},=r,={cx},={dx},0,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}})
// CHECK-64: {{.*}} call { i32, i32, i32, i32 } asm " xchgq %rbx,${1:q}\0A cpuid\0A xchgq %rbx,${1:q}", "={ax},=r,={cx},={dx},0,2,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}}, i32 %{{[a-z0-9]+}})
// CHECK-32: {{.*}} call { i32, i32, i32, i32 } asm "cpuid", "={ax},={bx},={cx},={dx},0,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}})
// CHECK-32: {{.*}} call { i32, i32, i32, i32 } asm "cpuid", "={ax},={bx},={cx},={dx},0,2,~{dirflag},~{fpsr},~{flags}"(i32 %{{[a-z0-9]+}}, i32 %{{[a-z0-9]+}})
unsigned eax0, ebx0, ecx0, edx0;
unsigned eax1, ebx1, ecx1, edx1;
void test_cpuid(unsigned level, unsigned count) {
__cpuid(level, eax1, ebx1, ecx1, edx1);
__cpuid_count(level, count, eax0, ebx0, ecx0, edx0);
}
|
0 |
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs/include/stdint.h
|
#ifndef STDINT_H
#define STDINT_H
#ifdef __INT32_TYPE__
typedef unsigned __INT32_TYPE__ uint32_t;
#endif
#ifdef __INT64_TYPE__
typedef unsigned __INT64_TYPE__ uint64_t;
#endif
#ifdef __INTPTR_TYPE__
typedef __INTPTR_TYPE__ intptr_t;
typedef unsigned __INTPTR_TYPE__ uintptr_t;
#else
#error Every target should have __INTPTR_TYPE__
#endif
#endif /* STDINT_H */
|
0 |
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs/include/stdlib.h
|
#pragma once
typedef __SIZE_TYPE__ size_t;
|
0 |
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs/include/math.h
|
#pragma once
|
0 |
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs/include/setjmp.h
|
#ifndef SETJMP_H
#define SETJMP_H
typedef struct {
int x[42];
} jmp_buf;
#endif
|
0 |
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs
|
repos/DirectXShaderCompiler/tools/clang/test/Headers/Inputs/include/complex.h
|
#pragma once
#define complex _Complex
|
0 |
repos/DirectXShaderCompiler/tools/clang/test
|
repos/DirectXShaderCompiler/tools/clang/test/SemaTemplate/crash-8204126.cpp
|
// RUN: %clang_cc1 -fsyntax-only -verify %s
struct A
{
template<int> template<typename T> friend void foo(T) {} // expected-error{{extraneous template parameter list}}
void bar() { foo(0); } // expected-error{{use of undeclared identifier 'foo'}}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.