Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / clang / unittests / StaticAnalyzer / SValTest.cpp
blobd8897b0f2183d76f6f9fe393f7a7796e5973b566
1 //===- unittests/StaticAnalyzer/SvalTest.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "CheckerRegistration.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/AST/DeclGroup.h"
14 #include "clang/AST/RecursiveASTVisitor.h"
15 #include "clang/AST/Stmt.h"
16 #include "clang/AST/Type.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
22 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
23 #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24 #include "clang/Testing/TestClangConfig.h"
25 #include "clang/Tooling/Tooling.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "gtest/gtest.h"
32 namespace clang {
34 // getType() tests include whole bunch of type comparisons,
35 // so when something is wrong, it's good to have gtest telling us
36 // what are those types.
37 LLVM_ATTRIBUTE_UNUSED std::ostream &operator<<(std::ostream &OS,
38 const QualType &T) {
39 return OS << T.getAsString();
42 LLVM_ATTRIBUTE_UNUSED std::ostream &operator<<(std::ostream &OS,
43 const CanQualType &T) {
44 return OS << QualType{T};
47 namespace ento {
48 namespace {
50 //===----------------------------------------------------------------------===//
51 // Testing framework implementation
52 //===----------------------------------------------------------------------===//
54 /// A simple map from variable names to symbolic values used to init them.
55 using SVals = llvm::StringMap<SVal>;
57 /// SValCollector is the barebone of all tests.
58 ///
59 /// It is implemented as a checker and reacts to binds, so we find
60 /// symbolic values of interest, and to end analysis, where we actually
61 /// can test whatever we gathered.
62 class SValCollector : public Checker<check::Bind, check::EndAnalysis> {
63 public:
64 void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const {
65 // Skip instantly if we finished testing.
66 // Also, we care only for binds happening in variable initializations.
67 if (Tested || !isa<DeclStmt>(S))
68 return;
70 if (const auto *VR = llvm::dyn_cast_or_null<VarRegion>(Loc.getAsRegion())) {
71 CollectedSVals[VR->getDescriptiveName(false)] = Val;
75 void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
76 ExprEngine &Engine) const {
77 if (!Tested) {
78 test(Engine, Engine.getContext());
79 Tested = true;
80 CollectedSVals.clear();
84 /// Helper function for tests to access bound symbolic values.
85 SVal getByName(StringRef Name) const { return CollectedSVals[Name]; }
87 private:
88 /// Entry point for tests.
89 virtual void test(ExprEngine &Engine, const ASTContext &Context) const = 0;
91 mutable bool Tested = false;
92 mutable SVals CollectedSVals;
95 static void expectSameSignAndBitWidth(QualType ExpectedTy, QualType ActualTy,
96 const ASTContext &Context) {
97 EXPECT_EQ(ExpectedTy->isUnsignedIntegerType(),
98 ActualTy->isUnsignedIntegerType());
99 EXPECT_EQ(Context.getTypeSize(ExpectedTy), Context.getTypeSize(ActualTy));
102 // Fixture class for parameterized SValTest
103 class SValTest : public testing::TestWithParam<TestClangConfig> {};
105 // SVAL_TEST is a combined way of providing a short code snippet and
106 // to test some programmatic predicates on symbolic values produced by the
107 // engine for the actual code.
109 // Each test has a NAME. One can think of it as a name for normal gtests.
111 // Each test should provide a CODE snippet. Code snippets might contain any
112 // valid C/C++, but have ONLY ONE defined function. There are no requirements
113 // about function's name or parameters. It can even be a class method. The
114 // body of the function must contain a set of variable declarations. Each
115 // variable declaration gets bound to a symbolic value, so for the following
116 // example:
118 // int x = <expr>;
120 // `x` will be bound to whatever symbolic value the engine produced for <expr>.
121 // LIVENESS and REASSIGNMENTS don't affect this binding.
123 // During the test the actual values can be accessed via `getByName` function,
124 // and, for the `x`-bound value, one must use "x" as its name.
126 // Example:
127 // SVAL_TEST(SimpleSValTest, R"(
128 // void foo() {
129 // int x = 42;
130 // })") {
131 // SVal X = getByName("x");
132 // EXPECT_TRUE(X.isConstant(42));
133 // }
134 #define SVAL_TEST(NAME, CODE) \
135 class NAME##SValCollector final : public SValCollector { \
136 public: \
137 void test(ExprEngine &Engine, const ASTContext &Context) const override; \
138 }; \
140 void add##NAME##SValCollector(AnalysisASTConsumer &AnalysisConsumer, \
141 AnalyzerOptions &AnOpts) { \
142 AnOpts.CheckersAndPackages = {{"test.##NAME##SValCollector", true}}; \
143 AnalysisConsumer.AddCheckerRegistrationFn([](CheckerRegistry &Registry) { \
144 Registry.addChecker<NAME##SValCollector>("test.##NAME##SValCollector", \
145 "Description", ""); \
146 }); \
149 TEST_P(SValTest, NAME) { \
150 EXPECT_TRUE(runCheckerOnCodeWithArgs<add##NAME##SValCollector>( \
151 CODE, GetParam().getCommandLineArgs())); \
153 void NAME##SValCollector::test(ExprEngine &Engine, \
154 const ASTContext &Context) const
156 //===----------------------------------------------------------------------===//
157 // Actual tests
158 //===----------------------------------------------------------------------===//
160 SVAL_TEST(GetConstType, R"(
161 void foo() {
162 int x = 42;
163 int *y = nullptr;
164 bool z = true;
165 })") {
166 SVal X = getByName("x");
167 ASSERT_FALSE(X.getType(Context).isNull());
168 EXPECT_EQ(Context.IntTy, X.getType(Context));
170 SVal Y = getByName("y");
171 ASSERT_FALSE(Y.getType(Context).isNull());
172 expectSameSignAndBitWidth(Context.getUIntPtrType(), Y.getType(Context),
173 Context);
175 SVal Z = getByName("z");
176 ASSERT_FALSE(Z.getType(Context).isNull());
177 EXPECT_EQ(Context.BoolTy, Z.getType(Context));
180 SVAL_TEST(GetLocAsIntType, R"(
181 void foo(int *x) {
182 long int a = (long long int)x;
183 unsigned b = (long long unsigned)&a;
184 int c = (long long int)nullptr;
185 })") {
186 SVal A = getByName("a");
187 ASSERT_FALSE(A.getType(Context).isNull());
189 // TODO: Turn it into signed long
190 expectSameSignAndBitWidth(Context.UnsignedLongTy, A.getType(Context),
191 Context);
193 SVal B = getByName("b");
194 ASSERT_FALSE(B.getType(Context).isNull());
195 expectSameSignAndBitWidth(Context.UnsignedIntTy, B.getType(Context), Context);
197 SVal C = getByName("c");
198 ASSERT_FALSE(C.getType(Context).isNull());
199 expectSameSignAndBitWidth(Context.IntTy, C.getType(Context), Context);
202 SVAL_TEST(GetSymExprType, R"(
203 void foo(int a, int b) {
204 int x = a;
205 int y = a + b;
206 long z = a;
207 })") {
208 QualType Int = Context.IntTy;
210 SVal X = getByName("x");
211 ASSERT_FALSE(X.getType(Context).isNull());
212 EXPECT_EQ(Int, X.getType(Context));
214 SVal Y = getByName("y");
215 ASSERT_FALSE(Y.getType(Context).isNull());
216 EXPECT_EQ(Int, Y.getType(Context));
218 // TODO: Change to Long when we support symbolic casts
219 SVal Z = getByName("z");
220 ASSERT_FALSE(Z.getType(Context).isNull());
221 EXPECT_EQ(Int, Z.getType(Context));
224 SVAL_TEST(GetPointerType, R"(
225 int *bar();
226 int &foobar();
227 struct Z {
228 int a;
229 int *b;
231 void foo(int x, int *y, Z z) {
232 int &a = x;
233 int &b = *y;
234 int &c = *bar();
235 int &d = foobar();
236 int &e = z.a;
237 int &f = *z.b;
238 })") {
239 QualType Int = Context.IntTy;
241 SVal A = getByName("a");
242 ASSERT_FALSE(A.getType(Context).isNull());
243 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
244 ASSERT_NE(APtrTy, nullptr);
245 EXPECT_EQ(Int, APtrTy->getPointeeType());
247 SVal B = getByName("b");
248 ASSERT_FALSE(B.getType(Context).isNull());
249 const auto *BPtrTy = dyn_cast<PointerType>(B.getType(Context));
250 ASSERT_NE(BPtrTy, nullptr);
251 EXPECT_EQ(Int, BPtrTy->getPointeeType());
253 SVal C = getByName("c");
254 ASSERT_FALSE(C.getType(Context).isNull());
255 const auto *CPtrTy = dyn_cast<PointerType>(C.getType(Context));
256 ASSERT_NE(CPtrTy, nullptr);
257 EXPECT_EQ(Int, CPtrTy->getPointeeType());
259 SVal D = getByName("d");
260 ASSERT_FALSE(D.getType(Context).isNull());
261 const auto *DRefTy = dyn_cast<LValueReferenceType>(D.getType(Context));
262 ASSERT_NE(DRefTy, nullptr);
263 EXPECT_EQ(Int, DRefTy->getPointeeType());
265 SVal E = getByName("e");
266 ASSERT_FALSE(E.getType(Context).isNull());
267 const auto *EPtrTy = dyn_cast<PointerType>(E.getType(Context));
268 ASSERT_NE(EPtrTy, nullptr);
269 EXPECT_EQ(Int, EPtrTy->getPointeeType());
271 SVal F = getByName("f");
272 ASSERT_FALSE(F.getType(Context).isNull());
273 const auto *FPtrTy = dyn_cast<PointerType>(F.getType(Context));
274 ASSERT_NE(FPtrTy, nullptr);
275 EXPECT_EQ(Int, FPtrTy->getPointeeType());
278 SVAL_TEST(GetCompoundType, R"(
279 struct TestStruct {
280 int a, b;
282 union TestUnion {
283 int a;
284 float b;
285 TestStruct c;
287 void foo(int x) {
288 int a[] = {1, x, 2};
289 TestStruct b = {x, 42};
290 TestUnion c = {42};
291 TestUnion d = {.c=b};
293 )") {
294 SVal A = getByName("a");
295 ASSERT_FALSE(A.getType(Context).isNull());
296 const auto *AArrayType = dyn_cast<ArrayType>(A.getType(Context));
297 ASSERT_NE(AArrayType, nullptr);
298 EXPECT_EQ(Context.IntTy, AArrayType->getElementType());
300 SVal B = getByName("b");
301 ASSERT_FALSE(B.getType(Context).isNull());
302 const auto *BRecordType = dyn_cast<RecordType>(B.getType(Context));
303 ASSERT_NE(BRecordType, nullptr);
304 EXPECT_EQ("TestStruct", BRecordType->getDecl()->getName());
306 SVal C = getByName("c");
307 ASSERT_FALSE(C.getType(Context).isNull());
308 const auto *CRecordType = dyn_cast<RecordType>(C.getType(Context));
309 ASSERT_NE(CRecordType, nullptr);
310 EXPECT_EQ("TestUnion", CRecordType->getDecl()->getName());
312 auto D = getByName("d").getAs<nonloc::CompoundVal>();
313 ASSERT_TRUE(D.has_value());
314 auto Begin = D->begin();
315 ASSERT_NE(D->end(), Begin);
316 ++Begin;
317 ASSERT_EQ(D->end(), Begin);
318 auto LD = D->begin()->getAs<nonloc::LazyCompoundVal>();
319 ASSERT_TRUE(LD.has_value());
320 auto LDT = LD->getType(Context);
321 ASSERT_FALSE(LDT.isNull());
322 const auto *DElaboratedType = dyn_cast<ElaboratedType>(LDT);
323 ASSERT_NE(DElaboratedType, nullptr);
324 const auto *DRecordType =
325 dyn_cast<RecordType>(DElaboratedType->getNamedType());
326 ASSERT_NE(DRecordType, nullptr);
327 EXPECT_EQ("TestStruct", DRecordType->getDecl()->getName());
330 SVAL_TEST(GetStringType, R"(
331 void foo() {
332 const char *a = "Hello, world!";
334 )") {
335 SVal A = getByName("a");
336 ASSERT_FALSE(A.getType(Context).isNull());
337 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
338 ASSERT_NE(APtrTy, nullptr);
339 EXPECT_EQ(Context.CharTy, APtrTy->getPointeeType());
342 SVAL_TEST(GetThisType, R"(
343 class TestClass {
344 void foo();
346 void TestClass::foo() {
347 const auto *a = this;
349 )") {
350 SVal A = getByName("a");
351 ASSERT_FALSE(A.getType(Context).isNull());
352 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
353 ASSERT_NE(APtrTy, nullptr);
354 const auto *ARecordType = dyn_cast<RecordType>(APtrTy->getPointeeType());
355 ASSERT_NE(ARecordType, nullptr);
356 EXPECT_EQ("TestClass", ARecordType->getDecl()->getName());
359 SVAL_TEST(GetFunctionPtrType, R"(
360 void bar();
361 void foo() {
362 auto *a = &bar;
364 )") {
365 SVal A = getByName("a");
366 ASSERT_FALSE(A.getType(Context).isNull());
367 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
368 ASSERT_NE(APtrTy, nullptr);
369 ASSERT_TRUE(isa<FunctionProtoType>(APtrTy->getPointeeType()));
372 SVAL_TEST(GetLabelType, R"(
373 void foo() {
374 entry:
375 void *a = &&entry;
376 char *b = (char *)&&entry;
378 )") {
379 SVal A = getByName("a");
380 ASSERT_FALSE(A.getType(Context).isNull());
381 EXPECT_EQ(Context.VoidPtrTy, A.getType(Context));
383 SVal B = getByName("a");
384 ASSERT_FALSE(B.getType(Context).isNull());
385 // TODO: Change to CharTy when we support symbolic casts
386 EXPECT_EQ(Context.VoidPtrTy, B.getType(Context));
389 std::vector<TestClangConfig> allTestClangConfigs() {
390 std::vector<TestClangConfig> all_configs;
391 TestClangConfig config;
392 config.Language = Lang_CXX14;
393 for (std::string target :
394 {"i686-pc-windows-msvc", "i686-apple-darwin9",
395 "x86_64-apple-darwin9", "x86_64-scei-ps4",
396 "x86_64-windows-msvc", "x86_64-unknown-linux",
397 "x86_64-apple-macosx", "x86_64-apple-ios14.0",
398 "wasm32-unknown-unknown", "wasm64-unknown-unknown",
399 "thumb-pc-win32", "sparc64-none-openbsd",
400 "sparc-none-none", "riscv64-unknown-linux",
401 "ppc64-windows-msvc", "powerpc-ibm-aix",
402 "powerpc64-ibm-aix", "s390x-ibm-zos",
403 "armv7-pc-windows-msvc", "aarch64-pc-windows-msvc",
404 "xcore-xmos-elf"}) {
405 config.Target = target;
406 all_configs.push_back(config);
408 return all_configs;
411 INSTANTIATE_TEST_SUITE_P(SValTests, SValTest,
412 testing::ValuesIn(allTestClangConfigs()));
414 } // namespace
415 } // namespace ento
416 } // namespace clang